diff --git a/AGENTS.md b/AGENTS.md index 9f35884..afb41fb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ Codex every prompt prompt recall into context: ten memories, the block naming the tool on demand mcp past_recall, the model's own recall, on a local MCP server every turn stop stamps the activity file, keeps one waiter on the session - compaction precompact sends the session so far + compaction precompact sends the sittings that closed; the one still open at most once an hour session end end makes sure a waiter runs detached idle the waiter: sends once Codex's process is gone, or after idleMinutes | @@ -43,6 +43,11 @@ plugins/past/ .github/workflows/check.yml every pull request: the script parses and runs, the manifests parse ``` +Credit refusals persist per operation in this host's state book, under `creditPauses`. +Each pause stores a connection fingerprint, required credits, and the next balance check time. +Use `updateState` for every change. Keep transcript hashes and pending sessions intact on a refusal. +`status --refresh` reads `/api/v1/usage` before it clears a pause. A write pause leaves recall available. + ## The script `bin/past-hook.mjs` is the whole plugin. The rules it keeps: @@ -65,7 +70,11 @@ plugins/past/ gone or the last turn is `idleMinutes` old (720 by default). `ensureWaiters` (`Stop`, `SessionStart`, `$past:status`) replaces a waiter that died or that an older `WAITER_VERSION` started (bump it whenever the waiter changes), and a replacement past its deadline sends at - once. `PreCompact` sends before the context is summarised. `SessionStart` sends the idle + once. `PreCompact` sends the sittings that closed since the last send, once each, and the one + still open only when the session's last send is an hour old (`COMPACTION_RESEND_MS`): a session + that never goes quiet compacts every few minutes, and sent whole at each one it was a new paid + revision every time, while the transcript on disk loses nothing. The held sitting keeps its old + hash in `state.json`, so it goes with the waiter's send. `SessionStart` sends the idle sessions that never reached past.dev, and `tidyPending` drops an open session that is gone, empty, or in past.dev unchanged and idle. Why `SessionEnd` sends nothing is under "Codex" below. 5. **A recall query is redacted like the content it would send.** It crosses the network exactly @@ -90,8 +99,8 @@ plugins/past/ 9. **What is sent for a session does not change by a byte.** The heading and the speaker names that `renderTranscript` prints are part of the content hash, and so are `SOURCE`, `AGENT` and `SPEAKER` at the top of the script: a changed byte makes `backfill` send every session already - in past.dev again, as a paid revision. `sittingId` and the cut (`sittingsOf`, `silenceMeter`) are - fixed too: changed, they move the boundaries of every session that grows afterwards, and the old + in past.dev again, as a paid revision. `sittingId` and the cut (`sittingsOf`, `silenceMeter`, the size + measured on the turns' own text) are fixed too: changed, they move the boundaries of every session that grows afterwards, and the old sittings stay in past.dev beside the new ones. 10. **`~/.past` is the person's alone.** The folder is `700` and every file in it is created `600`, never written open and narrowed afterwards. A plain-http `apiUrl` on another machine @@ -100,9 +109,14 @@ plugins/past/ decides which of two statements is the later from those times. A sitting starts at the first turn after the thread was silent for `sittingMinutes` (30 by default, 5 at least), whoever speaks; tool calls and their output count as activity, so a prompt stays with its reply while - Codex works. Each sitting is one data point timed at its first turn, and every changed sitting - goes in one `/api/v1/ingest/batch` call. `state.json` pins `sittingMinutes` per session at its - first send, so a changed value never moves the boundaries of a session already in past.dev. + Codex works. One also starts once the sitting so far holds `sittingKilobytes` of prose (50 by + default, 10 at least), measured on the turns' own text and only once Codex has answered, so a + thread that never goes quiet is cut all the same and a prompt is never parted from its first + answer. Each sitting is one data point timed at its first turn, and every changed sitting + goes in one `/api/v1/ingest/batch` call. `state.json` pins `sittingMinutes` and + `sittingKilobytes` per session at its first send, so a changed value never moves the boundaries + of a session already in past.dev; one sent in sittings before the size existed is pinned to no + size (`0`). 12. **The product is written past.dev.** Every sentence a person reads says past.dev: the READMEs, the manifest's display names, the skills' text, what a mode prints. Identifiers keep `past`: diff --git a/README.md b/README.md index 406971d..1bbafa0 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ session opens recall what past.dev knows about this project ──► in every prompt recall what past.dev knows about this prompt ──► into context any time Codex asks past.dev itself, with past_recall ──► into context every reply nothing is sent; the session is marked active -compaction the session so far is sent, before its detail is summarised away +compaction the sittings that closed are sent; the one still open at most once an hour session over the session is sent: its Codex process exited, or it was quiet for 12 hours ``` @@ -88,7 +88,7 @@ after 12 hours without a new turn. The next session to start also sends any earl reached past.dev, which covers a crash or a machine that slept. **A session is sent in sittings.** Where a thread went quiet for 30 minutes, the next turn starts a -new sitting. Each sitting is dated at its own first turn, so a decision made on the third day of a +new sitting; so does the next one after 50 KB of prose, once Codex has answered. Each sitting is dated at its own first turn, so a decision made on the third day of a long thread is remembered on that day, and past.dev can tell which of two statements came later. A session that continues sends its last sitting and the new ones again, nothing earlier. @@ -142,8 +142,9 @@ slug from the console's **Audiences** page. `$past:connect --audience project` w `~/.past/config.json` holds the connection and a few switches: `recall` and `ingest` turn either half off, `idleMinutes` (720) is how long a session stays quiet before it is sent, -`sittingMinutes` (30) is how long a pause starts a new sitting, and `deny` lists paths whose -sessions are never read. `PAST_API_KEY`, `PAST_IDENTITY` and `PAST_API_URL` override the file. +`sittingMinutes` (30) is how long a pause starts a new sitting, `sittingKilobytes` (50) how much +prose does, and `deny` lists paths whose sessions are never read. `PAST_API_KEY`, `PAST_IDENTITY` +and `PAST_API_URL` override the file. Each setting is described in the [plugin's README](plugins/past/README.md#configuration). For a self-hosted past.dev, pass your deployment's URL as the third argument of `$past:connect`. Use diff --git a/plugins/past/.codex-plugin/plugin.json b/plugins/past/.codex-plugin/plugin.json index b012e0e..80bd014 100644 --- a/plugins/past/.codex-plugin/plugin.json +++ b/plugins/past/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "past", - "version": "0.2.0", + "version": "0.3.0", "description": "Your Codex sessions become memory, and every session starts briefed.", "author": { "name": "past.dev", "url": "https://past.dev" }, "homepage": "https://github.com/pastdotdev/codex-plugin", diff --git a/plugins/past/README.md b/plugins/past/README.md index c40a9bc..1d00e8c 100644 --- a/plugins/past/README.md +++ b/plugins/past/README.md @@ -49,19 +49,22 @@ is nothing to do: `$past:status` shows it. | `SessionStart` | a session opens | recalls this project's history and puts it in context | | `UserPromptSubmit` | every prompt | recalls the ten memories closest to the prompt and puts them in context | | `Stop` | after each reply | stamps the session's activity; sends nothing itself | -| `PreCompact` | the context is about to be compacted | sends the session so far, before the detail is summarised away | +| `PreCompact` | the context is about to be compacted | sends the sittings that closed since the last send; the one still open at most once an hour | | `SessionEnd` | Codex unloads a session | makes sure the session will be sent; sends nothing itself | **When a session is sent.** Codex says a session ended even when it only went quiet for half an hour, so the plugin does not send on that. A session is sent within a minute after the Codex process that ran it exits (the end of a `codex exec` run, the desktop app when you quit it), or -after 12 hours without a new turn (`idleMinutes`). It is sent before a compaction too. +after 12 hours without a new turn (`idleMinutes`). Before a compaction, the sittings that closed +since the last send go too, and the one still open at most once an hour. `SessionStart` also sends any earlier session that never reached past.dev and has gone idle, which is what covers a crash or a machine that slept. **A session is sent in sittings.** A new sitting starts where the session went quiet for 30 -minutes (`sittingMinutes`): nobody wrote and Codex ran nothing. Each sitting is dated at its own +minutes (`sittingMinutes`): nobody wrote and Codex ran nothing. One also starts once the sitting +so far holds 50 KB of prose (`sittingKilobytes`), after Codex's reply, so a thread that never pauses +is cut all the same. Each sitting is dated at its own first turn, and what past.dev remembers takes the date of the sitting it came from, so something said on the third day of a thread that ran for three days is dated that day. A prompt and its reply stay together while Codex works on it, however long. When a session continues, only its last sitting @@ -122,6 +125,7 @@ narrows it to an audience from the console; `--audience project` widens it back. "ingest": true, "idleMinutes": 720, "sittingMinutes": 30, + "sittingKilobytes": 50, "deny": ["/Users/you/clients/acme"] } ``` @@ -133,6 +137,9 @@ narrows it to an audience from the console; `--audience project` widens it back. - `sittingMinutes` is how long a session stays quiet before what follows starts a new sitting (30 by default, 5 at least). Shorter dates what past.dev remembers more closely, in more and smaller data points. A session keeps the length it was first sent with. +- `sittingKilobytes` is how much prose a sitting holds before the next turn starts a new one (50 + by default, 10 at least), the cut waiting for Codex's reply. A session keeps the size it was + first sent with. - `deny` holds path fragments. A session whose working directory matches one is ignored completely — nothing is read and nothing is sent. - `PAST_API_KEY`, `PAST_IDENTITY` and `PAST_API_URL` override the file. @@ -164,3 +171,12 @@ console. ## License MIT — see [LICENSE](LICENSE). + +## Credits + +After `402 out-of-credits`, the plugin pauses the refused operation and keeps unsent data locally. +A write refusal does not pause recall. A recall refusal pauses recall separately. +On later calls, the plugin checks the balance at most once per five minutes for each paused operation. +The plugin resumes when the balance covers the refused call. The server checks the balance again for each request. +Run `$past:status --refresh` after you add credits to check the balance now. +A new API key or API URL starts with no pause from the previous connection. diff --git a/plugins/past/bin/past-hook.mjs b/plugins/past/bin/past-hook.mjs index e3f526c..4f278ca 100755 --- a/plugins/past/bin/past-hook.mjs +++ b/plugins/past/bin/past-hook.mjs @@ -30,9 +30,19 @@ const DEFAULT_IDLE_MINUTES = 720; // 12 hours // minutes nearly every sitting would be one exchange, so a smaller value is read as five. const DEFAULT_SITTING_MINUTES = 30; const MIN_SITTING_MINUTES = 5; +// A sitting is also closed where it holds this much prose. An agent that runs for hours without a +// pause never goes quiet, so its session was one sitting, and sent again at every compaction as it +// grew it was a new paid revision of the whole every few minutes. The cut falls between two of the +// agent's turns or before the developer's next prompt, never between a prompt and its first answer. +const DEFAULT_SITTING_KILOBYTES = 50; +const MIN_SITTING_KILOBYTES = 10; +// At a compaction the sitting still open is sent again only when the session's last send is older +// than this. The transcript on disk loses nothing at a compaction, so the open sitting can wait for +// the session to end or go idle; the hour bounds what a crash in between could lose. +const COMPACTION_RESEND_MS = 60 * 60000; const DEFAULT_API_URL = 'https://api.past.dev'; const MARKER = '=== past · recalled from memory ==='; -const VERSION = '0.2.0'; +const VERSION = '0.3.0'; // ---------------------------------------------------------------------------------------- Codex @@ -113,6 +123,8 @@ function loadConfig() { idleMinutes: Number(file.idleMinutes) > 0 ? Number(file.idleMinutes) : DEFAULT_IDLE_MINUTES, sittingMinutes: Number(file.sittingMinutes) > 0 ? Math.max(MIN_SITTING_MINUTES, Number(file.sittingMinutes)) : DEFAULT_SITTING_MINUTES, + sittingKilobytes: Number(file.sittingKilobytes) > 0 + ? Math.max(MIN_SITTING_KILOBYTES, Number(file.sittingKilobytes)) : DEFAULT_SITTING_KILOBYTES, // An audience slug from the console; empty means the whole project sees what is sent. audience: typeof file.audience === 'string' ? file.audience.trim() : '', }; @@ -302,17 +314,35 @@ function silenceMeter() { // for `sittingMinutes`, whoever speaks: a resumed session, or a permission granted the next // morning, can start with the agent rather than the person. Each sitting is a data point timed at // its own first turn. A memory takes the time of the data point it was drawn from, so one said on -// the third day of a session that ran for three days is dated that day, not the first. A prompt is -// never parted from its answer while the agent works on it. A session only grows at its end, so a +// the third day of a session that ran for three days is dated that day, not the first. A new +// sitting also starts once the one so far holds `sittingKilobytes` of prose, so a session that +// never goes quiet is cut all the same; that cut waits for the agent to have answered, so a prompt +// is never parted from its first answer, and falls between two of the agent's turns where it +// works on without the person. Each sitting is placed on the branch current at its first turn, +// where the transcript records one per turn, and the whole session keeps its last: a switch later +// in the session then changes no sitting already closed. A session only grows at its end, so a // sitting never changes once the next one has begun, and a session that resumes sends its last // sitting again, not the whole. -function sittingsOf(parsed, minutes) { +function sittingsOf(parsed, minutes, kilobytes) { const sittings = []; + let held = 0; + let previous = null; for (const turn of parsed.turns) { - if (!sittings.length || (turn.at && turn.quiet >= minutes * 60000)) { - sittings.push({ ...parsed, turns: [], firstAt: sittings.length ? turn.at : parsed.firstAt }); + const quiet = turn.quiet >= minutes * 60000; + // Measured on the turns' own text, so the cut moves with neither the heading nor the redaction. + const full = kilobytes > 0 && held >= kilobytes * 1024 && previous !== null && previous.role !== 'user'; + if (!sittings.length || (turn.at && (quiet || full))) { + sittings.push({ + ...parsed, + turns: [], + firstAt: sittings.length ? turn.at : parsed.firstAt, + branch: turn.branch || parsed.branch, + }); + held = 0; } sittings[sittings.length - 1].turns.push(turn); + held += Buffer.byteLength(turn.text); + previous = turn; } return sittings; } @@ -329,19 +359,22 @@ const hashOf = (text) => createHash('sha256').update(text).digest('hex'); * state.json knows a sent session by the hash of its whole rendering (`hash`), which is what still * recognises one sent whole before sittings existed, and by one hash per sitting (`sittings`). A * session sent whole that grew since has no sitting hashes, so all of its sittings go. A session - * keeps the sitting length it was first sent with (`sittingMinutes`): a new value in the config - * applies to the sessions sent after it, and the boundaries of one already in past.dev never move. + * keeps the sitting length and size it was first sent with (`sittingMinutes`, `sittingKilobytes`): + * a new value in the config applies to the sessions sent after it, and the boundaries of one + * already in past.dev never move. One sent in sittings before the size existed keeps no size at all. */ function planSend(parsed, context, sent, config) { - const minutes = (sent && sent.sittingMinutes) || config.sittingMinutes; - const sittings = sittingsOf(parsed, minutes).map((sitting, index) => { + const pinned = Boolean(sent && sent.sittingMinutes); + const minutes = pinned ? sent.sittingMinutes : config.sittingMinutes; + const kilobytes = pinned ? (Number(sent.sittingKilobytes) || 0) : config.sittingKilobytes; + const sittings = sittingsOf(parsed, minutes, kilobytes).map((sitting, index) => { const content = renderTranscript(sitting, context); return { index, sitting, content, hash: hashOf(content), bytes: Buffer.byteLength(content) }; }); const whole = hashOf(renderTranscript(parsed, context)); - if (sent && sent.hash === whole) return { whole, minutes, sittings, changed: [] }; const known = sent && Array.isArray(sent.sittings) ? sent.sittings : []; - return { whole, minutes, sittings, changed: sittings.filter((part) => known[part.index] !== part.hash) }; + if (sent && sent.hash === whole) return { whole, minutes, kilobytes, sittings, known, changed: [] }; + return { whole, minutes, kilobytes, sittings, known, changed: sittings.filter((part) => known[part.index] !== part.hash) }; } // Which project, branch and directory a session belongs to. A Codex transcript says so itself, and @@ -414,8 +447,51 @@ async function request(url, options) { // Every call is time-boxed. A slow network must never hold a prompt, so the caller's budget is // the hook's budget, and an expired call simply returns nothing. +// Each operation pauses independently. Free reads remain available after a write refusal. +const CREDIT_CHECK_MS = 5 * 60 * 1000; +const creditAccount = (config) => hashOf(`${config.apiUrl}\n${config.apiKey}`); +function creditPause(config, operation) { + const pauses = book(loadState()).creditPauses; + const pause = pauses && pauses[operation]; + return pause && pause.account === creditAccount(config) ? pause : null; +} + +async function checkCredits(config, operation, timeoutMs, force = false) { + const pause = creditPause(config, operation); + if (!pause) return true; + const now = Date.now(); + let claimed = false; + updateState((fresh) => { + const own = book(fresh); + const current = own.creditPauses && own.creditPauses[operation]; + if (current && current.account === pause.account && (force || current.nextCheck <= now)) { + current.nextCheck = now + CREDIT_CHECK_MS; + claimed = true; + } + }); + if (!claimed) return false; + const usage = await api(config, '/api/v1/usage', null, timeoutMs, 'GET'); + if (!usage || usage.error) return false; + const available = usage.metered === false || (usage.balance && + typeof usage.balance.left === 'number' && usage.balance.left >= pause.needed); + if (!available) return false; + updateState((fresh) => { + const own = book(fresh); + const current = own.creditPauses && own.creditPauses[operation]; + if (current && current.account === pause.account && current.at === pause.at) + delete own.creditPauses[operation]; + }); + return !creditPause(config, operation); +} + async function api(config, path, body, timeoutMs, method = 'POST') { if (!config.apiKey) return null; + const operation = method === 'POST' && ['/api/v1/ingest', '/api/v1/ingest/batch'].includes(path) ? 'ingest' + : method === 'POST' && path === '/api/v1/recall' ? 'recall' : null; + const started = Date.now(); + if (operation && !await checkCredits(config, operation, Math.min(timeoutMs, 2000))) + return { error: 402, body: JSON.stringify({ code: 'out-of-credits' }), paused: true }; + timeoutMs = Math.max(1, timeoutMs - (Date.now() - started)); const control = new AbortController(); const timer = setTimeout(() => control.abort(), timeoutMs); try { @@ -429,7 +505,23 @@ async function api(config, path, body, timeoutMs, method = 'POST') { body: body === null ? undefined : JSON.stringify(body), signal: control.signal, }); - if (!response.ok) return { error: response.status, body: await response.text().catch(() => '') }; + if (!response.ok) { + const text = await response.text().catch(() => ''); + let refusal; + try { refusal = JSON.parse(text); } catch { /* Keep the HTTP error. */ } + if (operation && response.status === 402 && refusal && refusal.code === 'out-of-credits') { + const needed = refusal.data && refusal.data.creditsNeeded; + updateState((fresh) => { + const own = book(fresh); + if (!own.creditPauses) own.creditPauses = {}; + own.creditPauses[operation] = { + account: creditAccount(config), at: Date.now(), nextCheck: Date.now() + CREDIT_CHECK_MS, + needed: typeof needed === 'number' && needed > 0 ? needed : 1, + }; + }); + } + return { error: response.status, body: text }; + } return await response.json().catch(() => ({})); } catch { return null; @@ -608,7 +700,7 @@ function modeMcp() { return new Promise((done) => lines.on('close', () => Promise.all([...inflight]).then(done))); } -async function ingestSession(config, state, sessionId, transcriptPath, context, {stillRunning = false} = {}) { +async function ingestSession(config, state, sessionId, transcriptPath, context, {stillRunning = false, compacting = false} = {}) { if (!config.ingest || !config.apiKey) return { skipped: 'not configured' }; const parsed = readTranscript(transcriptOf(sessionId, transcriptPath)); const { sessions, pending } = book(state); @@ -619,39 +711,51 @@ async function ingestSession(config, state, sessionId, transcriptPath, context, return { skipped: 'nothing to send' }; } - const plan = planSend(parsed, context, sessions[sessionId], config); + const before = sessions[sessionId]; + const plan = planSend(parsed, context, before, config); + // A compaction sends the sittings that closed since the last send, once each, and holds the one + // still open unless the session's last send is an hour old: that sitting grows at every turn, + // and sent at every compaction it was a new paid revision of itself every few minutes. Its turns + // are in the file whatever the context loses, and go when the session ends or goes idle. + const last = plan.sittings[plan.sittings.length - 1]; + const held = compacting && plan.changed.includes(last) && before && before.sentAt + && Date.now() - Date.parse(before.sentAt) < COMPACTION_RESEND_MS ? last : null; + const parts = held ? plan.changed.filter((part) => part !== held) : plan.changed; // The server charges nothing for an unchanged re-send, but the call still spends a request // from the key's per-minute budget. The hashes skip it, and they live here on purpose. - if (!plan.changed.length) { + if (!parts.length) { // Unchanged still closes the session out. Without this it stays pending, and every later // SessionStart re-reads and re-hashes a transcript that is already in past.dev. if (!stillRunning && pending[sessionId]) updateState((fresh) => { delete book(fresh).pending[sessionId]; }, state); - return { skipped: 'unchanged' }; + return { skipped: held ? 'held' : 'unchanged' }; } const place = placeOf(parsed, context); - const label = `${AGENT} · ${place.project}${place.branch ? ` · ${place.branch}` : ''}`; // One call for every sitting that changed, so a session spends one request however long it ran. + // Each sitting is labelled with its own branch, the one its content is rendered with. const result = await api(config, '/api/v1/ingest/batch', { - items: plan.changed.map((part) => ({ - id: sittingId(sessionId, part.index), - content: part.content, - label, - timestamp: part.sitting.firstAt, - identity: config.identity || undefined, - audience: config.audience && config.audience !== 'project' ? config.audience : undefined, - metadata: { - source: SOURCE, - client: SOURCE, - conversationId: sessionId, - sessionId, - project: place.project, - cwd: place.cwd, - gitBranch: place.branch || '', - sitting: part.index + 1, - turns: part.sitting.turns.length, - }, - })), + items: parts.map((part) => { + const branch = placeOf(part.sitting, context).branch; + return { + id: sittingId(sessionId, part.index), + content: part.content, + label: `${AGENT} · ${place.project}${branch ? ` · ${branch}` : ''}`, + timestamp: part.sitting.firstAt, + identity: config.identity || undefined, + audience: config.audience && config.audience !== 'project' ? config.audience : undefined, + metadata: { + source: SOURCE, + client: SOURCE, + conversationId: sessionId, + sessionId, + project: place.project, + cwd: place.cwd, + gitBranch: branch || '', + sitting: part.index + 1, + turns: part.sitting.turns.length, + }, + }; + }), }, 30000); if (!result || result.error) { @@ -662,10 +766,15 @@ async function ingestSession(config, state, sessionId, transcriptPath, context, updateState((fresh) => { book(fresh).lastError = lastError; }, state); return { error: result ? result.error : 'unreachable', code }; } + // A held sitting keeps the hash it was last sent with, or none, so it goes at the next send, and + // the whole hash is written only once the whole session is in past.dev. + const hashes = plan.sittings.map((part) => part.hash); + if (held) { if (plan.known[held.index]) hashes[held.index] = plan.known[held.index]; else hashes.pop(); } const sent = { - hash: plan.whole, - sittings: plan.sittings.map((part) => part.hash), + hash: held ? before.hash : plan.whole, + sittings: hashes, sittingMinutes: plan.minutes, + sittingKilobytes: plan.kilobytes, sentAt: new Date().toISOString(), turns: parsed.turns.length, }; @@ -680,9 +789,10 @@ async function ingestSession(config, state, sessionId, transcriptPath, context, ok: true, turns: parsed.turns.length, sittings: plan.sittings.length, - sent: plan.changed.length, - bytes: plan.changed.reduce((sum, part) => sum + part.bytes, 0), - credits: creditsOf(plan.changed), + sent: parts.length, + held: held ? 1 : 0, + bytes: parts.reduce((sum, part) => sum + part.bytes, 0), + credits: creditsOf(parts), }; } @@ -790,9 +900,11 @@ function recentPrompts(transcriptPath) { /** * Compaction is the one moment the context really does reset: everything before the boundary - * becomes a lossy summary. past.dev holds the prose, so the session is flushed here — durable before - * the detail goes, and recallable by the SessionStart that fires straight after with source - * `compact`. It writes and says nothing. + * becomes a lossy summary, while the transcript on disk keeps every turn. So the send here serves + * the SessionStart that fires straight after with source `compact`, and a crash before the + * session's own send, at a bounded price: the sittings that closed since the last send go, once + * each, and the one still open goes at most once an hour (`COMPACTION_RESEND_MS`); it stays in the + * file, and goes when the session ends or goes idle. This hook writes and says nothing. */ async function modePreCompact(config) { const input = await readStdin(); @@ -807,7 +919,7 @@ async function modePreCompact(config) { input.session_id, transcript, {project: basename(cwd), cwd, branch: ''}, - {stillRunning: true}, + {stillRunning: true, compacting: true}, ); } @@ -844,8 +956,10 @@ function clearActivity(sessionId) { try { unlinkSync(activityPath(sessionId)); } // Bumped whenever the waiter's logic changes: a waiter started by an older version is replaced, // because it is a long-lived process still running the code it was started with. 4: sessions are // sent in sittings, and a waiter of 3 would send an open session whole. 5: sittings are cut where -// the transcript went quiet, for as long as the config says. -const WAITER_VERSION = 5; +// the transcript went quiet, for as long as the config says. 6: sittings are also cut by size, and +// a waiter of 5 would cut a session the hooks already sent by size along other lines, and send its +// sittings again under shifted ids. +const WAITER_VERSION = 6; // The waiter never sleeps longer than this in one go. A timer does not count the time the machine // is asleep, so one long timer set for "in twelve hours" fires hours late after a night with the // lid closed. Short slices checked against the wall clock send within a minute of waking instead. @@ -1351,13 +1465,18 @@ async function modeSearch(config, argv) { if (!config.identity) { console.log(`No identity set. Run ${commandOf('connect')} to set one.`); return; } if (OFFLINE) { console.log(NEEDS_OUTSIDE); return; } const memories = await recall(config, query, 8, 15000); + if (creditPause(config, 'recall')) { console.log(`Recall paused: insufficient credits. Run ${commandOf('status')} --refresh after you add credits.`); return; } if (!memories.length) { console.log('Nothing in past.dev matches that yet.'); return; } for (const [index, memory] of memories.entries()) { console.log(`[${index + 1}] ${(memory.at || '').slice(0, 10)} — ${memory.content.replace(/\s+/g, ' ').trim()}`); } } -function modeStatus(config) { +async function modeStatus(config, argv) { + if (argv.includes('--refresh')) { + for (const operation of ['ingest', 'recall']) + await checkCredits(config, operation, 2000, true); + } // Heals before it reports: a session left overdue by a dead or outdated waiter is sent now. // Inside a sandbox it only reports: a waiter started there could never reach past.dev. if (!SANDBOXED) { try { ensureWaiters(); } catch { /* status still reports */ } } @@ -1373,7 +1492,8 @@ function modeStatus(config) { `Recall ${config.recall && config.identity ? 'on' : 'off'}`, `Ingest ${config.ingest && config.apiKey ? 'on' : 'off'}`, `Audience ${config.audience && config.audience !== 'project' ? config.audience : 'whole project'}`, - `Sittings a new one after ${config.sittingMinutes} min of quiet (sittingMinutes; a session keeps the length it was first sent with)`, + `Sittings a new one after ${config.sittingMinutes} min of quiet or ${config.sittingKilobytes} KB of prose ` + + '(sittingMinutes, sittingKilobytes; a session keeps the values it was first sent with)', `Sessions ${sent} sent · ${open.length} open` + (unsent ? ` (${unsent} not sent yet)` : ''), ]; @@ -1396,6 +1516,10 @@ function modeStatus(config) { } lines.push(`Idle timer ${parts.join('; ')}`); } + for (const operation of ['ingest', 'recall']) { + if (creditPause(config, operation)) + lines.push(`Credits ${operation} paused. Unsent data stays local. Run ${commandOf('status')} --refresh after you add credits.`); + } const { lastError } = book(state); if (lastError) { const at = new Date(lastError.at); @@ -1521,7 +1645,7 @@ try { else if (mode === 'stop') await modeStop(config); else if (mode === 'idle') await modeIdle(config, argv); else if (mode === 'precompact') await modePreCompact(config); - else if (mode === 'status') modeStatus(config); + else if (mode === 'status') await modeStatus(config, argv); else if (mode === 'cut') modeCut(config, argv); else if (mode === 'search') await modeSearch(config, argv); else if (mode === 'backfill') await modeBackfill(config, argv); diff --git a/plugins/past/skills/cut/SKILL.md b/plugins/past/skills/cut/SKILL.md index 39e50a3..7da913e 100644 --- a/plugins/past/skills/cut/SKILL.md +++ b/plugins/past/skills/cut/SKILL.md @@ -25,7 +25,7 @@ Run it from this skill's folder: the path is relative to it. It only reads, so i Show the user the result. This is what leaves the machine: the prompts and the replies, with secrets redacted. Tool output, file contents, diffs and what Codex or a hook injected are not in it. A session is sent in sittings, one data point each: a new one starts where the conversation -went quiet for `sittingMinutes` (30 by default), and each begins with its own heading. The first line names the +went quiet for `sittingMinutes` (30 by default) or past `sittingKilobytes` of prose (50 by default), and each begins with its own heading. The first line names the session and its sittings, and reports the size on disk, the size sent and what sending it now costs. The last line says what happens next. Relay that line as it is. diff --git a/plugins/past/skills/status/SKILL.md b/plugins/past/skills/status/SKILL.md index 96f2150..fba9e7d 100644 --- a/plugins/past/skills/status/SKILL.md +++ b/plugins/past/skills/status/SKILL.md @@ -20,3 +20,6 @@ If the output says the hooks have never run in Codex, that is the reason nothing sent: Codex runs no hook that a person has not trusted. Tell the user where to trust the five past.dev hooks: `/hooks` in a terminal session, or the past.dev plugin's page in the ChatGPT desktop app, where **Trust all** does it. Then they send one prompt and ask for the status again. + +If the user asks to check credits now, add `--refresh` to the status command. +This option reads the balance from the API and clears a credit pause only when the balance is sufficient.