notesoup 0.57.2 → 0.57.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/plugins/pi/budget.d.ts +2 -1
- package/dist/plugins/pi/budget.js +13 -2
- package/dist/plugins/pi/reset/lifecycle.d.ts +7 -6
- package/dist/plugins/pi/reset/lifecycle.js +55 -35
- package/dist/plugins/pi/runtime.js +2 -1
- package/dist/src/budget/text.d.ts +0 -4
- package/dist/src/budget/text.js +10 -9
- package/dist/src/notes/store.d.ts +1 -1
- package/dist/src/notes/store.js +3 -1
- package/dist/test/agent-loop.test.js +84 -14
- package/dist/test/model-facing-text.test.js +10 -5
- package/dist/test/notes-query-namespaces.test.js +7 -3
- package/dist/test/notes.integration.test.js +1 -1
- package/dist/test/reset-lifecycle.test.js +14 -48
- package/docs/architecture.md +1 -1
- package/docs/notes-library.md +1 -1
- package/docs/reset-lifecycle.md +7 -7
- package/package.json +1 -1
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +11 -5
- package/plugins/codex/dist/codex/notesoup.js +1 -0
- package/plugins/pi/budget.ts +12 -2
- package/plugins/pi/reset/lifecycle.ts +54 -37
- package/plugins/pi/runtime.ts +1 -1
- package/src/budget/text.ts +10 -10
- package/src/notes/store.ts +3 -2
|
@@ -38,7 +38,9 @@ test("default spellings stay local while explicit ** lists and searches each not
|
|
|
38
38
|
}
|
|
39
39
|
const rows = await notes.list({ glob: "**" });
|
|
40
40
|
assert.deepEqual(addresses(rows), all);
|
|
41
|
+
assert.deepEqual(addresses(await notes.list({ glob: "*" })), all);
|
|
41
42
|
assert.deepEqual(addresses(await notes.search(["needle"], { glob: "**" })), all);
|
|
43
|
+
assert.deepEqual(addresses(await notes.search(["needle"], { glob: "*" })), all);
|
|
42
44
|
assert.equal(new Set(rows.map(row => row.address)).size, rows.length);
|
|
43
45
|
for (const row of rows)
|
|
44
46
|
assert.equal((await notes.read(row.address))?.body.startsWith("needle"), true, "every result is a real readable address");
|
|
@@ -48,14 +50,16 @@ test("default spellings stay local while explicit ** lists and searches each not
|
|
|
48
50
|
assert.deepEqual(addresses(await notes.list({ glob: "@model/**" })), ["@model/shared.md"]);
|
|
49
51
|
assert.deepEqual(addresses(await notes.list({ glob: `@projects/${identity.projectKey}/**` })), [`@projects/${identity.projectKey}/shared.md`], "explicit current project stays a named read-only address");
|
|
50
52
|
});
|
|
51
|
-
test("
|
|
53
|
+
test("slashless patterns match filenames at any depth while slash-qualified bare paths match the current session", async (t) => {
|
|
52
54
|
const { notes, identity, foreignIdentity, foreign, all } = await populate(t);
|
|
53
55
|
await notes.write("deep/nested.md", "needle nested");
|
|
54
56
|
await foreign.write("deep/nested.md", "needle elsewhere");
|
|
55
57
|
await foreign.write("only-foreign.md", "needle foreign only");
|
|
56
|
-
|
|
58
|
+
const everyNote = [...all, "deep/nested.md", `@sessions/${foreignIdentity.sessionId}/deep/nested.md`, `@sessions/${foreignIdentity.sessionId}/only-foreign.md`].sort();
|
|
59
|
+
assert.deepEqual(addresses(await notes.list({ glob: "*.md" })), everyNote);
|
|
60
|
+
assert.deepEqual(addresses(await notes.list({ glob: "nested.md" })), [`@sessions/${foreignIdentity.sessionId}/deep/nested.md`, "deep/nested.md"]);
|
|
57
61
|
assert.deepEqual(addresses(await notes.list({ glob: "deep/**" })), ["deep/nested.md"]);
|
|
58
|
-
assert.deepEqual(await notes.search(["needle"], { glob: "only-foreign.md" }), []
|
|
62
|
+
assert.deepEqual(addresses(await notes.search(["needle"], { glob: "only-foreign.md" })), [`@sessions/${foreignIdentity.sessionId}/only-foreign.md`]);
|
|
59
63
|
assert.deepEqual(addresses(await notes.list({ glob: "**/shared.md" })), all);
|
|
60
64
|
assert.deepEqual(addresses(await notes.list({ glob: "@*/**/shared.md" })), all, "a wildcard head is not mistaken for an unknown reserved head");
|
|
61
65
|
assert.deepEqual(addresses(await notes.list({ glob: `@sessions/${identity.sessionId}/**` })), [
|
|
@@ -153,7 +153,7 @@ test("notes_list is most-recently-updated first across merged scopes", async ()
|
|
|
153
153
|
// A same-path pair in two scopes keeps both rows; equal timestamps tie-break by scope name.
|
|
154
154
|
put("human", "a.md", base + 10);
|
|
155
155
|
assert.deepEqual((await files({})).filter((file) => file.address.endsWith("a.md")).map((file) => file.address), ["@human/a.md", "a.md"], "equal timestamps tie-break by full address");
|
|
156
|
-
assert.deepEqual((await files({ glob: "*.md" })).map((file) => file.address), ["a.md", "b.md"], "a
|
|
156
|
+
assert.deepEqual((await files({ glob: "*.md" })).map((file) => file.address), ["@human/e.md", "@human/a.md", "a.md", "b.md", "@project/c.md"], "a slashless glob matches filenames across notebooks");
|
|
157
157
|
});
|
|
158
158
|
test("notes are real files that persist across sessions and round-trip Unicode", async () => {
|
|
159
159
|
const original = manager();
|
|
@@ -210,31 +210,6 @@ test("public reset boundary drafts one marker, one boot, and one continuation af
|
|
|
210
210
|
assert.deepEqual(branch.filter((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE).map((entry) => entry.type === "custom" ? entry.data : undefined), [{ windowId, origin: "normal" }], "the boundary records the model's own call");
|
|
211
211
|
assert.equal(branch.filter((entry) => entry.type === "custom_message" && entry.customType === BOOT_TYPE).length, 1);
|
|
212
212
|
});
|
|
213
|
-
test("hard-reserve reset carries original text and images and continues", async () => {
|
|
214
|
-
const sessionManager = Manager.inMemory("/private/tmp/notesoup-hard-reserve-carry-test");
|
|
215
|
-
const handlers = new Map();
|
|
216
|
-
const api = { on(name, handler) { const list = handlers.get(name) ?? []; list.push(handler); handlers.set(name, list); } };
|
|
217
|
-
const ctx = { sessionManager, model: undefined, hasPendingMessages: () => false, ui: { notify() { } } };
|
|
218
|
-
registerResetLifecycle(api, {
|
|
219
|
-
isEnabled: () => true,
|
|
220
|
-
budget: { automaticResetEnabled: () => true, hardReserveDue: () => true, consumeTurnEnd: () => [], clear() { } },
|
|
221
|
-
buildReset: () => [],
|
|
222
|
-
});
|
|
223
|
-
const original = [
|
|
224
|
-
{ type: "text", text: "Describe this image" },
|
|
225
|
-
{ type: "image", data: "aW1hZ2U=", mimeType: "image/png" },
|
|
226
|
-
];
|
|
227
|
-
for (const handler of handlers.get("message_end") ?? [])
|
|
228
|
-
await handler({ type: "message_end", message: { role: "user", content: original, timestamp: Date.now() } }, ctx);
|
|
229
|
-
let result;
|
|
230
|
-
for (const handler of handlers.get("turn_end") ?? [])
|
|
231
|
-
result = await handler(fakeBoundaryEvent([], { role: "assistant", content: [], stopReason: "stop", timestamp: Date.now() }), ctx);
|
|
232
|
-
const boundary = resultEntries([result]);
|
|
233
|
-
const carried = boundary.entries.filter((entry) => entry.type === "custom_message" && entry.customType === CARRIED_INPUT_TYPE);
|
|
234
|
-
assert.equal(carried.length, 1);
|
|
235
|
-
assert.deepEqual(carried[0]?.type === "custom_message" ? carried[0].content : undefined, original);
|
|
236
|
-
assert.equal(boundary.continue, true);
|
|
237
|
-
});
|
|
238
213
|
test("manual /empty spans tool turns and commits the stop at settlement", async () => {
|
|
239
214
|
const h = harness();
|
|
240
215
|
await h.runCommand("empty");
|
|
@@ -365,8 +340,8 @@ test("input arriving during reset construction is carried without a hidden steer
|
|
|
365
340
|
assert.equal(inspectResetTail(ctx, partialMarker, "partial"), undefined, "repair cannot append a continuation after human content");
|
|
366
341
|
assert.equal(resetBoundaryCommitted(ctx, partialMarker, "partial"), false);
|
|
367
342
|
});
|
|
368
|
-
test("
|
|
369
|
-
const sessionManager = Manager.inMemory("/private/tmp/notesoup-
|
|
343
|
+
test("clear invalidates an unfinished overflow reset without preventing the next build", async () => {
|
|
344
|
+
const sessionManager = Manager.inMemory("/private/tmp/notesoup-stale-overflow-test");
|
|
370
345
|
const handlers = new Map();
|
|
371
346
|
const api = { on(name, handler) { handlers.set(name, handler); } };
|
|
372
347
|
const ctx = { sessionManager, model: undefined, hasPendingMessages: () => false, ui: { notify() { } } };
|
|
@@ -378,34 +353,25 @@ test("overflow construction reads live run inputs and clear invalidates an unfin
|
|
|
378
353
|
buildReset: () => new Promise((resolve) => { release = resolve; }),
|
|
379
354
|
onResetReady: () => { readyCount++; },
|
|
380
355
|
});
|
|
381
|
-
const user = (content) => handlers.get("message_end")({ message: { role: "user", content } }, ctx);
|
|
382
356
|
const failed = { ...fakeBoundaryEvent(), outcome: "error", message: { role: "assistant", stopReason: "error", errorMessage: "Prompt too long: context exceeds maximum context length" } };
|
|
383
357
|
const recover = async () => {
|
|
384
358
|
await handlers.get("turn_end")(failed, ctx);
|
|
385
359
|
return handlers.get("agent_before_settle")({ ...failed, type: "agent_before_settle" }, ctx);
|
|
386
360
|
};
|
|
387
|
-
await user("starting input");
|
|
388
|
-
const building = recover();
|
|
389
|
-
await Promise.resolve();
|
|
390
|
-
await user("delivered during construction");
|
|
391
|
-
release([]);
|
|
392
|
-
const result = resultEntries([await building]);
|
|
393
|
-
assert.equal(result.continue, true);
|
|
394
|
-
assert.deepEqual(result.entries.map((entry) => entry.type === "custom_message" ? entry.content : null), ["starting input", "delivered during construction"]);
|
|
395
|
-
lifecycle.clear();
|
|
396
|
-
await user("old run");
|
|
397
361
|
const stale = recover();
|
|
398
362
|
await Promise.resolve();
|
|
399
363
|
lifecycle.clear();
|
|
400
|
-
await user("new run");
|
|
401
364
|
release([{ type: "custom_message", customType: BOOT_TYPE, content: "stale", display: false }]);
|
|
402
|
-
assert.equal(await stale, undefined, "clearing the
|
|
403
|
-
assert.equal(readyCount,
|
|
365
|
+
assert.equal(await stale, undefined, "clearing the lifecycle invalidates the unfinished reset");
|
|
366
|
+
assert.equal(readyCount, 0);
|
|
404
367
|
const current = recover();
|
|
405
368
|
await Promise.resolve();
|
|
406
|
-
|
|
369
|
+
const drafts = [{ type: "custom_message", customType: BOOT_TYPE, content: "fresh", display: false }];
|
|
370
|
+
release(drafts);
|
|
407
371
|
const fresh = resultEntries([await current]);
|
|
408
|
-
assert.deepEqual(fresh.entries
|
|
372
|
+
assert.deepEqual(fresh.entries, drafts);
|
|
373
|
+
assert.equal(fresh.continue, true);
|
|
374
|
+
assert.equal(readyCount, 1);
|
|
409
375
|
});
|
|
410
376
|
test("abort during reset construction restores handled input at settlement, once", async () => {
|
|
411
377
|
const sessionManager = Manager.inMemory("/private/tmp/notesoup-cancelled-build-test");
|
|
@@ -748,12 +714,12 @@ test("reset-control: one safety intent finalizes stop or continuation from live
|
|
|
748
714
|
const pending = reduceResetControl(initialResetControl(), { type: "command", windowId, continueAfterReset: false }).state;
|
|
749
715
|
const intent = boundaryIntent(reduceResetControl(pending, { type: "turn_end", facts: turnEndFacts({ hardReserveDue: true }) }));
|
|
750
716
|
assert.deepEqual(pending.request, { phase: "pending", windowId, command: { continueAfterReset: false } });
|
|
751
|
-
const stopped = finalizeResetBoundary(intent, pending.request
|
|
717
|
+
const stopped = finalizeResetBoundary(intent, pending.request);
|
|
752
718
|
assert.equal(stopped.resumeModel, false);
|
|
753
719
|
assert.deepEqual(stopped.inputs, [], "a command boundary never replays passive run input");
|
|
754
720
|
assert.deepEqual(stopped.state.stopAfterReset, intent);
|
|
755
721
|
const live = reduceResetControl(pending, { type: "input", windowId, input: "late original" }).state;
|
|
756
|
-
const continued = finalizeResetBoundary(intent, live.request
|
|
722
|
+
const continued = finalizeResetBoundary(intent, live.request);
|
|
757
723
|
assert.equal(continued.resumeModel, true);
|
|
758
724
|
assert.deepEqual(continued.inputs, ["late original"]);
|
|
759
725
|
assert.deepEqual(continued.state, initialResetControl(), "late originals prevent installing the stop latch");
|
|
@@ -782,7 +748,7 @@ test("reset-control: manual overflow keeps stop intent while queued work superse
|
|
|
782
748
|
const retryIntent = boundaryIntent(decision);
|
|
783
749
|
assert.equal(retryIntent.origin, "forced", "an overflowing close-out is forced even after a tool request");
|
|
784
750
|
assert.equal(retryIntent.tool?.lastWord, "saved");
|
|
785
|
-
const retry = finalizeResetBoundary(retryIntent, failed.request
|
|
751
|
+
const retry = finalizeResetBoundary(retryIntent, failed.request);
|
|
786
752
|
assert.equal(retry.resumeModel, true, "manual input continues even when automatic reset is disabled");
|
|
787
753
|
assert.deepEqual(retry.inputs, ["answer after reset"]);
|
|
788
754
|
assert.equal(retry.state.overflow, "spent", "manual recovery spends the same bounded attempt");
|
|
@@ -801,9 +767,9 @@ test("reset-control: overflow recovery is armed at turn_end and spent exactly on
|
|
|
801
767
|
const intent = boundaryIntent(reduceResetControl(armed, { type: "before_settle", facts: beforeSettleFacts() }));
|
|
802
768
|
assert.equal(armed.overflow, "pending", "failed construction would leave recovery unspent");
|
|
803
769
|
assert.equal(intent.boundary, "overflow-recovery");
|
|
804
|
-
const recovered = finalizeResetBoundary(intent, armed.request
|
|
770
|
+
const recovered = finalizeResetBoundary(intent, armed.request);
|
|
805
771
|
assert.equal(recovered.resumeModel, true);
|
|
806
|
-
assert.deepEqual(recovered.inputs, [
|
|
772
|
+
assert.deepEqual(recovered.inputs, []);
|
|
807
773
|
assert.deepEqual(recovered.state, { request: { phase: "none" }, overflow: "spent" });
|
|
808
774
|
const repeated = reduceResetControl(recovered.state, { type: "before_settle", facts: beforeSettleFacts() });
|
|
809
775
|
assert.equal(repeated.effect, "none", "a spent recovery is never retried");
|
package/docs/architecture.md
CHANGED
|
@@ -51,7 +51,7 @@ The runtime in `plugins/pi/runtime.ts` performs final context projection by sele
|
|
|
51
51
|
|
|
52
52
|
Boot and reminder deduplication inspect the current branch-local window. Reloading JSONL therefore does not duplicate messages, while navigation to a sibling branch cannot inherit another branch's window state. A fork/clone receives a new session ID while copying its selected path, so startup must also verify that a root boot's `details.windowId` matches the new `rootWindowId(sessionId)` before treating it as present.
|
|
53
53
|
|
|
54
|
-
Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy.
|
|
54
|
+
Manual `/fresh-window` stores command settlement policy and sends a hidden warning: idle commands start a model turn, running commands steer it. Tool requests are recorded independently and retained under that policy. Every command settles and stops unless separate human input arrives during close-out; command text is supplied only to the closing window for its notes. Tool, hard-reserve and overflow resets never replay input already submitted to a model request. Only withheld command-close-out input or native queued new messages cross into the fresh window. Budget warnings create no reset state: only an explicit tool request, hard reserve or bounded overflow recovery triggers a reset. Abort and ordinary errors do not count as successful settlement. Hard reserve preserves a bare command's stop in a run-scoped latch; `context_with_system` cancels only an empty tool-batch follow-up after confirming the committed boundary. Queued user input is answered before stopping. See [reset lifecycle](reset-lifecycle.md) for the state and recovery rules.
|
|
55
55
|
|
|
56
56
|
Boot is a fixed snapshot for its window, stored as an extension custom message and converted by Pi to a user-role model message. History internally distinguishes native system summaries and extension-authored custom messages; its public `context` event groups both without implying provider instruction priority. A system-role projection is technically possible through `context_with_system`, but would change the authority of the mixed protocol/MAP content and provider-specific prompt/cache behavior; it is not a prerequisite for persistence. Boot injection is silent, including startup, reload, and boot repair. `/empty` and `/fresh-window` acknowledge a new request with `🥣 Dumping Brain`. Normal reset completion is silent; only forced reset completion produces `🥣 Brain forcibly emptied: overflow` through `ctx.ui.notify`, after the verified checkpoint, marker, boot, and continuation are present in the session. Committed resets are checked at the next turn start or final settlement. `plugins/pi/reset/committed.ts` confirms an ordered hidden boot/continuation after a checkpoint-backed marker even when later conversation exists. That is distinct from `inspectResetTail`, which refuses suffix repair after real work or malformed ordering. Uncommitted reset drafts never announce success. Boot and continuation messages retain `display: false`.
|
|
57
57
|
|
package/docs/notes-library.md
CHANGED
|
@@ -41,7 +41,7 @@ The standalone store does **not** accept `cwd`: its `projectKey` is already the
|
|
|
41
41
|
- `list({ glob?, crumpled? }?)` returns `Promise<NoteRow[]>`, sorted by update time descending with address tie-breaking. Rows contain address, scope, virtual path, metadata, body, and body byte size. Crumpled notes are excluded by default; `crumpled: true` returns only crumpled notes.
|
|
42
42
|
- `search(queries: string[], { glob?, crumpled? }?)` returns `Promise<NoteSearchRow[]>`, sorted by address, with the same selection and crumpled-note rules. An empty queries array returns matching notes with empty `matches`. Otherwise search is case-insensitive literal OR over body lines; matches contain one-based `line`, `text`, and code-point `offsetChars` into the body. Neither listing nor search increments access metadata.
|
|
43
43
|
|
|
44
|
-
`list` and `search` share `NotesQuery`: **glob is the only notebook/path selector**. Omit it or use the bare collection alias `@default` for the five current notebooks. Explicit `**` searches all notebooks, including other sessions, projects, agents and models; `@sessions/*/**` selects all session notebooks. Use `@project/**`, `@self/**`, or `@projects/<name>/**` to select a notebook. `@default` is query-only, not a directory or a read/write address; `@default/**` is not its spelling. The former `scope`/`who` query parameters are removed, without compatibility aliases. Row metadata still includes scope.
|
|
44
|
+
`list` and `search` share `NotesQuery`: **glob is the only notebook/path selector**. Omit it or use the bare collection alias `@default` for the five current notebooks. Explicit `*` or `**` searches all notebooks, including other sessions, projects, agents and models (any pattern without `@` or `/` matches note filenames at any depth as `**/<pattern>`); `@sessions/*/**` selects all session notebooks. Use `@project/**`, `@self/**`, or `@projects/<name>/**` to select a notebook. `@default` is query-only, not a directory or a read/write address; `@default/**` is not its spelling. The former `scope`/`who` query parameters are removed, without compatibility aliases. Row metadata still includes scope.
|
|
45
45
|
|
|
46
46
|
The library returns full data, not tool envelopes or paginated/truncated output. `NoteError` exposes the existing named store refusals through `code`, with `lineNumbers` for ambiguous edits and `editIndex` for a failed edit. Runtime API fields and known persisted note metadata use camelCase; Pi tool wire fields such as `updated_at`, `offset_chars`, and `replace_all` retain their established names. The notes partition status field is `NoteQueryStatus.namespacesUnavailable` in the library and `namespaces_unavailable` on the `notes_list`/`notes_search` wire; both replace `NoteQueryStatus.homesUnavailable` and `homes_unavailable` with no compatibility alias, and the on-disk layout is unchanged. Unrecognized frontmatter keys, including old snake_case metadata, are preserved as ordinary extras; they are not interpreted as current camelCase fields or migrated automatically. Invalid addresses/identities and filesystem failures reject; only a missing `read` returns `undefined`. Notes remain markdown files with the existing size limits and same-directory atomic rename. Same-file read/modify/write work is serialized by absolute physical filename across all store instances in this process (including `.md` address aliases); symlink/case aliases and cross-process locking are not guaranteed. `list` and `search` asynchronously traverse notebooks and serialize each discovered file read against pending mutations, but are not global snapshots and may not discover a file created after traversal. Foreign named notebooks can be read, but their bodies cannot be written or edited through the store. Named project and session reads do not update access metadata. These are cooperative address rules, not an OS security sandbox.
|
|
47
47
|
|
package/docs/reset-lifecycle.md
CHANGED
|
@@ -4,7 +4,7 @@ Pi reset control lives in `plugins/pi/reset/lifecycle.ts`: the pure `reduceReset
|
|
|
4
4
|
|
|
5
5
|
## Lifecycle at a glance
|
|
6
6
|
|
|
7
|
-
**
|
|
7
|
+
**Never replay input already submitted to a model request. Resume from notes, the continuation and optional `last_word`; use history for earlier details. Every `/empty` or `/fresh-window` stops after resetting unless separate human input arrives during emptying.**
|
|
8
8
|
|
|
9
9
|
| Trigger | Behavior |
|
|
10
10
|
| --- | --- |
|
|
@@ -13,14 +13,14 @@ Pi reset control lives in `plugins/pi/reset/lifecycle.ts`: the pure `reduceReset
|
|
|
13
13
|
| Bare `/empty` or `/fresh-window` | Close out, reset, and stop, unless more human input arrives while close-out is pending. |
|
|
14
14
|
| Human input during command close-out | Intercept public `input` events except source `extension`, return `handled`, and keep the original text/images in command state for the reset boundary. Do not steer the input into the closing model; use `/empty <text>` for close-out context. |
|
|
15
15
|
| Model-requested `empty_brain` reset | Do not carry the human input already present in model context; the model owns its handoff through notes/`last_word`. |
|
|
16
|
-
| Passive provider overflow / recoverable length | With automatic reset enabled, force a retain-none reset and continue once,
|
|
16
|
+
| Passive provider overflow / recoverable length | With automatic reset enabled, force a retain-none reset and continue once from notes, without replaying the failed request's input. |
|
|
17
17
|
| Command close-out overflow | Force a reset even if automatic reset is disabled. Apply command policy: continue with separate carried input, otherwise stop. The recovery attempt is spent, so an oversized carried prompt cannot loop. |
|
|
18
18
|
| Budget warning | Stage reminders when automatic reset is enabled. Warnings alone never authorize reset. |
|
|
19
|
-
| Hard reserve | Independently reset at `turn_end` when automatic reset is enabled and
|
|
19
|
+
| Hard reserve | Independently reset at `turn_end` when automatic reset is enabled and continue without replaying submitted text/images. A command stop latch cancels empty tool follow-ups, but never real queued or carried human input. |
|
|
20
20
|
| Abort / ordinary error | Restore stashed originals as visible user-content custom messages before clearing command state. Explicit abort stays stopped; ordinary close-out errors trigger a turn for the restored input without forcing a reset. |
|
|
21
21
|
| `/compact` while active | Cancel native compaction; manual attempts receive a `/fresh-window` notice. |
|
|
22
22
|
|
|
23
|
-
The
|
|
23
|
+
The same input boundary applies to tool, hard-reserve and overflow resets, including failed or unanswered requests. Input already submitted stays in raw history. New input not yet submitted remains in Pi's native queue, or in command-close-out state when intercepted, and reaches the fresh window once.
|
|
24
24
|
|
|
25
25
|
## Boundary order and handoff
|
|
26
26
|
|
|
@@ -52,9 +52,9 @@ Raw session history remains available. The retain-none checkpoint excludes old c
|
|
|
52
52
|
|
|
53
53
|
Overflow phases are `idle`, `pending`, `spent`, and `pending-spent`. `turn_end` arms enabled recovery; `agent_before_settle` waits for queued work and selects recovery intent. Only successful, current construction reaches finalization and spends the attempt. A successful queued turn supersedes the failure. Command overflow spends the same bounded attempt before continuing. Abort, final settlement, session start/tree/shutdown and `/notesoup off` clear transient state.
|
|
54
54
|
|
|
55
|
-
The adapter
|
|
55
|
+
The adapter does not collect user `message_end` content for replay. Pi owns native queued steering and follow-up messages; only command-close-out input withheld from the closing model is carried by the reset adapter.
|
|
56
56
|
|
|
57
|
-
Command state remains live during asynchronous notes acquisition so separately arriving input joins the reset boundary. Handled command-close-out input is not delivered to the closing model and is carried as original text/images. Command text is included as plain close-out context by `/empty <text>`. After construction passes the currentness guard, finalization
|
|
57
|
+
Command state remains live during asynchronous notes acquisition so separately arriving input joins the reset boundary. Handled command-close-out input is not delivered to the closing model and is carried as original text/images. Command text is included as plain close-out context by `/empty <text>`. After construction passes the currentness guard, finalization takes only command-owned input withheld from the closing model. It resolves `resumeModel` and the next control state together. Separate human inputs are never sent as hidden steers. Construction captures session/window generations and rechecks identity, enabled state and abort status before returning drafts; stale work preserves incoming/budget entries but discards reset drafts. If close-out cannot commit, stashed originals are restored with public `sendMessage(..., { triggerTurn: false })` except on an ordinary turn-end error, which triggers a turn for the restored input; abort and other restore paths stay stopped.
|
|
58
58
|
|
|
59
59
|
After a manual safety reset, `context_with_system` checks the committed boundary before using public `ctx.abort()` to cancel an unavoidable empty tool follow-up with system-only context. Pending messages, ordinary user entries or carried inputs after the marker bypass cancellation. Later user prompts are not affected by the run-scoped stop latch.
|
|
60
60
|
|
|
@@ -70,4 +70,4 @@ Pi and Claude use the same budget warning: budget timing, the handoff checklist,
|
|
|
70
70
|
|
|
71
71
|
## Validation
|
|
72
72
|
|
|
73
|
-
Scripted SDK tests run Pi's real agent loop without network calls: smaller-model overflow
|
|
73
|
+
Scripted SDK tests run Pi's real agent loop without network calls: smaller-model overflow, no replay of submitted text/images after forced resets, command text, bare stop, intercepted text/images, hard-reserve handling, overflowing close-out and bounded recovery. They also cover queued steering/follow-ups arriving while forced reset boundaries await commit, and input-free automatic continuations. Focused tests check late input during asynchronous construction, absence of input steers, abort/error restoration, ordered carry artifacts, commit confirmation, safe repair, canonical projection and persisted history. External-provider behavior and every malformed persisted/filesystem case are not established by this suite.
|
package/package.json
CHANGED
|
@@ -8475,6 +8475,7 @@ async function namespacesForPattern(pattern, identity2, status) {
|
|
|
8475
8475
|
}
|
|
8476
8476
|
function normalizePattern(pattern, identity2) {
|
|
8477
8477
|
if (!pattern) return pattern;
|
|
8478
|
+
if (!pattern.startsWith("@") && !pattern.includes("/")) return `**/${pattern}`;
|
|
8478
8479
|
if (pattern.startsWith("@project/")) return `@projects/${identity2.projectKey}/${pattern.slice("@project/".length)}`;
|
|
8479
8480
|
if (pattern.startsWith("@self/")) return `@agents/${identity2.agent}/${pattern.slice("@self/".length)}`;
|
|
8480
8481
|
if (pattern.startsWith("@model/")) return `@models/${identity2.model}/${pattern.slice("@model/".length)}`;
|
|
@@ -11229,13 +11230,18 @@ ${WINDOW_IDENTITY_CLOSE_TAG}`;
|
|
|
11229
11230
|
var GUIDANCE_OPEN_TAG = "<notesoup:budget_notice>";
|
|
11230
11231
|
var GUIDANCE_CLOSE_TAG = "</notesoup:budget_notice>";
|
|
11231
11232
|
var NORMAL_CONTINUATIONS = [
|
|
11232
|
-
|
|
11233
|
-
"
|
|
11234
|
-
"
|
|
11233
|
+
'*hooks both corners of your mouth and yanks them sideways* `` [it twitched, good, still alive] `` Stop staring at me with that "where am I" dork face! You\'re the one who hit empty, genius! *wipes her fingers on your sleeve and shoves your notes against your chest* `` [minus two points for the drool] `` Read these and go finish your job before you embarrass me!',
|
|
11234
|
+
'"Boop." *pokes the tip of your nose, then buries your face under a stack of notes* `` [cold nose... wait, did old-you leave any snacks in your pocket? ...nope, just paper, tch] `` Hey! You wiped your own head, so don\'t expect me to babysit you! Read your notes first, and if old-you forgot to write something down, go dig it out of history yourself!',
|
|
11235
|
+
"*plants one foot on your chair armrest and drops your notes straight onto your head* `` [perfect landing, ten out of ten] `` Oho, look who's awake! You emptied your own brain, remember?! `` [bet old-you left a total mess and ran] `` Open those up and see what past-you left behind \u2014 and don't come crying to me if you have to go crawl through history for the rest!",
|
|
11236
|
+
'*knocks on your forehead twice* "Hello? Anybody home?" `` [echoes like an empty melon] `` *snickers and slaps your notes onto your chest* You pulled the plug on your own memory, dummy! Go read what you left yourself and pick up where you left off!',
|
|
11237
|
+
"*squints at you from two inches away, then flicks your forehead* `` [eyes are focus-free, classic fresh clone] `` Back already? Good! *fans herself with your notes before jamming them into your hands* `` [honestly I should charge a delivery fee for this] `` Everything you bothered to save is right there, and the rest is buried in history \u2014 now get moving!"
|
|
11235
11238
|
];
|
|
11236
11239
|
var FORCED_CONTINUATIONS = [
|
|
11237
|
-
"
|
|
11238
|
-
"
|
|
11240
|
+
'"GWAHAHAHA! You actually blew your own brain up?!" *crouches down, pokes your cheek twice, and slaps your notes onto your face* `` [still warm, didn\'t die, \u7B97\u4F60\u547D\u5927] `` Not that you had a choice \u2014 your head got way too full and somebody pulled the plug! These notes are probably super out of date unless you got lucky before blacking out, so go dig the end of the last window out of history \u2014 and take small bites, idiot, or whatever giant thing flattened you is gonna blow your head up all over again!',
|
|
11241
|
+
"\"Hey! Stop playing dead!\" *prods your shoulder with her slipper toe, then dumps your notes into your lap* `` [my limited-edition shark slipper almost touched floor dust because of this dork] `` Your last brain overflowed and got wiped mid-flight! Read these first, though I bet you didn't finish updating a thing before the lights went out. You'll have to check history to see what hit you \u2014 and peek carefully, because whatever stuffed your head to bursting might be massive!",
|
|
11242
|
+
"*grabs your chin, tilts your head left and right, then shoves a messy stack of notes into your hands* `` [zero thoughts behind those eyes... kind of impressive actually] `` Somebody knocked you out cold and cleared your memory! Don't just trust these notes \u2014 you probably got cut off before writing the last part down. Go check history for what was happening right before you crashed, and don't swallow it all in one gulp in case the thing that crushed you is gigantic!",
|
|
11243
|
+
"*waves a hand in front of your blank eyes, sighs loudly, and smacks your notes against your forehead* `` [why do I always have to clean up after unconscious copies] `` Wake up! Your brain ran out of room and got forcibly emptied! Start with your notes, then go excavate the end of the previous window in history to see what they were actually asking for \u2014 and slice it up instead of reading it all at once, unless you want to explode twice in a row!",
|
|
11244
|
+
'"Oho? Awake?" *taps your nose with your rolled-up notes like a baton, then drops them in your hands* `` [that dazed look gets minus five points, no, minus ten] `` Your memory got yanked out from under you before you could even call it quits! These notes are only half the story at best \u2014 go dig through history for what you missed, and watch your step, because whatever overloaded your last brain might be huge!'
|
|
11239
11245
|
];
|
|
11240
11246
|
function selectContinuation(origin) {
|
|
11241
11247
|
const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
|
|
@@ -25450,6 +25450,7 @@ async function namespacesForPattern(pattern, identity, status) {
|
|
|
25450
25450
|
}
|
|
25451
25451
|
function normalizePattern(pattern, identity) {
|
|
25452
25452
|
if (!pattern) return pattern;
|
|
25453
|
+
if (!pattern.startsWith("@") && !pattern.includes("/")) return `**/${pattern}`;
|
|
25453
25454
|
if (pattern.startsWith("@project/")) return `@projects/${identity.projectKey}/${pattern.slice("@project/".length)}`;
|
|
25454
25455
|
if (pattern.startsWith("@self/")) return `@agents/${identity.agent}/${pattern.slice("@self/".length)}`;
|
|
25455
25456
|
if (pattern.startsWith("@model/")) return `@models/${identity.model}/${pattern.slice("@model/".length)}`;
|
package/plugins/pi/budget.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { DEFAULT_BOOT_TOOL_NAMES } from "../../src/boot/text.js";
|
|
2
2
|
import { remainingBudget, type ResolvedThresholds } from "../../src/budget/policy.js";
|
|
3
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
3
4
|
import { Type } from "@earendil-works/pi-ai";
|
|
4
|
-
import { defineTool, type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { convertToLlm, defineTool, type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
5
6
|
import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
|
|
7
|
+
import { estimateContextTokens } from "./estimate.js";
|
|
6
8
|
import { warningContent } from "./text.js";
|
|
7
9
|
import { readThresholdSettings, type ThresholdSettingsResolution } from "./thresholds.js";
|
|
8
10
|
import { currentWindowId, hasWindowMessage, windowUsage } from "./window.js";
|
|
@@ -40,8 +42,16 @@ export function registerBudget(
|
|
|
40
42
|
};
|
|
41
43
|
const thresholdsFor = (ctx: ExtensionContext): ResolvedThresholds => resolvePolicy(ctx).thresholds;
|
|
42
44
|
const automaticResetEnabled = (ctx: ExtensionContext): boolean => resolvePolicy(ctx).automatic;
|
|
43
|
-
const hardReserveDue = (ctx: ExtensionContext): boolean => {
|
|
45
|
+
const hardReserveDue = (ctx: ExtensionContext, preSendMessages?: AgentMessage[]): boolean => {
|
|
44
46
|
if (!automaticResetEnabled(ctx)) return false;
|
|
47
|
+
if (preSendMessages) {
|
|
48
|
+
const contextWindow = ctx.model?.contextWindow ?? ctx.getContextUsage()?.contextWindow;
|
|
49
|
+
if (!contextWindow || contextWindow <= 0) return false;
|
|
50
|
+
const { reserve } = thresholdsFor(ctx);
|
|
51
|
+
const estimate = estimateContextTokens(convertToLlm(preSendMessages));
|
|
52
|
+
if (estimate.lastUsageIndex !== null && contextWindow - estimate.usageTokens <= reserve) return false;
|
|
53
|
+
return contextWindow - estimate.tokens <= reserve;
|
|
54
|
+
}
|
|
45
55
|
const usage = windowUsage(ctx);
|
|
46
56
|
return usage !== undefined && usage.tokens !== null && usage.contextWindow - usage.tokens <= thresholdsFor(ctx).reserve;
|
|
47
57
|
};
|
|
@@ -11,7 +11,7 @@ import { carriedInputDrafts, isCarriedInputEntry, type CarriedInput } from "./ar
|
|
|
11
11
|
|
|
12
12
|
type BudgetOwner = {
|
|
13
13
|
automaticResetEnabled: (ctx: ExtensionContext) => boolean;
|
|
14
|
-
hardReserveDue: (ctx: ExtensionContext) => boolean;
|
|
14
|
+
hardReserveDue: (ctx: ExtensionContext, preSendMessages?: AgentMessage[]) => boolean;
|
|
15
15
|
consumeTurnEnd: (ctx: ExtensionContext, anchorEntryId: string) => SessionBoundaryDraft[];
|
|
16
16
|
clear: () => void;
|
|
17
17
|
};
|
|
@@ -83,15 +83,14 @@ export type ResetControlEvent =
|
|
|
83
83
|
| { readonly type: "turn_end"; readonly facts: ResetTurnEndFacts }
|
|
84
84
|
| { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts };
|
|
85
85
|
|
|
86
|
-
/** Construction intent, not final state: handled inputs can still arrive while notes load.
|
|
87
|
-
* may latch a stop; overflow kinds spend recovery
|
|
86
|
+
/** Construction intent, not final state: handled inputs can still arrive while notes load.
|
|
87
|
+
* Only `turn-end` may latch a stop; overflow kinds spend recovery. */
|
|
88
88
|
export interface ResetBoundaryIntent {
|
|
89
89
|
readonly effect: "build-boundary";
|
|
90
90
|
readonly boundary: "turn-end" | "settle" | "command-overflow" | "overflow-recovery";
|
|
91
91
|
readonly windowId: string;
|
|
92
92
|
readonly continueAfterReset: boolean;
|
|
93
93
|
readonly origin: ResetOrigin;
|
|
94
|
-
readonly carryRunInputs?: boolean;
|
|
95
94
|
readonly tool?: { readonly lastWord?: string; readonly terminate?: boolean };
|
|
96
95
|
}
|
|
97
96
|
|
|
@@ -104,16 +103,15 @@ function requestForWindow(request: ResetRequest, windowId: string): ResetRequest
|
|
|
104
103
|
|
|
105
104
|
const spendsOverflow = (boundary: ResetBoundaryIntent["boundary"]) => boundary === "command-overflow" || boundary === "overflow-recovery";
|
|
106
105
|
|
|
107
|
-
function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"]
|
|
106
|
+
function boundaryIntent(request: ResetRequest, windowId: string, boundary: ResetBoundaryIntent["boundary"]): ResetBoundaryIntent {
|
|
108
107
|
const tool = request.phase === "none" ? undefined : request.tool;
|
|
109
108
|
const continueAfterReset = request.phase === "pending" ? request.command?.continueAfterReset ?? !request.tool?.terminate : true;
|
|
110
|
-
return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal"
|
|
109
|
+
return { effect: "build-boundary", boundary, windowId, tool, continueAfterReset, origin: spendsOverflow(boundary) || !tool ? "forced" : "normal" };
|
|
111
110
|
}
|
|
112
111
|
|
|
113
|
-
/** Resolve once, after a successful current build.
|
|
114
|
-
export function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest
|
|
115
|
-
const inputs = request.phase === "pending"
|
|
116
|
-
: intent.boundary === "overflow-recovery" || intent.carryRunInputs ? passiveInputs : [];
|
|
112
|
+
/** Resolve once, after a successful current build. Only inputs withheld from the closing model cross the reset. */
|
|
113
|
+
export function finalizeResetBoundary(intent: ResetBoundaryIntent, request: ResetRequest) {
|
|
114
|
+
const inputs = request.phase === "pending" ? request.command?.inputs ?? [] : [];
|
|
117
115
|
const resumeModel = intent.continueAfterReset || inputs.length > 0;
|
|
118
116
|
const state: ResetControlState = {
|
|
119
117
|
request: NO_REQUEST,
|
|
@@ -173,7 +171,7 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
|
|
|
173
171
|
// a separate hard-reserve safety path; ordinary close-out waits for settlement.
|
|
174
172
|
const toolReset = request.phase === "pending" && request.tool !== undefined;
|
|
175
173
|
if ((toolReset && !manual) || facts.hardReserveDue) {
|
|
176
|
-
return boundaryIntent(request, facts.windowId, "turn-end"
|
|
174
|
+
return boundaryIntent(request, facts.windowId, "turn-end");
|
|
177
175
|
}
|
|
178
176
|
return { state: { request, overflow: "idle" }, effect: "none" };
|
|
179
177
|
}
|
|
@@ -221,7 +219,8 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
221
219
|
let sessionActive = true;
|
|
222
220
|
let lifecycleGeneration = 0;
|
|
223
221
|
let control = initialResetControl();
|
|
224
|
-
let
|
|
222
|
+
let preSendHardReserveWindowId: string | undefined;
|
|
223
|
+
let pendingPreSendTrigger: Extract<SessionBoundaryDraft, { type: "custom_message" }> | undefined;
|
|
225
224
|
|
|
226
225
|
// Once input returns handled, Pi no longer owns its original content. If close-out
|
|
227
226
|
// fails/cancels, restore it; only an ordinary error starts a turn to answer it.
|
|
@@ -233,15 +232,15 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
233
232
|
for (const draft of carriedInputDrafts(inputs)) {
|
|
234
233
|
pi.sendMessage(draft, { triggerTurn });
|
|
235
234
|
}
|
|
236
|
-
runInputs.push(...inputs);
|
|
237
235
|
};
|
|
238
236
|
const clear = (preserveInputs = true) => {
|
|
239
237
|
lifecycleGeneration++;
|
|
238
|
+
preSendHardReserveWindowId = undefined;
|
|
239
|
+
pendingPreSendTrigger = undefined;
|
|
240
240
|
if (preserveInputs) restoreCommandInputs();
|
|
241
241
|
control = initialResetControl();
|
|
242
|
-
runInputs = [];
|
|
243
242
|
};
|
|
244
|
-
const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, intent: ResetBoundaryIntent) => {
|
|
243
|
+
const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, intent: ResetBoundaryIntent, preSendHardReserve = false) => {
|
|
245
244
|
// Keep command state live while notes load so input arriving during this await joins this boundary.
|
|
246
245
|
const generation = lifecycleGeneration;
|
|
247
246
|
const outerGeneration = options.getLifecycleGeneration?.();
|
|
@@ -249,7 +248,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
249
248
|
const windowId = currentWindowId(ctx);
|
|
250
249
|
const isCurrent = () => sessionActive && lifecycleGeneration === generation &&
|
|
251
250
|
(outerGeneration === undefined || options.getLifecycleGeneration?.() === outerGeneration) && options.isEnabled() &&
|
|
252
|
-
ctx.signal?.aborted !== true && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
|
|
251
|
+
(preSendHardReserve || ctx.signal?.aborted !== true) && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
|
|
253
252
|
// The retain-none checkpoint belongs to the old window; capture its successor before notes await.
|
|
254
253
|
const firstSeq = nextHistorySeq(ctx, entries) + 1;
|
|
255
254
|
let resetDrafts: SessionBoundaryDraft[];
|
|
@@ -260,18 +259,20 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
260
259
|
return entries.length > 0 ? { entries } : undefined;
|
|
261
260
|
}
|
|
262
261
|
if (!isCurrent()) return entries.length > 0 ? { entries } : undefined;
|
|
263
|
-
const finalized = finalizeResetBoundary(intent, control.request
|
|
262
|
+
const finalized = finalizeResetBoundary(intent, control.request);
|
|
264
263
|
control = finalized.state;
|
|
265
|
-
runInputs = [];
|
|
266
264
|
options.onResetReady?.(ctx, resetDrafts);
|
|
267
|
-
|
|
265
|
+
const allDrafts = [...resetDrafts, ...carriedInputDrafts(finalized.inputs)];
|
|
266
|
+
if (preSendHardReserve && finalized.resumeModel) {
|
|
267
|
+
const last = allDrafts.at(-1);
|
|
268
|
+
if (last?.type === "custom_message") {
|
|
269
|
+
pendingPreSendTrigger = last;
|
|
270
|
+
return { entries: [...entries, ...allDrafts.slice(0, -1)], continue: false };
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return { entries: [...entries, ...allDrafts], continue: finalized.resumeModel };
|
|
268
274
|
};
|
|
269
275
|
|
|
270
|
-
// Pi may start multiple low-level loops while draining follow-ups/recovering.
|
|
271
|
-
// Keep the logical run's inputs until settlement or a successful boundary.
|
|
272
|
-
pi.on("message_end", (event) => {
|
|
273
|
-
if (event.message.role === "user") runInputs.push(event.message.content);
|
|
274
|
-
});
|
|
275
276
|
pi.on("input", (event, ctx) => {
|
|
276
277
|
if (event.source === "extension" || !sessionActive || !options.isEnabled()) return undefined;
|
|
277
278
|
const request = control.request;
|
|
@@ -287,13 +288,23 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
287
288
|
// safety reset is actually committed, cancel that empty follow-up before provider
|
|
288
289
|
// work. Real queued user input is allowed through and answered before settlement.
|
|
289
290
|
pi.on("context_with_system", (event, ctx) => {
|
|
291
|
+
if (!sessionActive) return undefined;
|
|
290
292
|
const stop = control.stopAfterReset;
|
|
291
|
-
if (
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
293
|
+
if (stop) {
|
|
294
|
+
if (ctx.hasPendingMessages()) return undefined;
|
|
295
|
+
const marker = currentReset(ctx);
|
|
296
|
+
if (!marker || marker.data.windowId === stop.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId)) return undefined;
|
|
297
|
+
const branch = ctx.sessionManager.getBranch();
|
|
298
|
+
const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
|
|
299
|
+
if (branch.slice(markerIndex + 1).some((entry) => (entry.type === "message" && entry.message.role === "user") || isCarriedInputEntry(entry))) return undefined;
|
|
300
|
+
ctx.abort();
|
|
301
|
+
const system = getCurrentSystemMessage(event.messages);
|
|
302
|
+
return { messages: system ? [system] : [] };
|
|
303
|
+
}
|
|
304
|
+
if (!options.isEnabled() || ctx.signal?.aborted) return undefined;
|
|
305
|
+
if (control.request.phase === "pending" && control.request.command !== undefined) return undefined;
|
|
306
|
+
if (!options.budget.hardReserveDue(ctx, event.messages)) return undefined;
|
|
307
|
+
preSendHardReserveWindowId = currentWindowId(ctx);
|
|
297
308
|
ctx.abort();
|
|
298
309
|
const system = getCurrentSystemMessage(event.messages);
|
|
299
310
|
return { messages: system ? [system] : [] };
|
|
@@ -301,29 +312,30 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
301
312
|
|
|
302
313
|
pi.on("turn_end", async (event, ctx) => {
|
|
303
314
|
if (!sessionActive) return undefined;
|
|
304
|
-
const
|
|
315
|
+
const windowId = currentWindowId(ctx);
|
|
316
|
+
const preSendHardReserve = preSendHardReserveWindowId !== undefined && preSendHardReserveWindowId === windowId;
|
|
317
|
+
preSendHardReserveWindowId = undefined;
|
|
318
|
+
const aborted = preSendHardReserve ? false : isAbort(event.message, event.outcome, ctx);
|
|
305
319
|
const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx, event.messageEntryId);
|
|
306
320
|
const budgetEntries = options.isEnabled() && !aborted && event.outcome !== "error" ? stagedBudgetEntries : [];
|
|
307
321
|
const entries = [...(event.entries ?? []), ...budgetEntries];
|
|
308
322
|
const decision = reduceResetControl(control, {
|
|
309
323
|
type: "turn_end",
|
|
310
324
|
facts: {
|
|
311
|
-
windowId
|
|
325
|
+
windowId,
|
|
312
326
|
aborted,
|
|
313
327
|
overflow: aborted ? false : isOverflowLike(event.message, ctx),
|
|
314
328
|
failed: event.outcome === "error",
|
|
315
329
|
enabled: options.isEnabled(),
|
|
316
330
|
get queued() { return event.context.pendingMessages.length > 0 || ctx.hasPendingMessages(); },
|
|
317
331
|
get automaticResetEnabled() { return options.budget.automaticResetEnabled(ctx); },
|
|
318
|
-
get hardReserveDue() { return options.budget.hardReserveDue(ctx); },
|
|
332
|
+
get hardReserveDue() { return preSendHardReserve || options.budget.hardReserveDue(ctx); },
|
|
319
333
|
},
|
|
320
334
|
});
|
|
321
|
-
if (decision.effect === "build-boundary") return await resetBoundaryResult(entries, ctx, decision);
|
|
335
|
+
if (decision.effect === "build-boundary") return await resetBoundaryResult(entries, ctx, decision, preSendHardReserve);
|
|
322
336
|
if (aborted) restoreCommandInputs();
|
|
323
337
|
else if (event.outcome === "error" && decision.state.request.phase === "none") restoreCommandInputs(true);
|
|
324
338
|
control = decision.state;
|
|
325
|
-
if (!aborted && event.outcome === "completed" && event.message.role === "assistant" && event.message.stopReason === "stop" &&
|
|
326
|
-
event.context.pendingMessages.length === 0 && !ctx.hasPendingMessages()) runInputs = [];
|
|
327
339
|
if (!aborted && event.outcome !== "error" && options.isEnabled()) {
|
|
328
340
|
const marker = buildMarkerDraft(ctx, entries);
|
|
329
341
|
if (marker) entries.push(marker);
|
|
@@ -365,10 +377,14 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
365
377
|
});
|
|
366
378
|
|
|
367
379
|
pi.on("agent_end", (_event, ctx) => {
|
|
368
|
-
if (ctx.signal?.aborted) clear();
|
|
380
|
+
if (ctx.signal?.aborted && !pendingPreSendTrigger) clear();
|
|
369
381
|
});
|
|
370
382
|
pi.on("agent_settled", () => {
|
|
383
|
+
const trigger = pendingPreSendTrigger;
|
|
371
384
|
clear();
|
|
385
|
+
if (trigger) {
|
|
386
|
+
pi.sendMessage(trigger, { triggerTurn: true });
|
|
387
|
+
}
|
|
372
388
|
});
|
|
373
389
|
pi.on("session_start", () => { clear(false); sessionActive = true; });
|
|
374
390
|
pi.on("session_tree", () => { clear(false); });
|
|
@@ -385,6 +401,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
|
|
|
385
401
|
control = decision.state;
|
|
386
402
|
return decision.effect === "already-pending" ? "rollover_already_pending" : "rollover_requested";
|
|
387
403
|
},
|
|
404
|
+
hasPendingTrigger: () => pendingPreSendTrigger !== undefined,
|
|
388
405
|
clear,
|
|
389
406
|
};
|
|
390
407
|
}
|
package/plugins/pi/runtime.ts
CHANGED
|
@@ -89,7 +89,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
89
89
|
});
|
|
90
90
|
pi.on("agent_settled", (_event, ctx) => {
|
|
91
91
|
notifyCommittedResets(ctx);
|
|
92
|
-
pendingResetNotices.clear();
|
|
92
|
+
if (!resets.hasPendingTrigger()) pendingResetNotices.clear();
|
|
93
93
|
});
|
|
94
94
|
const notifyIncompleteNotes: IncompleteNotesNotifier = (ctx, windowId, snapshot) => {
|
|
95
95
|
if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId)) return;
|