@aeondave/pi-persona-mind 0.9.6 → 0.9.8

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 (55) hide show
  1. package/AGENTS.md +137 -135
  2. package/CHANGELOG.md +287 -270
  3. package/LICENSE +24 -24
  4. package/README.md +84 -171
  5. package/docs/DESIGN.md +605 -573
  6. package/docs/MEMORY-RESEARCH.md +163 -163
  7. package/package.json +15 -6
  8. package/src/core/auto-optimize.ts +323 -249
  9. package/src/core/backlog.ts +228 -228
  10. package/src/core/blocked.ts +38 -38
  11. package/src/core/capture.ts +155 -154
  12. package/src/core/context-budget.ts +74 -74
  13. package/src/core/handoff-store.ts +111 -111
  14. package/src/core/handoff.ts +70 -70
  15. package/src/core/host-compat.ts +16 -16
  16. package/src/core/ids.ts +59 -59
  17. package/src/core/inject.ts +247 -247
  18. package/src/core/knowledge-review.ts +107 -107
  19. package/src/core/memory-read.ts +34 -34
  20. package/src/core/memory.ts +321 -321
  21. package/src/core/migrate.ts +713 -713
  22. package/src/core/mind-settings.ts +54 -54
  23. package/src/core/optimize-history.ts +163 -163
  24. package/src/core/optimize-service.ts +189 -180
  25. package/src/core/optimize.ts +127 -127
  26. package/src/core/retrieval.ts +164 -164
  27. package/src/core/scanner.ts +146 -146
  28. package/src/core/scope.ts +201 -205
  29. package/src/core/service.ts +720 -720
  30. package/src/core/session-memory.ts +71 -71
  31. package/src/core/store.ts +1002 -1002
  32. package/src/extension/activity.ts +79 -79
  33. package/src/extension/auto-optimize-session.ts +143 -143
  34. package/src/extension/auto-optimize.ts +565 -569
  35. package/src/extension/handoff.ts +23 -23
  36. package/src/extension/knowledge-review.ts +229 -229
  37. package/src/extension/memory-inspector.ts +82 -82
  38. package/src/extension/mind-actions.ts +38 -38
  39. package/src/extension/mind-worker.ts +32 -32
  40. package/src/extension/persona-dependency.ts +76 -76
  41. package/src/extension/reference-anchor.ts +48 -0
  42. package/src/extension/review-evidence.ts +222 -222
  43. package/src/extension/worker-memory-anchor.ts +28 -28
  44. package/src/index.ts +1357 -1310
  45. package/src/session-memory.ts +127 -122
  46. package/src/tools/backlog.ts +126 -126
  47. package/src/tools/memory-handoff.ts +30 -30
  48. package/src/tools/memory-history.ts +46 -46
  49. package/src/tools/memory.ts +6 -4
  50. package/src/ui/card-frame.ts +161 -161
  51. package/src/ui/inspector-frame.ts +44 -44
  52. package/src/ui/memory-inspector.ts +464 -464
  53. package/src/ui/mind-result-card.ts +48 -48
  54. package/src/ui/presentation.ts +87 -87
  55. package/src/ui/session-note-card.ts +58 -56
@@ -1,154 +1,155 @@
1
- /**
2
- * Deterministic, model-free capture-cue detection — the counter to the structural weakness of a
3
- * purely explicit memory (the agent forgets to call `remember`). Scans a user message for phrasing
4
- * that signals a durable preference/convention/instruction, and returns a candidate the extension
5
- * can either persist (only for direct, explicit user intent) or surface as a gentle candidate.
6
- *
7
- * No LLM, no network: just cues. A cue is auto-eligible only when the persistence request starts
8
- * the user's own sentence; instruction-shaped prose quoted inside a report remains nudge-only.
9
- */
10
-
11
- import type { MemoryKind } from "./memory.ts";
12
-
13
- export interface CaptureCue {
14
- /** The cued sentence (trimmed, length-capped) — quoted back in the nudge. */
15
- snippet: string;
16
- /** The suggested memory kind for the candidate. */
17
- kind: MemoryKind;
18
- /** Capture is always provisional in the native active session, regardless of durability wording. */
19
- term: "session";
20
- /** True only for a sentence-initial EXPLICIT persist-intent phrase ("from now on", "remember
21
- * that", "for future reference") — as opposed to casual "always/never"/"I prefer" or a cue
22
- * quoted inside a report. AUTO may capture only this high-confidence class, session-locally. */
23
- strong: boolean;
24
- /** The durable fact with the cue phrase removed when it can be done deterministically. */
25
- candidate: string;
26
- }
27
-
28
- export type CaptureMode = "auto" | "prompt" | "off";
29
-
30
- /** Automatic capture is limited to direct, explicit user intent. `prompt` keeps the old nudge-only
31
- * behaviour; `off` disables both detection and capture. Invalid values fail back to the safe,
32
- * useful default instead of silently disabling memory. */
33
- export function captureMode(env: NodeJS.ProcessEnv = process.env): CaptureMode {
34
- const configured = env.PI_PERSONA_MIND_CAPTURE?.trim().toLowerCase();
35
- return configured === "prompt" || configured === "off" ? configured : "auto";
36
- }
37
-
38
- interface CuePattern {
39
- re: RegExp;
40
- kind: MemoryKind;
41
- }
42
-
43
- // Ordered by specificity: the first match wins and picks the kind.
44
- const CUES: CuePattern[] = [
45
- { re: /\b(?:architectural\s+decision|durable\s+decision|permanent\s+convention|stable\s+invariant|decisione\s+architetturale|decisione\s+durevole|convenzione\s+permanente|invariante\s+stabile)\b/i, kind: "rationale" },
46
- { re: /\b(?:always|never)\b/i, kind: "convention" },
47
- { re: /\b(?:i\s+prefer|i'd\s+prefer|prefer\s+that|from\s+now\s+on|going\s+forward|in\s+(?:the\s+)?future|preferisco|preferirei|da\s+ora\s+in\s+poi|da\s+questo\s+momento|d['’]ora\s+in\s+poi|in\s+futuro|per\s+il\s+futuro)\b/i, kind: "preference" },
48
- { re: /\b(?:remember(?:\s+that)?|keep\s+in\s+mind|note\s+that|don'?t\s+forget|for\s+future\s+reference|commit\s+(?:this\s+)?to\s+memory|ricorda(?:ti)?(?:\s+(?:che|di))?|tieni\s+(?:a\s+mente|presente)|nota\s+che|non\s+dimentica(?:re|rti)|memorizza|segnati|conserva\s+in\s+memoria|salva(?:lo)?\s+(?:in|nella)\s+memoria)\b/i, kind: "note" },
49
- { re: /\b(?:the\s+user\s+is|i\s+am\s+(?:on|using)|i'm\s+(?:on|using)|we\s+use|my\s+\w+\s+is|io\s+uso|uso\s+\w+|usiamo)\b/i, kind: "preference" },
50
- ];
51
-
52
- const MAX_SNIPPET = 200;
53
-
54
- const DIRECT_DECISION_OWNER = /^\s*(?:we\b|i\b|this\s+project\b|for\s+this\s+project\b|abbiamo\b|ho\b|questo\s+progetto\b|per\s+questo\s+progetto\b)/i;
55
- const DURABLE_WORD = /\b(?:durable|permanent|stable|durevole|permanente|stabile)\b/i;
56
- const DECISION_WORD = /\b(?:architectural\s+decision|decision|convention|invariant|decisione\s+architetturale|decisione|convenzione|invariante)\b/i;
57
- const DECISION_ACTION = /\b(?:decided|chosen|chose|adopted|established|made|set|abbiamo\s+(?:deciso|scelto|adottato|stabilito|definito)|ho\s+(?:deciso|scelto|adottato|stabilito|definito))\b/i;
58
- const REPORTED_DECISION = /^\s*(?:i\s+(?:saw|noticed|read|heard|observed|found|learned)\b|ho\s+(?:visto|notato|letto|sentito|osservato|scoperto|appreso)\b|mi\s+sono\s+accort[oa]\b)/i;
59
-
60
- function isDirectDurableDecision(sentence: string): boolean {
61
- if (REPORTED_DECISION.test(sentence) || !DIRECT_DECISION_OWNER.test(sentence) || !DURABLE_WORD.test(sentence) || !DECISION_WORD.test(sentence)) return false;
62
- const action = DECISION_ACTION.exec(sentence);
63
- if (action === null) return false;
64
- const colon = sentence.indexOf(":");
65
- // Reject negation anywhere in a premise that extraction would discard. Otherwise inspect
66
- // only before the adoption verb: a negative fact remains eligible and keeps its wording.
67
- const premiseEnd = colon >= 0 && sentence.slice(colon + 1).trim() ? colon : action.index;
68
- return !/\b(?:never|not|non|mai)\b|n['’]t\b/i.test(sentence.slice(0, premiseEnd));
69
- }
70
-
71
- /** Split into sentences on ., !, ?, newline — coarse but enough to isolate the cued clause. */
72
- function sentences(text: string): string[] {
73
- // Foreign/quoted material is data, not the user's own persistence request. Parse Markdown fences
74
- // linearly so an unclosed fence also consumes the rest; a regex that requires a closing ``` would
75
- // turn malformed pasted code into durable memory. Four-space/tab-indented code is data too.
76
- let fence: { char: "`" | "~"; width: number } | undefined;
77
- const prose: string[] = [];
78
- for (const line of text.split(/\r?\n/)) {
79
- const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
80
- if (fence) {
81
- if (marker?.[0] === fence.char && marker.length >= fence.width) fence = undefined;
82
- continue;
83
- }
84
- if (marker) {
85
- fence = { char: marker[0] as "`" | "~", width: marker.length };
86
- continue;
87
- }
88
- if (/^(?: {4,}|\t)/.test(line) || /^\s*>/.test(line)) continue;
89
- prose.push(line);
90
- }
91
- return prose
92
- .join("\n")
93
- .split(/(?<=[.!?])\s+|\n+/)
94
- .map((s) => s.trim())
95
- .filter(Boolean);
96
- }
97
-
98
- const CUE_PREFIXES: readonly { re: RegExp; explicit: boolean }[] = [
99
- { re: /^\s*(?:please\s+)?(?:remember(?:\s+that)?|keep\s+in\s+mind(?:\s+that)?|don'?t\s+forget(?:\s+that)?|for\s+future\s+reference|commit\s+(?:this\s+)?to\s+memory(?:\s+that)?)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
100
- { re: /^\s*(?:i\s+(?:want|need)\s+you\s+to\s+remember(?:\s+that)?)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
101
- { re: /^\s*(?:from\s+now\s+on|going\s+forward|in\s+the\s+future)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
102
- { re: /^\s*(?:per\s+favore\s+)?(?:ricorda(?:ti)?(?:\s+(?:che|di))?|tieni\s+(?:a\s+mente|presente)(?:\s+che)?|non\s+dimentica(?:re|rti)(?:\s+che)?|memorizza(?:\s+che)?|segnati(?:\s+che)?|conserva\s+in\s+memoria(?:\s+che)?|salva(?:lo)?\s+(?:in|nella)\s+memoria(?:\s+che)?)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
103
- { re: /^\s*(?:voglio\s+che\s+tu\s+ricordi(?:\s+che)?)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
104
- { re: /^\s*(?:da\s+ora\s+in\s+poi|da\s+questo\s+momento|d['’]ora\s+in\s+poi|in\s+futuro|per\s+il\s+futuro)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
105
- { re: /^\s*(?:i(?:'d)?\s+prefer|prefer\s+that|preferisco|preferirei)\s*[,;:\-]?\s*(.+)$/i, explicit: false },
106
- { re: /^\s*(?:note\s+that|nota\s+che)\s*[,;:\-]?\s*(.+)$/i, explicit: false },
107
- ];
108
-
109
- function candidateFor(sentence: string): { text: string; explicit: boolean } {
110
- // A Markdown/list marker is presentation owned by the user, not part of the requested fact.
111
- // Block quotes were already excluded by `sentences`, so accepting a bullet here does not turn
112
- // quoted foreign material into an automatic write.
113
- const direct = sentence.replace(/^\s*(?:(?:[-+*])\s+(?:\[[ xX]\]\s+)?|(?:\d+[.)])\s+)/, "");
114
- if (isDirectDurableDecision(direct)) {
115
- const colon = direct.indexOf(":");
116
- const afterColon = colon >= 0 ? direct.slice(colon + 1).trim() : "";
117
- const text = afterColon || direct;
118
- return { text, explicit: /[\p{L}\p{N}]/u.test(text) };
119
- }
120
- // "Always remember" reinforces consent; stripping "never" would reverse a refusal.
121
- const withoutAlways = direct.replace(/^\s*always\s+/i, "");
122
- for (const prefix of CUE_PREFIXES) {
123
- const match = prefix.re.exec(direct) ?? (withoutAlways !== direct ? prefix.re.exec(withoutAlways) : null);
124
- const candidate = match?.[1]?.trim();
125
- if (candidate) {
126
- const text = candidate;
127
- return { text, explicit: prefix.explicit && /[\p{L}\p{N}]/u.test(text) };
128
- }
129
- }
130
- return { text: direct, explicit: false };
131
- }
132
-
133
- /** Every durable cue in direct user prose, capped so a hostile/accidental wall of cues cannot turn
134
- * one input into an unbounded write burst. */
135
- export function detectCaptureCues(userText: string): CaptureCue[] {
136
- if (typeof userText !== "string" || !userText.trim()) return [];
137
- const found: CaptureCue[] = [];
138
- for (const sentence of sentences(userText)) {
139
- for (const cue of CUES) {
140
- if (!cue.re.test(sentence)) continue;
141
- const snippet = sentence.length > MAX_SNIPPET ? `${sentence.slice(0, MAX_SNIPPET - 1)}…` : sentence;
142
- const candidate = candidateFor(sentence);
143
- found.push({ snippet, kind: cue.kind, term: "session", strong: candidate.explicit, candidate: candidate.text });
144
- break;
145
- }
146
- if (found.length >= 4) break;
147
- }
148
- return found;
149
- }
150
-
151
- /** The first durable cue in `userText`, or null. Returns the cued sentence + a suggested kind. */
152
- export function detectCaptureCue(userText: string): CaptureCue | null {
153
- return detectCaptureCues(userText)[0] ?? null;
154
- }
1
+ /**
2
+ * Deterministic, model-free capture-cue detection — the counter to the structural weakness of a
3
+ * purely explicit memory (the agent forgets to call `remember`). Scans a user message for phrasing
4
+ * that signals a durable preference/convention/instruction, and returns a candidate the extension
5
+ * can either persist (only for direct, explicit user intent) or surface as a gentle candidate.
6
+ *
7
+ * No LLM, no network: just cues. A cue is auto-eligible only when the persistence request starts
8
+ * the user's own sentence; instruction-shaped prose quoted inside a report remains nudge-only.
9
+ */
10
+
11
+ import type { MemoryKind } from "./memory.ts";
12
+
13
+ export interface CaptureCue {
14
+ /** The cued sentence (trimmed, length-capped) — quoted back in the nudge. */
15
+ snippet: string;
16
+ /** The suggested memory kind for the candidate. */
17
+ kind: MemoryKind;
18
+ /** Capture is always provisional in the native active session, regardless of durability wording. */
19
+ term: "session";
20
+ /** True only for a sentence-initial EXPLICIT persist-intent phrase ("from now on", "remember
21
+ * that", "for future reference") — as opposed to casual "always/never"/"I prefer" or a cue
22
+ * quoted inside a report. AUTO may capture only this high-confidence class, session-locally. */
23
+ strong: boolean;
24
+ /** The durable fact with the cue phrase removed when it can be done deterministically. */
25
+ candidate: string;
26
+ }
27
+
28
+ export type CaptureMode = "auto" | "prompt" | "off";
29
+
30
+ /** Automatic capture is limited to direct, explicit user intent. `prompt` keeps the old nudge-only
31
+ * behaviour; `off` disables both detection and capture. Invalid values fail back to the safe,
32
+ * useful default instead of silently disabling memory. */
33
+ export function captureMode(env: NodeJS.ProcessEnv = process.env): CaptureMode {
34
+ const configured = env.PI_PERSONA_MIND_CAPTURE?.trim().toLowerCase();
35
+ return configured === "prompt" || configured === "off" ? configured : "auto";
36
+ }
37
+
38
+ interface CuePattern {
39
+ re: RegExp;
40
+ kind: MemoryKind;
41
+ }
42
+
43
+ // Ordered by specificity: the first match wins and picks the kind.
44
+ const CUES: CuePattern[] = [
45
+ { re: /\b(?:architectural\s+decision|durable\s+decision|permanent\s+convention|stable\s+invariant|decisione\s+architetturale|decisione\s+durevole|convenzione\s+permanente|invariante\s+stabile)\b/i, kind: "rationale" },
46
+ { re: /\b(?:always|never)\b/i, kind: "convention" },
47
+ { re: /\b(?:i\s+prefer|i'd\s+prefer|prefer\s+that|from\s+now\s+on|going\s+forward|in\s+(?:the\s+)?future|preferisco|preferirei|da\s+ora\s+in\s+poi|da\s+questo\s+momento|d['’]ora\s+in\s+poi|in\s+futuro|per\s+il\s+futuro)\b/i, kind: "preference" },
48
+ { re: /\b(?:remember(?:\s+that)?|keep\s+in\s+mind|note\s+that|don'?t\s+forget|for\s+future\s+reference|commit\s+(?:this\s+)?to\s+memory|ricorda(?:ti)?(?:\s+(?:che|di))?|tieni\s+(?:a\s+mente|presente)|nota\s+che|non\s+dimentica(?:re|rti)|memorizza|segnati|conserva\s+in\s+memoria|salva(?:lo)?\s+(?:in|nella)\s+memoria)\b/i, kind: "note" },
49
+ { re: /\b(?:the\s+user\s+is|i\s+am\s+(?:on|using)|i'm\s+(?:on|using)|we\s+use|my\s+\w+\s+is|io\s+uso|uso\s+\w+|usiamo)\b/i, kind: "preference" },
50
+ ];
51
+
52
+ const MAX_SNIPPET = 200;
53
+
54
+ const DIRECT_DECISION_OWNER = /^\s*(?:we\b|i\b|this\s+project\b|for\s+this\s+project\b|abbiamo\b|ho\b|questo\s+progetto\b|per\s+questo\s+progetto\b)/i;
55
+ const DURABLE_WORD = /\b(?:durable|permanent|stable|durevole|permanente|stabile)\b/i;
56
+ const DECISION_WORD = /\b(?:architectural\s+decision|decision|convention|invariant|decisione\s+architetturale|decisione|convenzione|invariante)\b/i;
57
+ const DECISION_ACTION = /\b(?:decided|chosen|chose|adopted|established|made|set|abbiamo\s+(?:deciso|scelto|adottato|stabilito|definito)|ho\s+(?:deciso|scelto|adottato|stabilito|definito))\b/i;
58
+ const REPORTED_DECISION = /^\s*(?:i\s+(?:saw|noticed|read|heard|observed|found|learned)\b|ho\s+(?:visto|notato|letto|sentito|osservato|scoperto|appreso)\b|mi\s+sono\s+accort[oa]\b)/i;
59
+
60
+ function isDirectDurableDecision(sentence: string): boolean {
61
+ if (REPORTED_DECISION.test(sentence) || !DIRECT_DECISION_OWNER.test(sentence) || !DURABLE_WORD.test(sentence) || !DECISION_WORD.test(sentence)) return false;
62
+ const action = DECISION_ACTION.exec(sentence);
63
+ if (action === null) return false;
64
+ const colon = sentence.indexOf(":");
65
+ // Reject negation anywhere in a premise that extraction would discard. Otherwise inspect
66
+ // only before the adoption verb: a negative fact remains eligible and keeps its wording.
67
+ const premiseEnd = colon >= 0 && sentence.slice(colon + 1).trim() ? colon : action.index;
68
+ return !/\b(?:never|not|non|mai)\b|n['’]t\b/i.test(sentence.slice(0, premiseEnd));
69
+ }
70
+
71
+ /** Split into sentences on ., !, ?, newline — coarse but enough to isolate the cued clause. */
72
+ function sentences(text: string): string[] {
73
+ // Foreign/quoted material is data, not the user's own persistence request. Parse Markdown fences
74
+ // linearly so an unclosed fence also consumes the rest; a regex that requires a closing ``` would
75
+ // turn malformed pasted code into durable memory. Four-space/tab-indented code is data too.
76
+ let fence: { char: "`" | "~"; width: number } | undefined;
77
+ const prose: string[] = [];
78
+ for (const line of text.split(/\r?\n/)) {
79
+ const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
80
+ if (fence) {
81
+ if (marker?.[0] === fence.char && marker.length >= fence.width) fence = undefined;
82
+ continue;
83
+ }
84
+ if (marker) {
85
+ fence = { char: marker[0] as "`" | "~", width: marker.length };
86
+ continue;
87
+ }
88
+ if (/^(?: {4,}|\t)/.test(line) || /^\s*>/.test(line)) continue;
89
+ prose.push(line);
90
+ }
91
+ return prose
92
+ .join("\n")
93
+ .split(/(?<=[.!?])\s+|\n+/)
94
+ .map((s) => s.trim())
95
+ .filter(Boolean);
96
+ }
97
+
98
+ const CUE_PREFIXES: readonly { re: RegExp; explicit: boolean }[] = [
99
+ { re: /^\s*(?:please\s+)?(?:remember(?:\s+that)?|keep\s+in\s+mind(?:\s+that)?|don'?t\s+forget(?:\s+that)?|for\s+future\s+reference|commit\s+(?:this\s+)?to\s+memory(?:\s+that)?)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
100
+ { re: /^\s*(?:i\s+(?:want|need)\s+you\s+to\s+remember(?:\s+that)?)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
101
+ { re: /^\s*(?:from\s+now\s+on|going\s+forward|in\s+the\s+future)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
102
+ { re: /^\s*(?:per\s+favore\s+)?(?:ricorda(?:ti)?(?:\s+(?:che|di))?|tieni\s+(?:a\s+mente|presente)(?:\s+che)?|non\s+dimentica(?:re|rti)(?:\s+che)?|memorizza(?:\s+che)?|segnati(?:\s+che)?|conserva\s+in\s+memoria(?:\s+che)?|salva(?:lo)?\s+(?:in|nella)\s+memoria(?:\s+che)?)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
103
+ { re: /^\s*(?:voglio\s+che\s+tu\s+ricordi(?:\s+che)?)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
104
+ { re: /^\s*(?:da\s+ora\s+in\s+poi|da\s+questo\s+momento|d['’]ora\s+in\s+poi|in\s+futuro|per\s+il\s+futuro)\s*[,;:\-]?\s*(.+)$/i, explicit: true },
105
+ { re: /^\s*(?:i(?:'d)?\s+prefer|prefer\s+that|preferisco|preferirei)\s*[,;:\-]?\s*(.+)$/i, explicit: false },
106
+ { re: /^\s*(?:note\s+that|nota\s+che)\s*[,;:\-]?\s*(.+)$/i, explicit: false },
107
+ ];
108
+
109
+ function candidateFor(sentence: string): { text: string; explicit: boolean } {
110
+ // A Markdown/list marker is presentation owned by the user, not part of the requested fact.
111
+ // Block quotes were already excluded by `sentences`, so accepting a bullet here does not turn
112
+ // quoted foreign material into an automatic write.
113
+ const direct = sentence.replace(/^\s*(?:(?:[-+*])\s+(?:\[[ xX]\]\s+)?|(?:\d+[.)])\s+)/, "");
114
+ if (isDirectDurableDecision(direct)) {
115
+ const colon = direct.indexOf(":");
116
+ const afterColon = colon >= 0 ? direct.slice(colon + 1).trim() : "";
117
+ const text = afterColon || direct;
118
+ return { text, explicit: /[\p{L}\p{N}]/u.test(text) };
119
+ }
120
+ // "Always remember" reinforces consent; stripping "never" would reverse a refusal.
121
+ const withoutAlways = direct.replace(/^\s*always\s+/i, "");
122
+ for (const prefix of CUE_PREFIXES) {
123
+ const match = prefix.re.exec(direct) ?? (withoutAlways !== direct ? prefix.re.exec(withoutAlways) : null);
124
+ const candidate = match?.[1]?.trim();
125
+ if (candidate) {
126
+ const text = candidate;
127
+ return { text, explicit: prefix.explicit && /[\p{L}\p{N}]/u.test(text) };
128
+ }
129
+ }
130
+ return { text: direct, explicit: false };
131
+ }
132
+
133
+ /** Every durable cue in direct user prose, capped so a hostile/accidental wall of cues cannot turn
134
+ * one input into an unbounded write burst. */
135
+ export function detectCaptureCues(userText: string): CaptureCue[] {
136
+ if (typeof userText !== "string" || !userText.trim()) return [];
137
+ const found: CaptureCue[] = [];
138
+ for (const sentence of sentences(userText)) {
139
+ for (const cue of CUES) {
140
+ if (!cue.re.test(sentence)) continue;
141
+ const snippet = sentence.length > MAX_SNIPPET ? `${sentence.slice(0, MAX_SNIPPET - 1)}…` : sentence;
142
+ const candidate = candidateFor(sentence);
143
+ if (found.some((prior) => prior.kind === cue.kind && prior.strong === candidate.explicit && prior.candidate === candidate.text)) break;
144
+ found.push({ snippet, kind: cue.kind, term: "session", strong: candidate.explicit, candidate: candidate.text });
145
+ break;
146
+ }
147
+ if (found.length >= 4) break;
148
+ }
149
+ return found;
150
+ }
151
+
152
+ /** The first durable cue in `userText`, or null. Returns the cued sentence + a suggested kind. */
153
+ export function detectCaptureCue(userText: string): CaptureCue | null {
154
+ return detectCaptureCues(userText)[0] ?? null;
155
+ }
@@ -1,74 +1,74 @@
1
- /**
2
- * Shared conservative planning estimate for injected context. It is deliberately not presented as
3
- * a provider tokenizer: unusual byte-pair splits can differ. UTF-8 bytes / 3 is simple, stable,
4
- * and errs high for ordinary English while treating non-ASCII content by its actual byte cost.
5
- */
6
-
7
- const encoder = new TextEncoder();
8
- export const DEFAULT_MEMORY_CONTEXT_TOKENS = 2_400;
9
-
10
- export function estimateTokens(text: string | readonly string[]): number {
11
- const blocks = typeof text === "string" ? [text] : text;
12
- return blocks.reduce((total, block, index) => total + Math.ceil(encoder.encode(block).byteLength / 3) + (index === 0 ? 0 : 1), 0);
13
- }
14
-
15
- export interface ContextBudgetCandidate<T> {
16
- value: T;
17
- /** High-priority context is considered before ordinary candidates but still obeys the hard cap. */
18
- pinned?: boolean;
19
- }
20
-
21
- export interface FitContextOptions<T> {
22
- maxTokens: number;
23
- /** Complete, already-rendered blocks that share the same total context budget. */
24
- fixedBlocks?: readonly string[];
25
- /** Render a complete fenced block and an omission disclosure for the selected whole items. */
26
- render(items: readonly T[], omitted: number): string;
27
- }
28
-
29
- export interface FitContextResult<T> {
30
- items: T[];
31
- omitted: number;
32
- text: string;
33
- estimatedTokens: number;
34
- overBudget: boolean;
35
- }
36
-
37
- /**
38
- * Select complete entries in priority order. Pinned entries are considered first, but still obey
39
- * the hard cap. The render callback owns XML/JSON/trust fences and receives the omission count, so
40
- * the final wrapper/footer is measured too. If fixed blocks alone exceed the cap, overBudget says so.
41
- */
42
- export function fitContextItems<T>(
43
- candidates: readonly ContextBudgetCandidate<T>[],
44
- options: FitContextOptions<T>,
45
- ): FitContextResult<T> {
46
- const maxTokens = Number.isNaN(options.maxTokens) ? 0 : Math.max(0, options.maxTokens);
47
- const selectedIndexes = new Set<number>();
48
- const valuesFor = (indexes: ReadonlySet<number>): T[] => candidates.flatMap((candidate, index) => indexes.has(index) ? [candidate.value] : []);
49
- const measure = (indexes: ReadonlySet<number>, omitted: number): { text: string; tokens: number } => {
50
- const text = options.render(valuesFor(indexes), omitted);
51
- return { text, tokens: estimateTokens([...(options.fixedBlocks ?? []), text]) };
52
- };
53
-
54
- const fitOrder = candidates.map((_, index) => index).sort((a, b) => Number(!candidates[a]?.pinned) - Number(!candidates[b]?.pinned) || a - b);
55
- for (const index of fitOrder) {
56
- if (selectedIndexes.has(index)) continue;
57
- const trial = new Set(selectedIndexes);
58
- trial.add(index);
59
- // Reserve room for the largest possible omission count: later candidates may also be omitted.
60
- const omitted = candidates.length - trial.size;
61
- if (measure(trial, omitted).tokens <= maxTokens) selectedIndexes.add(index);
62
- }
63
-
64
- const items = valuesFor(selectedIndexes);
65
- const omitted = candidates.length - selectedIndexes.size;
66
- const final = measure(selectedIndexes, omitted);
67
- return {
68
- items,
69
- omitted,
70
- text: final.text,
71
- estimatedTokens: final.tokens,
72
- overBudget: final.tokens > maxTokens,
73
- };
74
- }
1
+ /**
2
+ * Shared conservative planning estimate for injected context. It is deliberately not presented as
3
+ * a provider tokenizer: unusual byte-pair splits can differ. UTF-8 bytes / 3 is simple, stable,
4
+ * and errs high for ordinary English while treating non-ASCII content by its actual byte cost.
5
+ */
6
+
7
+ const encoder = new TextEncoder();
8
+ export const DEFAULT_MEMORY_CONTEXT_TOKENS = 2_400;
9
+
10
+ export function estimateTokens(text: string | readonly string[]): number {
11
+ const blocks = typeof text === "string" ? [text] : text;
12
+ return blocks.reduce((total, block, index) => total + Math.ceil(encoder.encode(block).byteLength / 3) + (index === 0 ? 0 : 1), 0);
13
+ }
14
+
15
+ export interface ContextBudgetCandidate<T> {
16
+ value: T;
17
+ /** High-priority context is considered before ordinary candidates but still obeys the hard cap. */
18
+ pinned?: boolean;
19
+ }
20
+
21
+ export interface FitContextOptions<T> {
22
+ maxTokens: number;
23
+ /** Complete, already-rendered blocks that share the same total context budget. */
24
+ fixedBlocks?: readonly string[];
25
+ /** Render a complete fenced block and an omission disclosure for the selected whole items. */
26
+ render(items: readonly T[], omitted: number): string;
27
+ }
28
+
29
+ export interface FitContextResult<T> {
30
+ items: T[];
31
+ omitted: number;
32
+ text: string;
33
+ estimatedTokens: number;
34
+ overBudget: boolean;
35
+ }
36
+
37
+ /**
38
+ * Select complete entries in priority order. Pinned entries are considered first, but still obey
39
+ * the hard cap. The render callback owns XML/JSON/trust fences and receives the omission count, so
40
+ * the final wrapper/footer is measured too. If fixed blocks alone exceed the cap, overBudget says so.
41
+ */
42
+ export function fitContextItems<T>(
43
+ candidates: readonly ContextBudgetCandidate<T>[],
44
+ options: FitContextOptions<T>,
45
+ ): FitContextResult<T> {
46
+ const maxTokens = Number.isNaN(options.maxTokens) ? 0 : Math.max(0, options.maxTokens);
47
+ const selectedIndexes = new Set<number>();
48
+ const valuesFor = (indexes: ReadonlySet<number>): T[] => candidates.flatMap((candidate, index) => indexes.has(index) ? [candidate.value] : []);
49
+ const measure = (indexes: ReadonlySet<number>, omitted: number): { text: string; tokens: number } => {
50
+ const text = options.render(valuesFor(indexes), omitted);
51
+ return { text, tokens: estimateTokens([...(options.fixedBlocks ?? []), text]) };
52
+ };
53
+
54
+ const fitOrder = candidates.map((_, index) => index).sort((a, b) => Number(!candidates[a]?.pinned) - Number(!candidates[b]?.pinned) || a - b);
55
+ for (const index of fitOrder) {
56
+ if (selectedIndexes.has(index)) continue;
57
+ const trial = new Set(selectedIndexes);
58
+ trial.add(index);
59
+ // Reserve room for the largest possible omission count: later candidates may also be omitted.
60
+ const omitted = candidates.length - trial.size;
61
+ if (measure(trial, omitted).tokens <= maxTokens) selectedIndexes.add(index);
62
+ }
63
+
64
+ const items = valuesFor(selectedIndexes);
65
+ const omitted = candidates.length - selectedIndexes.size;
66
+ const final = measure(selectedIndexes, omitted);
67
+ return {
68
+ items,
69
+ omitted,
70
+ text: final.text,
71
+ estimatedTokens: final.tokens,
72
+ overBudget: final.tokens > maxTokens,
73
+ };
74
+ }