notesoup 0.55.2 → 0.56.1

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.
Files changed (44) hide show
  1. package/dist/plugins/pi/budget.d.ts +4 -0
  2. package/dist/plugins/pi/budget.js +6 -1
  3. package/dist/plugins/pi/marker.d.ts +4 -2
  4. package/dist/plugins/pi/marker.js +18 -8
  5. package/dist/plugins/pi/reset/lifecycle.js +6 -0
  6. package/dist/src/history/query.d.ts +0 -2
  7. package/dist/src/history/query.js +2 -4
  8. package/dist/src/notes/store.d.ts +0 -2
  9. package/dist/src/notes/store.js +2 -2
  10. package/dist/src/tools/dream.d.ts +6 -6
  11. package/dist/src/tools/dream.js +8 -3
  12. package/dist/src/tools/notes.d.ts +18 -8
  13. package/dist/src/tools/notes.js +6 -11
  14. package/dist/test/agent-loop.test.js +44 -1
  15. package/dist/test/budget-settings.integration.test.js +18 -0
  16. package/dist/test/dream-tools.test.js +26 -7
  17. package/dist/test/marker.test.js +46 -15
  18. package/dist/test/notes-library.test.js +1 -1
  19. package/dist/test/notes.test.js +5 -4
  20. package/dist/test/pi-render.test.js +2 -2
  21. package/docs/architecture.md +1 -1
  22. package/docs/tool-results.md +2 -2
  23. package/package.json +1 -1
  24. package/playbook.md +1 -1
  25. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  26. package/plugins/claude/dist/claude/helper.js +8 -12
  27. package/plugins/claude/playbook.md +1 -1
  28. package/plugins/codex/dist/codex/notesoup.js +8 -12
  29. package/plugins/paseo/OVERVIEW.md +1 -1
  30. package/plugins/paseo/client/brain-empty-card.tsx +28 -9
  31. package/plugins/paseo/client/brain-empty-transformer.ts +5 -1
  32. package/plugins/paseo/client/markdown.tsx +14 -13
  33. package/plugins/paseo/client/notes-op-card.tsx +6 -6
  34. package/plugins/paseo/client/paper-card.tsx +20 -18
  35. package/plugins/paseo/client/paper-palette.ts +12 -9
  36. package/plugins/paseo/shared/brain-empty.ts +1 -0
  37. package/plugins/paseo/test/brain-empty.test.ts +8 -0
  38. package/plugins/pi/budget.ts +7 -1
  39. package/plugins/pi/marker.ts +18 -12
  40. package/plugins/pi/reset/lifecycle.ts +5 -0
  41. package/src/history/query.ts +2 -4
  42. package/src/notes/store.ts +3 -4
  43. package/src/tools/dream.ts +8 -3
  44. package/src/tools/notes.ts +7 -12
@@ -1,4 +1,8 @@
1
+ import { Type } from "@earendil-works/pi-ai";
1
2
  import { type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
3
+ export declare const ContextRemainingOutputSchema: Type.TObject<{
4
+ remaining_tokens: Type.TUnion<[Type.TInteger, Type.TNull]>;
5
+ }>;
2
6
  export declare function registerBudget(pi: ExtensionAPI, isEnabled: () => boolean, settingsManager?: SettingsManager): {
3
7
  automaticResetEnabled: (ctx: ExtensionContext) => boolean;
4
8
  hardReserveDue: (ctx: ExtensionContext) => boolean;
@@ -9,6 +9,9 @@ import { currentWindowId, hasWindowMessage, windowUsage } from "./window.js";
9
9
  import { tokenBudgetGuidance } from "../../src/budget/text.js";
10
10
  import { arrangeAnchoredReminders } from "./anchored.js";
11
11
  import { output } from "./tool-result.js";
12
+ export const ContextRemainingOutputSchema = Type.Object({
13
+ remaining_tokens: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
14
+ }, { additionalProperties: false });
12
15
  /** Remaining tokens in the provider's active window, or null without a usable estimate. */
13
16
  function remainingTokens(ctx) {
14
17
  const usage = windowUsage(ctx);
@@ -125,10 +128,12 @@ export function registerBudget(pi, isEnabled, settingsManager) {
125
128
  label: "Get context remaining",
126
129
  description: "Check how much room your brain has left before it gets forcibly emptied. Returns null when unknown.",
127
130
  parameters: Type.Object({}, { additionalProperties: false }),
131
+ outputSchema: ContextRemainingOutputSchema,
128
132
  async execute(_id, _params, _signal, _update, ctx) {
129
133
  // Report room to the hard-reserve wipe, including the warning runway.
130
134
  const remaining = remainingTokens(ctx);
131
- return output({ remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx).reserve) });
135
+ const value = { remaining_tokens: remainingBudget(remaining, thresholdsFor(ctx).reserve) };
136
+ return { ...output(value), structuredContent: value };
132
137
  },
133
138
  }));
134
139
  return {
@@ -1,9 +1,11 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ import type { CustomMessageEntryDraft, ExtensionAPI, ExtensionContext, SessionBoundaryDraft } from "@earendil-works/pi-coding-agent";
2
2
  /** Spacing between durable seq breadcrumbs, in projected history seq. */
3
- export declare const MARKER_INTERVAL = 120;
3
+ export declare const MARKER_INTERVAL = 100;
4
4
  /**
5
5
  * Stamp the current seq every MARKER_INTERVAL seqs. The marker names the seq it occupies, so a
6
6
  * model paging history_list meets a breadcrumb that tells it where it is. Skipped while a reset
7
7
  * tail still awaits boot or continuation: a foreign message there would close the repair shape.
8
8
  */
9
+ export declare function buildMarkerDraft(ctx: ExtensionContext, pending?: readonly SessionBoundaryDraft[]): CustomMessageEntryDraft | undefined;
10
+ /** Run-start fallback; active runs append the same draft through the turn-end boundary. */
9
11
  export declare function maybeSendMarker(pi: ExtensionAPI, ctx: ExtensionContext): void;
@@ -1,16 +1,16 @@
1
1
  import { piSequenceCount } from "../../src/history/pi.js";
2
- import { BOOT_TYPE, MARKER_TYPE } from "./entries.js";
2
+ import { BOOT_TYPE, MARKER_TYPE, RESET_MARKER_TYPE } from "./entries.js";
3
3
  import { nextHistorySeq } from "./history.js";
4
4
  import { inspectResetTail } from "./reset/artifacts.js";
5
5
  import { markerContent } from "./text.js";
6
6
  import { currentReset } from "./window.js";
7
7
  /** Spacing between durable seq breadcrumbs, in projected history seq. */
8
- export const MARKER_INTERVAL = 120;
8
+ export const MARKER_INTERVAL = 100;
9
9
  /** Highest seq already anchored by a window boot or marker; 0 before the first. */
10
- function lastMarkerSeq(ctx) {
10
+ function lastMarkerSeq(ctx, pending) {
11
11
  let last = 0;
12
12
  let nextSeq = 1;
13
- for (const entry of ctx.sessionManager.getEntries()) {
13
+ for (const entry of [...ctx.sessionManager.getEntries(), ...pending]) {
14
14
  const count = piSequenceCount(entry);
15
15
  if (count === 0)
16
16
  continue;
@@ -26,15 +26,25 @@ function lastMarkerSeq(ctx) {
26
26
  * model paging history_list meets a breadcrumb that tells it where it is. Skipped while a reset
27
27
  * tail still awaits boot or continuation: a foreign message there would close the repair shape.
28
28
  */
29
- export function maybeSendMarker(pi, ctx) {
29
+ export function buildMarkerDraft(ctx, pending = []) {
30
+ if (pending.some((entry) => entry.type === "custom" && entry.customType === RESET_MARKER_TYPE))
31
+ return;
30
32
  const reset = currentReset(ctx);
31
33
  if (reset) {
32
34
  const tail = inspectResetTail(ctx, reset.id, reset.data.windowId);
33
35
  if (tail && (!tail.boot || !tail.continuation))
34
36
  return;
35
37
  }
36
- const seq = nextHistorySeq(ctx);
37
- if (seq - lastMarkerSeq(ctx) < MARKER_INTERVAL)
38
+ const seq = nextHistorySeq(ctx, pending);
39
+ if (seq - lastMarkerSeq(ctx, pending) < MARKER_INTERVAL)
40
+ return;
41
+ return { type: "custom_message", customType: MARKER_TYPE, content: markerContent(seq), display: false, details: { seq } };
42
+ }
43
+ /** Run-start fallback; active runs append the same draft through the turn-end boundary. */
44
+ export function maybeSendMarker(pi, ctx) {
45
+ const draft = buildMarkerDraft(ctx);
46
+ if (!draft)
38
47
  return;
39
- pi.sendMessage({ customType: MARKER_TYPE, content: markerContent(seq), display: false, details: { seq } }, { triggerTurn: false });
48
+ const { type: _type, ...message } = draft;
49
+ pi.sendMessage(message, { triggerTurn: false });
40
50
  }
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
3
3
  import { currentReset, currentWindowId } from "../window.js";
4
4
  import { nextHistorySeq } from "../history.js";
5
+ import { buildMarkerDraft } from "../marker.js";
5
6
  import { resetBoundaryCommitted } from "./committed.js";
6
7
  import { errorMessage } from "../../../src/error-message.js";
7
8
  import { carriedInputDrafts, isCarriedInputEntry } from "./artifacts.js";
@@ -272,6 +273,11 @@ export function registerResetLifecycle(pi, options) {
272
273
  if (aborted || (event.outcome === "error" && decision.state.request.phase === "none"))
273
274
  restoreCommandInputs();
274
275
  control = decision.state;
276
+ if (!aborted && event.outcome !== "error" && options.isEnabled()) {
277
+ const marker = buildMarkerDraft(ctx, entries);
278
+ if (marker)
279
+ entries.push(marker);
280
+ }
275
281
  return entries.length > 0 ? { entries } : undefined;
276
282
  });
277
283
  pi.on("agent_before_settle", async (event, ctx) => {
@@ -18,12 +18,10 @@ export type HistorySelection = HistoryFilter & {
18
18
  until?: string;
19
19
  max_chars_per_item?: number;
20
20
  };
21
- /** The params to merge into the previous call to continue toward older events. */
22
21
  export declare const HistoryOlderSchema: Type.TObject<{
23
22
  session: Type.TOptional<Type.TString>;
24
23
  before_seq: Type.TInteger;
25
24
  }>;
26
- /** The params to merge into the previous call to continue toward newer events. */
27
25
  export declare const HistoryNewerSchema: Type.TObject<{
28
26
  session: Type.TOptional<Type.TString>;
29
27
  after_seq: Type.TInteger;
@@ -28,12 +28,10 @@ function resolveTimeBounds(params) {
28
28
  }
29
29
  return success({ ...(since.data === undefined ? {} : { sinceMs: since.data }), ...(until.data === undefined ? {} : { untilMs: until.data }) });
30
30
  }
31
- /** The params to merge into the previous call to continue toward older events. */
32
31
  export const HistoryOlderSchema = Type.Object({
33
32
  session: Type.Optional(Type.String()),
34
33
  before_seq: Type.Integer({ minimum: 1 }),
35
34
  }, { additionalProperties: false });
36
- /** The params to merge into the previous call to continue toward newer events. */
37
35
  export const HistoryNewerSchema = Type.Object({
38
36
  session: Type.Optional(Type.String()),
39
37
  after_seq: Type.Integer({ minimum: 1 }),
@@ -42,8 +40,8 @@ export const HistoryNewerSchema = Type.Object({
42
40
  export const HistoryPageSchema = Type.Object({
43
41
  notice: Type.Optional(Type.String()),
44
42
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
45
- page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
46
- page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
43
+ page_older: Type.Union([HistoryOlderSchema, Type.Null()], { description: "Args to merge into `history_list` for older events." }),
44
+ page_newer: Type.Union([HistoryNewerSchema, Type.Null()], { description: "Args to merge into `history_list` for newer events." }),
47
45
  }, { additionalProperties: false });
48
46
  /** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
49
47
  function truncateHistoryItem(item, fits) {
@@ -44,12 +44,10 @@ export type NotesQuery = {
44
44
  crumpled?: boolean;
45
45
  };
46
46
  /** A read exposes metadata and the pure body; the serialized frontmatter is never part of the body. */
47
- /** `accessedBefore` is the last access before this read, so a read never hides how long a note sat unread. */
48
47
  export type NoteReadResult = {
49
48
  meta: NoteMeta;
50
49
  body: string;
51
50
  resolvedScope: Scope;
52
- accessedBefore: number;
53
51
  };
54
52
  export type NoteWriteResult = {
55
53
  meta: NoteMeta;
@@ -300,11 +300,11 @@ export function createNotesStore(input) {
300
300
  const parsed = parseNote(raw, now);
301
301
  // Named notebooks, and every read during a dream, leave no access stamp.
302
302
  if (identity.dreaming !== undefined || ((scope === "project" || scope === "session") && destination.who !== undefined))
303
- return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
303
+ return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
304
304
  // A read records its own access, exactly as a write records an edit.
305
305
  const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
306
306
  await atomicWrite(path, serializeNote(meta, parsed.body));
307
- return { meta, body: parsed.body, resolvedScope: scope, accessedBefore: parsed.meta.lastAccessed };
307
+ return { meta, body: parsed.body, resolvedScope: scope };
308
308
  });
309
309
  }
310
310
  async function update(address, edits, options = {}) {
@@ -25,9 +25,11 @@ export declare const dreamBeginParameters: Type.TObject<{
25
25
  export declare const DreamBeginDataSchema: Type.TObject<{
26
26
  more: Type.TInteger;
27
27
  namespaces_unavailable: Type.TArray<Type.TString>;
28
+ project: Type.TString;
29
+ baseline: Type.TString;
28
30
  files: Type.TArray<Type.TObject<{
29
- updated_at: Type.TString;
30
31
  last_accessed: Type.TString;
32
+ updated_at: Type.TString;
31
33
  crumpled_at: Type.TOptional<Type.TString>;
32
34
  project_root: Type.TOptional<Type.TString>;
33
35
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -37,8 +39,6 @@ export declare const DreamBeginDataSchema: Type.TObject<{
37
39
  address: Type.TString;
38
40
  project_key: Type.TOptional<Type.TString>;
39
41
  }>>;
40
- project: Type.TString;
41
- baseline: Type.TString;
42
42
  }>;
43
43
  export type DreamBeginData = Static<typeof DreamBeginDataSchema>;
44
44
  export declare const dreamBegin: {
@@ -51,9 +51,11 @@ export declare const dreamBegin: {
51
51
  readonly outputSchema: Type.TUnion<[Type.TObject<{
52
52
  more: Type.TInteger;
53
53
  namespaces_unavailable: Type.TArray<Type.TString>;
54
+ project: Type.TString;
55
+ baseline: Type.TString;
54
56
  files: Type.TArray<Type.TObject<{
55
- updated_at: Type.TString;
56
57
  last_accessed: Type.TString;
58
+ updated_at: Type.TString;
57
59
  crumpled_at: Type.TOptional<Type.TString>;
58
60
  project_root: Type.TOptional<Type.TString>;
59
61
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -63,8 +65,6 @@ export declare const dreamBegin: {
63
65
  address: Type.TString;
64
66
  project_key: Type.TOptional<Type.TString>;
65
67
  }>>;
66
- project: Type.TString;
67
- baseline: Type.TString;
68
68
  }>, Type.TObject<{
69
69
  error: Type.TString;
70
70
  code: Type.TString;
@@ -1,11 +1,12 @@
1
1
  /** Dream operations: open one project's notes for consolidation, delete crumpled notes, close. */
2
2
  import { Type } from "typebox";
3
+ import { localIso } from "../notes/frontmatter.js";
3
4
  import { createNotesStore, noteIdentity } from "../notes/index.js";
4
5
  import { projectNamespaces } from "../notes/project-namespace.js";
5
6
  import { gitCommit } from "../dream/git.js";
6
7
  import { acquireDreamLock, dreamLockPath, releaseDreamLock } from "../dream/lock.js";
7
8
  import { failure, renderOutcome, resultSchema, success } from "./result.js";
8
- import { failureOf, listedFile, NoteIdentitySchema, NotesListDataSchema, renderListData, snapshot } from "./notes.js";
9
+ import { failureOf, listedFile, ListedFileSchema, NoteIdentitySchema, renderListData, snapshot, SnapshotSchema } from "./notes.js";
9
10
  function currentOpening(state, opening) {
10
11
  return state.pending === opening && state.generation === opening.generation;
11
12
  }
@@ -44,7 +45,11 @@ const NOT_DREAMING = "No dream is open; call dream_begin first.";
44
45
  export const dreamBeginParameters = Type.Object({
45
46
  project: Type.Optional(Type.String({ description: "(optional, default this project) Project name, as in @projects/<name>/." })),
46
47
  }, { additionalProperties: false });
47
- export const DreamBeginDataSchema = Type.Object({ project: Type.String(), baseline: Type.String(), ...NotesListDataSchema.properties }, { additionalProperties: false });
48
+ export const DreamBeginDataSchema = Type.Object({
49
+ project: Type.String(), baseline: Type.String(),
50
+ files: Type.Array(Type.Object({ ...ListedFileSchema.properties, last_accessed: Type.String() }, { additionalProperties: false })),
51
+ ...SnapshotSchema,
52
+ }, { additionalProperties: false });
48
53
  function renderBeginData(data) {
49
54
  return `dreaming over ${data.project} (baseline ${data.baseline})\n${renderListData(data)}`;
50
55
  }
@@ -81,7 +86,7 @@ export const dreamBegin = {
81
86
  }
82
87
  }
83
88
  rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
84
- const listed = snapshot(rows.map(row => listedFile(row, identity)), undefined, { namespacesUnavailable: unavailable }, renderListData);
89
+ const listed = snapshot(rows.map(row => ({ ...listedFile(row, identity), last_accessed: localIso(row.meta.lastAccessed) })), undefined, { namespacesUnavailable: unavailable }, renderListData);
85
90
  if (!listed.ok) {
86
91
  releaseOpening(state, opening);
87
92
  return listed;
@@ -12,7 +12,6 @@ export declare const NoteMetadataSchema: Type.TObject<{
12
12
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
13
13
  created_at: Type.TString;
14
14
  updated_at: Type.TString;
15
- last_accessed: Type.TString;
16
15
  crumpled_at: Type.TOptional<Type.TString>;
17
16
  project: Type.TOptional<Type.TString>;
18
17
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -36,6 +35,21 @@ export declare const NoteIdentitySchema: {
36
35
  address: Type.TString;
37
36
  project_key: Type.TOptional<Type.TString>;
38
37
  };
38
+ export declare const ListedFileSchema: Type.TObject<{
39
+ updated_at: Type.TString;
40
+ crumpled_at: Type.TOptional<Type.TString>;
41
+ project_root: Type.TOptional<Type.TString>;
42
+ project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
43
+ name: Type.TString;
44
+ path: Type.TString;
45
+ }>>>;
46
+ address: Type.TString;
47
+ project_key: Type.TOptional<Type.TString>;
48
+ }>;
49
+ export declare const SnapshotSchema: {
50
+ more: Type.TInteger;
51
+ namespaces_unavailable: Type.TArray<Type.TString>;
52
+ };
39
53
  export declare const NotesWriteDataSchema: Type.TObject<{
40
54
  outcome: Type.TUnion<[Type.TLiteral<"created">, Type.TLiteral<"overwrote">, Type.TLiteral<"uncrumpled">]>;
41
55
  project_root: Type.TOptional<Type.TString>;
@@ -67,7 +81,6 @@ export declare const NotesReadDataSchema: Type.TObject<{
67
81
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
68
82
  created_at: Type.TString;
69
83
  updated_at: Type.TString;
70
- last_accessed: Type.TString;
71
84
  crumpled_at: Type.TOptional<Type.TString>;
72
85
  project: Type.TOptional<Type.TString>;
73
86
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -86,7 +99,6 @@ export declare const NotesListDataSchema: Type.TObject<{
86
99
  namespaces_unavailable: Type.TArray<Type.TString>;
87
100
  files: Type.TArray<Type.TObject<{
88
101
  updated_at: Type.TString;
89
- last_accessed: Type.TString;
90
102
  crumpled_at: Type.TOptional<Type.TString>;
91
103
  project_root: Type.TOptional<Type.TString>;
92
104
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -108,7 +120,6 @@ export declare const NotesSearchDataSchema: Type.TObject<{
108
120
  offset_chars: Type.TInteger;
109
121
  }>>;
110
122
  updated_at: Type.TString;
111
- last_accessed: Type.TString;
112
123
  crumpled_at: Type.TOptional<Type.TString>;
113
124
  project_root: Type.TOptional<Type.TString>;
114
125
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -231,7 +242,6 @@ export declare const notesRead: {
231
242
  origin: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"self">, Type.TLiteral<"external">]>;
232
243
  created_at: Type.TString;
233
244
  updated_at: Type.TString;
234
- last_accessed: Type.TString;
235
245
  crumpled_at: Type.TOptional<Type.TString>;
236
246
  project: Type.TOptional<Type.TString>;
237
247
  extra: Type.TRecord<"^.*$", Type.TUnknown>;
@@ -256,7 +266,9 @@ export declare const notesListParameters: Type.TObject<{
256
266
  crumpled: Type.TOptional<Type.TBoolean>;
257
267
  cwd: Type.TOptional<Type.TString>;
258
268
  }>;
259
- export declare function renderListData(data: NotesListData): string;
269
+ export declare function renderListData(data: Snapshot<NotesListData["files"][number] & {
270
+ last_accessed?: string;
271
+ }>): string;
260
272
  export declare const notesList: {
261
273
  readonly name: "notes_list";
262
274
  readonly label: "Notes list";
@@ -272,7 +284,6 @@ export declare const notesList: {
272
284
  namespaces_unavailable: Type.TArray<Type.TString>;
273
285
  files: Type.TArray<Type.TObject<{
274
286
  updated_at: Type.TString;
275
- last_accessed: Type.TString;
276
287
  crumpled_at: Type.TOptional<Type.TString>;
277
288
  project_root: Type.TOptional<Type.TString>;
278
289
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -321,7 +332,6 @@ export declare const notesSearch: {
321
332
  offset_chars: Type.TInteger;
322
333
  }>>;
323
334
  updated_at: Type.TString;
324
- last_accessed: Type.TString;
325
335
  crumpled_at: Type.TOptional<Type.TString>;
326
336
  project_root: Type.TOptional<Type.TString>;
327
337
  project_siblings: Type.TOptional<Type.TArray<Type.TObject<{
@@ -42,7 +42,6 @@ export const NoteMetadataSchema = Type.Object({
42
42
  origin: Type.Union([...ORIGIN_VALUES]),
43
43
  created_at: Type.String(),
44
44
  updated_at: Type.String(),
45
- last_accessed: Type.String(),
46
45
  crumpled_at: Type.Optional(Type.String()),
47
46
  project: Type.Optional(Type.String()),
48
47
  extra: Type.Record(Type.String(), Type.Unknown()),
@@ -74,7 +73,6 @@ function noteMetadata(meta) {
74
73
  origin: meta.origin,
75
74
  created_at: localIso(meta.createdAt),
76
75
  updated_at: localIso(meta.updatedAt),
77
- last_accessed: localIso(meta.lastAccessed),
78
76
  ...(typeof meta.crumpledAt === "string" ? { crumpled_at: meta.crumpledAt } : {}),
79
77
  ...(typeof meta.project === "string" ? { project: meta.project } : {}),
80
78
  extra,
@@ -85,7 +83,6 @@ function renderMetadata(metadata) {
85
83
  `origin ${metadata.origin}`,
86
84
  `created ${metadata.created_at}`,
87
85
  `updated ${metadata.updated_at}`,
88
- `accessed ${metadata.last_accessed}`,
89
86
  ...(metadata.crumpled_at === undefined ? [] : [`crumpled ${metadata.crumpled_at}`]),
90
87
  ...(metadata.project === undefined ? [] : [`project ${metadata.project}`]),
91
88
  ];
@@ -114,10 +111,9 @@ export const NoteIdentitySchema = {
114
111
  project_key: Type.Optional(Type.String()),
115
112
  ...ProjectReceiptSchema,
116
113
  };
117
- const ListedFileSchema = Type.Object({
114
+ export const ListedFileSchema = Type.Object({
118
115
  ...NoteIdentitySchema,
119
116
  updated_at: Type.String(),
120
- last_accessed: Type.String(),
121
117
  crumpled_at: Type.Optional(Type.String()),
122
118
  }, { additionalProperties: false });
123
119
  const MatchSchema = Type.Object({
@@ -129,9 +125,9 @@ const SearchedFileSchema = Type.Object({
129
125
  ...ListedFileSchema.properties,
130
126
  matches: Type.Array(MatchSchema),
131
127
  }, { additionalProperties: false });
132
- const SnapshotSchema = {
128
+ export const SnapshotSchema = {
133
129
  more: Type.Integer({ description: "How many more were left out." }),
134
- namespaces_unavailable: Type.Array(Type.String()),
130
+ namespaces_unavailable: Type.Array(Type.String(), { description: "Unreadable notebooks or notes." }),
135
131
  };
136
132
  export const NotesWriteDataSchema = Type.Object({
137
133
  ...NoteIdentitySchema,
@@ -179,7 +175,7 @@ export function snapshot(rows, limit, status, renderData, shrink) {
179
175
  return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
180
176
  }
181
177
  export function listedFile(row, identity) {
182
- return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), last_accessed: localIso(row.meta.lastAccessed), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
178
+ return { ...noteIdentity(identity, row.address), updated_at: localIso(row.meta.updatedAt), ...(row.meta.crumpledAt === undefined ? {} : { crumpled_at: row.meta.crumpledAt }) };
183
179
  }
184
180
  export const notesWriteParameters = Type.Object({ address: Type.String(), content: Type.String(), origin: ORIGIN, cwd: CWD_PARAMETER }, { additionalProperties: false });
185
181
  function renderWriteData(data) {
@@ -255,8 +251,7 @@ export const notesRead = {
255
251
  const totalChars = Array.from(note.body).length;
256
252
  if (params.offset_chars !== undefined && params.offset_chars > totalChars)
257
253
  return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
258
- // Report the access before this one: the read itself must not make a long-unread note look fresh.
259
- const metadata = noteMetadata({ ...note.meta, lastAccessed: note.accessedBefore });
254
+ const metadata = noteMetadata(note.meta);
260
255
  return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, ...window }), (result) => renderOutcome(result, renderReadData));
261
256
  }
262
257
  catch (error) {
@@ -269,7 +264,7 @@ export const notesListParameters = Type.Object({ glob: GLOB_PARAMETER, limit: FI
269
264
  export function renderListData(data) {
270
265
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
271
266
  for (const file of data.files) {
272
- lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at} | accessed ${file.last_accessed}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
267
+ lines.push(`- ${renderIdentity(file)} | updated ${file.updated_at}${file.last_accessed === undefined ? "" : ` | accessed ${file.last_accessed}`}${file.crumpled_at === undefined ? "" : ` | crumpled ${file.crumpled_at}`}`);
273
268
  }
274
269
  if (data.more > 0)
275
270
  lines.push(`${data.more} more matching notes omitted; narrow with glob`);
@@ -6,8 +6,9 @@ import test from "node:test";
6
6
  import { createAssistantMessageEventStream, getCurrentSystemMessage } from "@earendil-works/pi-ai";
7
7
  import { createAgentSession, createCodemodeExtension, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
8
8
  import notesoup, { createNotesoup } from "../plugins/pi/extension.js";
9
- import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, NEXT_WINDOW_PROMPT_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
9
+ import { BOOT_TYPE, CARRIED_INPUT_TYPE, CONTINUATION_TYPE, GUIDANCE_TYPE, MANUAL_WIPE_TYPE, MARKER_TYPE, NEXT_WINDOW_PROMPT_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
10
10
  import { historyFromSession } from "../plugins/pi/history.js";
11
+ import { MARKER_INTERVAL } from "../plugins/pi/marker.js";
11
12
  import { assertBootHistory } from "./helpers/extension.js";
12
13
  import { NOTES_PROTOCOL_OPEN_TAG, WINDOW_IDENTITY_OPEN_TAG } from "../src/boot/text.js";
13
14
  import { FORCED_CONTINUATIONS, GUIDANCE_OPEN_TAG, NORMAL_CONTINUATIONS, warningPrompt } from "../src/budget/text.js";
@@ -235,6 +236,48 @@ function assertFreshRequest(fixture, requestIndex, oldSentinel) {
235
236
  assert.ok(body.includes(WINDOW_IDENTITY_OPEN_TAG), "the new provider request includes the fresh context-window boot");
236
237
  assert.deepEqual(continuationLinesIn(body).length, 1, "the fresh window carries exactly one reset paragraph");
237
238
  }
239
+ test("real AgentSession: turn-end markers reach tool continuations and allow one-turn lag when steering crosses the interval", async () => {
240
+ for (const seedCount of [MARKER_INTERVAL - 4, MARKER_INTERVAL - 7]) {
241
+ let starts = 0;
242
+ let fixture;
243
+ fixture = await openFixture({
244
+ compactionEnabled: false,
245
+ hook: (pi, getSession) => {
246
+ pi.on("before_agent_start", () => { starts++; });
247
+ pi.on("tool_call", async () => { await getSession().steer("MARKER_MID_RUN_USER"); });
248
+ },
249
+ script: (request) => request === 1
250
+ ? assistant(fixture, [{ type: "toolCall", id: "marker-tool", name: "get_context_remaining", arguments: {} }], "toolUse")
251
+ : assistant(fixture, [{ type: "text", text: "steered input handled" }]),
252
+ });
253
+ try {
254
+ for (let i = 0; i < seedCount; i++)
255
+ fixture.sessionManager.appendMessage(assistant(fixture, [{ type: "text", text: "seed" }]));
256
+ await fixture.session.prompt("MARKER_INITIAL_USER");
257
+ await fixture.session.waitForIdle();
258
+ assert.equal(starts, 1);
259
+ assert.equal(fixture.requests.length, 2, "the marker does not create another model request");
260
+ assert.equal(text(fixture.requests[0]).includes("notesoup:marker"), false);
261
+ assert.equal(text(fixture.requests[1]).includes("notesoup:marker"), seedCount === MARKER_INTERVAL - 4);
262
+ assert.equal(text(fixture.requests[1]).split("MARKER_MID_RUN_USER").length - 1, 1);
263
+ const branch = fixture.sessionManager.getBranch();
264
+ const markers = branch.filter((entry) => entry.type === "custom_message" && entry.customType === MARKER_TYPE);
265
+ assert.equal(markers.length, 1);
266
+ const marker = markers[0];
267
+ const markerIndex = branch.indexOf(marker);
268
+ const userIndex = branch.findIndex((entry) => entry.type === "message" && entry.message.role === "user" && JSON.stringify(entry.message.content).includes("MARKER_MID_RUN_USER"));
269
+ assert.equal(markerIndex < userIndex, seedCount === MARKER_INTERVAL - 4, "a steering-only threshold crossing is marked after its response");
270
+ assert.ok(branch.slice(0, markerIndex).some((entry) => entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolCallId === "marker-tool"));
271
+ const projection = historyFromSession({ sessionManager: fixture.sessionManager });
272
+ const addressed = projection.windows.flatMap((window) => window.items).find((item) => item.text.includes("<notesoup:marker"));
273
+ assert.ok(addressed);
274
+ assert.deepEqual(marker.type === "custom_message" ? marker.details : undefined, { seq: addressed.seq });
275
+ }
276
+ finally {
277
+ fixture.close();
278
+ }
279
+ }
280
+ });
238
281
  test("real Pi codemode receives typed notes/history outcomes, including expected errors", async () => {
239
282
  let fixture;
240
283
  fixture = await openFixture({
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
2
2
  import { join } from "node:path";
3
3
  import test from "node:test";
4
4
  import { SettingsManager } from "@earendil-works/pi-coding-agent";
5
+ import { Check } from "typebox/value";
5
6
  import { DEFAULT_REMINDER_MARGIN_TOKENS, DEFAULT_RESERVE_TOKENS } from "../src/budget/constants.js";
6
7
  import { GUIDANCE_TYPE, RESET_MARKER_TYPE, WARNING_TYPE } from "../plugins/pi/entries.js";
7
8
  import { deriveThresholds } from "../src/budget/policy.js";
@@ -115,6 +116,23 @@ test("early guidance stays silent and the final warning notifies immediately onc
115
116
  await runHandlers(captured, "agent_settled", {}, final);
116
117
  assert.equal(noticesOf(final).filter((notice) => notice.message === "🥣 Brain almost full").length, 1, "repeated injection and commit do not notify again");
117
118
  });
119
+ test("get_context_remaining declares its output and returns matching structured and text values", async () => {
120
+ const fixture = settingsFixture({ reserveTokens: 16_384 });
121
+ const sm = manager();
122
+ const captured = makeExtension(sm);
123
+ const schema = captured.tools.get("get_context_remaining")?.outputSchema;
124
+ assert.ok(schema, "the registered tool declares an output schema");
125
+ for (const [tokens, expected] of [[72_563, 111_053], [null, null]]) {
126
+ const ctx = context(sm, undefined, { tokens, contextWindow: 200_000, percent: tokens === null ? null : tokens / 2000 }, true, fixture.cwd);
127
+ const result = await call(captured, "get_context_remaining", {}, ctx);
128
+ assert.deepEqual(result.structuredContent, { remaining_tokens: expected });
129
+ assert.deepEqual(result.structuredContent, resultJson(result));
130
+ assert.equal(Check(schema, result.structuredContent), true);
131
+ const text = result.content[0];
132
+ assert.ok(text && text.type === "text");
133
+ assert.equal(text.text, JSON.stringify(result.structuredContent));
134
+ }
135
+ });
118
136
  test("the reported room ends at the hard reserve, clamps at zero, and preserves unknown usage", async () => {
119
137
  const fixture = settingsFixture({
120
138
  reserveTokens: 16_384,
@@ -132,18 +132,37 @@ test("baseline failure releases pending ownership and permits a retry", async (t
132
132
  assert.ok((await dreamBegin.execute({}, me, state)).ok);
133
133
  assert.ok((await dreamEnd.execute({}, me, state)).ok);
134
134
  });
135
- test("notes_read reports the access before itself, so reading never makes an unread note look fresh", async (t) => {
135
+ test("dream_begin reports the stored access, and dream reads do not refresh it", async (t) => {
136
136
  const { home, as } = fixture(t);
137
137
  const me = as("s", "alpha");
138
+ const state = {};
138
139
  const old = "2026-01-01T08:00:00.000+08:00";
139
- mkdirSync(join(home, "human"), { recursive: true });
140
- writeFileSync(join(home, "human", "stale.md"), `---\norigin: self\ncreatedAt: ${old}\nupdatedAt: ${old}\nlastAccessed: ${old}\naccessCount: 0\n---\n\nbody`);
141
- const first = await notesRead.execute({ address: "@human/stale" }, notesToolContext(me, "/work/alpha"));
140
+ writeFileSync(join(home, "project", "alpha", "stale.md"), `---\norigin: self\ncreatedAt: ${old}\nupdatedAt: ${old}\nlastAccessed: ${old}\naccessCount: 0\n---\n\nbody`);
141
+ const first = await dreamBegin.execute({}, me, state);
142
142
  assert.ok(first.ok);
143
- assert.equal(Date.parse(first.data.metadata.last_accessed), Date.parse(old), "the first read shows the old access");
144
- const second = await notesRead.execute({ address: "@human/stale" }, notesToolContext(me, "/work/alpha"));
143
+ assert.equal(Check(dreamBegin.outputSchema, first.data), true);
144
+ const row = first.data.files[0];
145
+ assert.equal(row.address, "@projects/alpha/stale.md");
146
+ assert.equal(Date.parse(row.last_accessed), Date.parse(old), "the dream shows the pre-dream access");
147
+ assert.ok(dreamBegin.render(first).includes(` | accessed ${row.last_accessed}`));
148
+ const read = await notesRead.execute({ address: "@project/stale" }, notesToolContext(dreamingIdentity(me, state), "/work/alpha"));
149
+ assert.ok(read.ok && read.data.text === "body");
150
+ const during = (await createNotesStore(me).list({ glob: "@project/**" }))[0];
151
+ assert.equal(during.meta.lastAccessed, Date.parse(old));
152
+ assert.equal(during.meta.accessCount, 0, "dream reads leave storage untouched");
153
+ assert.ok((await dreamEnd.execute({}, me, state)).ok);
154
+ const second = await dreamBegin.execute({}, me, state);
145
155
  assert.ok(second.ok);
146
- assert.ok(Date.parse(second.data.metadata.last_accessed) > Date.parse(old), "the first read still counted as an access");
156
+ assert.equal(second.data.files[0].last_accessed, row.last_accessed, "a later dream sees the same pre-dream access");
157
+ assert.ok((await dreamEnd.execute({}, me, state)).ok);
158
+ assert.ok((await notesRead.execute({ address: "@project/stale" }, notesToolContext(me, "/work/alpha"))).ok);
159
+ const after = (await createNotesStore(me).list({ glob: "@project/**" }))[0];
160
+ assert.equal(after.meta.accessCount, 1, "ordinary reads still stamp storage");
161
+ const third = await dreamBegin.execute({}, me, state);
162
+ assert.ok(third.ok);
163
+ assert.equal(Date.parse(third.data.files[0].last_accessed), after.meta.lastAccessed);
164
+ assert.ok(after.meta.lastAccessed > Date.parse(old));
165
+ assert.ok((await dreamEnd.execute({}, me, state)).ok);
147
166
  });
148
167
  test("dream_begin refuses an unknown project", async (t) => {
149
168
  const { as } = fixture(t);