pi-braid 0.42.0 → 0.43.0

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 (102) hide show
  1. package/CHANGELOG.md +1077 -0
  2. package/README.md +61 -228
  3. package/TOOLS.md +12 -14
  4. package/build-info.json +4 -4
  5. package/dist/extensions/cognitive/metacognition/handlers/think.js +9 -0
  6. package/dist/extensions/core/polyfill/index.d.ts +3 -4
  7. package/dist/extensions/core/polyfill/index.js +34 -131
  8. package/dist/extensions/core/skills-tool/index.js +47 -26
  9. package/dist/extensions/enforcement/handlers/register-agent-end-api-error.js +13 -0
  10. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +8 -3
  11. package/dist/extensions/enforcement/session-health.d.ts +52 -4
  12. package/dist/extensions/enforcement/session-health.js +75 -5
  13. package/dist/extensions/enforcement/whisper.js +15 -1
  14. package/dist/extensions/heartbeat/heartbeat-scheduler/index.d.ts +17 -0
  15. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +40 -78
  16. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +2 -1
  17. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +26 -28
  18. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.d.ts +62 -31
  19. package/dist/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.js +130 -55
  20. package/dist/extensions/manifest.js +6 -0
  21. package/dist/extensions/memory/context-lifecycle/index.js +11 -10
  22. package/dist/extensions/memory/context-manager/analysis.d.ts +2 -0
  23. package/dist/extensions/memory/context-manager/analysis.js +6 -2
  24. package/dist/extensions/memory/context-manager/handlers/compaction-retry.js +3 -3
  25. package/dist/extensions/memory/context-manager/handlers/events.js +13 -1
  26. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +10 -14
  27. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +62 -88
  28. package/dist/extensions/self/path-miss/detect.d.ts +30 -0
  29. package/dist/extensions/self/path-miss/detect.js +67 -0
  30. package/dist/extensions/self/path-miss/index.d.ts +33 -0
  31. package/dist/extensions/self/path-miss/index.js +118 -0
  32. package/dist/extensions/self/watchdog/engine.d.ts +8 -1
  33. package/dist/extensions/self/watchdog/engine.js +25 -2
  34. package/dist/extensions/self/watchdog/index.js +14 -1
  35. package/dist/lib/ai/llm-call.js +23 -0
  36. package/dist/lib/ai/model-resolver.d.ts +11 -10
  37. package/dist/lib/ai/model-resolver.js +16 -19
  38. package/dist/lib/ai/presend-budget.d.ts +68 -0
  39. package/dist/lib/ai/presend-budget.js +83 -0
  40. package/dist/lib/config/braid-settings.d.ts +38 -0
  41. package/dist/lib/config/braid-settings.js +84 -0
  42. package/dist/lib/config/per-tool-settings.d.ts +4 -4
  43. package/dist/lib/config/per-tool-settings.js +4 -4
  44. package/dist/lib/core/event-names.d.ts +1 -0
  45. package/dist/lib/core/event-names.js +1 -0
  46. package/dist/lib/detection/context-tiers.d.ts +18 -5
  47. package/dist/lib/detection/context-tiers.js +51 -33
  48. package/dist/lib/detection/context-usage.d.ts +62 -1
  49. package/dist/lib/detection/context-usage.js +158 -1
  50. package/dist/lib/errors/llm-error.d.ts +14 -0
  51. package/dist/lib/errors/llm-error.js +44 -1
  52. package/dist/lib/state/global-state.d.ts +4 -8
  53. package/dist/lib/state/global-state.js +11 -28
  54. package/dist/lib/telemetry/context-heartbeat.d.ts +9 -0
  55. package/dist/lib/telemetry/context-heartbeat.js +18 -8
  56. package/dist/lib/utils/argument-report.d.ts +41 -0
  57. package/dist/lib/utils/argument-report.js +95 -0
  58. package/dist/lib/utils/wake-gate.d.ts +6 -0
  59. package/dist/lib/utils/wake-gate.js +52 -4
  60. package/docs/SETUP.md +7 -6
  61. package/package.json +11 -13
  62. package/src/extensions/cognitive/metacognition/handlers/think.ts +9 -0
  63. package/src/extensions/core/polyfill/index.ts +29 -157
  64. package/src/extensions/core/skills-tool/index.ts +60 -37
  65. package/src/extensions/enforcement/AGENTS.md +38 -1
  66. package/src/extensions/enforcement/handlers/register-agent-end-api-error.ts +13 -0
  67. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +8 -2
  68. package/src/extensions/enforcement/session-health.ts +94 -5
  69. package/src/extensions/enforcement/whisper.ts +15 -1
  70. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +53 -80
  71. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +34 -43
  72. package/src/extensions/heartbeat/heartbeat-scheduler/whisper-batcher.ts +154 -52
  73. package/src/extensions/manifest.ts +6 -0
  74. package/src/extensions/memory/AGENTS.md +37 -38
  75. package/src/extensions/memory/context-lifecycle/index.ts +11 -10
  76. package/src/extensions/memory/context-manager/analysis.ts +8 -1
  77. package/src/extensions/memory/context-manager/handlers/compaction-retry.ts +3 -3
  78. package/src/extensions/memory/context-manager/handlers/events.ts +18 -1
  79. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +81 -115
  80. package/src/extensions/scheduling/timer/AGENTS.md +14 -4
  81. package/src/extensions/self/AGENTS.md +2 -1
  82. package/src/extensions/self/path-miss/AGENTS.md +39 -0
  83. package/src/extensions/self/path-miss/detect.ts +78 -0
  84. package/src/extensions/self/path-miss/index.ts +135 -0
  85. package/src/extensions/self/watchdog/AGENTS.md +36 -18
  86. package/src/extensions/self/watchdog/engine.ts +30 -2
  87. package/src/extensions/self/watchdog/index.ts +13 -1
  88. package/src/lib/ai/AGENTS.md +2 -0
  89. package/src/lib/ai/llm-call.ts +30 -0
  90. package/src/lib/ai/model-resolver.ts +16 -19
  91. package/src/lib/ai/presend-budget.ts +117 -0
  92. package/src/lib/config/braid-settings.ts +125 -0
  93. package/src/lib/config/per-tool-settings.ts +4 -4
  94. package/src/lib/core/event-names.ts +1 -0
  95. package/src/lib/detection/context-tiers.ts +52 -41
  96. package/src/lib/detection/context-usage.ts +211 -2
  97. package/src/lib/errors/llm-error.ts +55 -1
  98. package/src/lib/state/global-state.ts +11 -29
  99. package/src/lib/telemetry/context-heartbeat.ts +27 -7
  100. package/src/lib/utils/AGENTS.md +1 -0
  101. package/src/lib/utils/argument-report.ts +105 -0
  102. package/src/lib/utils/wake-gate.ts +59 -4
@@ -19,6 +19,7 @@ Misc utilities that don't fit a more specific subdir.
19
19
  | `error-guard.ts` | Wraps handler errors with logging and recovery. |
20
20
  | `async-fs.ts` | Async filesystem primitives (`asyncExists`). Replaces duplicate `existsSync` checks. |
21
21
  | `format-tool-result.ts` | Structured Output Catalyst - wraps tool output in consistent TOOL/STATUS/RESULT header format. MDA research (2601.21996) backing. |
22
+ | `argument-report.ts` | Builds the refusal text a tool-argument rejection carries: the accepted values and a required field's stated purpose, both read from the tool's own schema at the moment the message is built (no second copy to drift). Used from a tool's `prepareArguments`, which pi calls before its own validation. |
22
23
 
23
24
  ## Local Contracts
24
25
 
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Tool-argument refusal text.
3
+ *
4
+ * pi validates a tool call against its schema and reports the failure in
5
+ * schema terms: an out-of-list value says "must be equal to one of the allowed
6
+ * values", a missing required field says "must have required properties
7
+ * decision". Neither names the values, so the model that guessed one learns
8
+ * nothing it can act on and guesses again.
9
+ *
10
+ * The accepted values, and the sentence explaining a required field, are
11
+ * already in the schema. This module reads them from there at the moment the
12
+ * refusal is built: no list is written twice, so no copy can drift from the
13
+ * one the validator enforces.
14
+ *
15
+ * Seat: a tool's `prepareArguments`. pi calls it first, inside the same
16
+ * guarded block as its own schema validation, so a throw here is what the
17
+ * model reads — and the schema stays exactly as strict as it was. The checks
18
+ * below are equivalences, not relaxations: a call refused here is one pi would
19
+ * have refused too, only with a message the model can use.
20
+ *
21
+ * Scope is the top level of the argument object. A nested list is left to pi
22
+ * rather than described from a guess about its parent.
23
+ */
24
+
25
+ /** A schema node, as far as this module needs to read it. */
26
+ interface SchemaNode {
27
+ const?: unknown;
28
+ enum?: unknown;
29
+ anyOf?: unknown;
30
+ oneOf?: unknown;
31
+ description?: unknown;
32
+ properties?: unknown;
33
+ required?: unknown;
34
+ [keyword: string]: unknown;
35
+ }
36
+
37
+ function nodeOf(value: unknown): SchemaNode | undefined {
38
+ return value && typeof value === "object" ? (value as SchemaNode) : undefined;
39
+ }
40
+
41
+ /**
42
+ * The values a schema node accepts, read from the node.
43
+ *
44
+ * A single-valued node (`const`, which is what `Type.Literal` builds) yields
45
+ * one value; an `enum` yields its list; a union of those yields all of them.
46
+ * A node that constrains nothing yields no values, and the caller then leaves
47
+ * the message to pi.
48
+ */
49
+ export function acceptedValues(node: unknown): string[] {
50
+ const schema = nodeOf(node);
51
+ if (!schema) return [];
52
+ if (typeof schema.const === "string") return [schema.const];
53
+ if (Array.isArray(schema.enum) && schema.enum.every((v) => typeof v === "string")) {
54
+ return [...new Set(schema.enum as string[])];
55
+ }
56
+ const branches = Array.isArray(schema.anyOf)
57
+ ? schema.anyOf
58
+ : Array.isArray(schema.oneOf)
59
+ ? schema.oneOf
60
+ : undefined;
61
+ if (!branches) return [];
62
+ return [...new Set(branches.flatMap((branch) => acceptedValues(branch)))];
63
+ }
64
+
65
+ function quoted(value: string): string {
66
+ return JSON.stringify(value);
67
+ }
68
+
69
+ /**
70
+ * Throw the refusal a model can act on, when this module can say more than the
71
+ * validator does. Returns silently otherwise, leaving pi's own message intact.
72
+ *
73
+ * `schema` is the same object the tool declares as its `parameters`, and
74
+ * `args` the arguments the call carried.
75
+ */
76
+ export function checkArgumentValues(toolName: string, schema: unknown, args: unknown): void {
77
+ const root = nodeOf(schema);
78
+ const properties = nodeOf(root?.properties);
79
+ const input = nodeOf(args);
80
+ if (!root || !properties || !input) return;
81
+
82
+ // A required field with a stated purpose: say both, once.
83
+ if (Array.isArray(root.required)) {
84
+ for (const key of root.required) {
85
+ if (typeof key !== "string") continue;
86
+ const value = (input as Record<string, unknown>)[key];
87
+ if (value !== undefined && value !== null) continue;
88
+ const purpose = nodeOf(properties[key])?.description;
89
+ if (typeof purpose !== "string" || purpose.length === 0) continue;
90
+ throw new Error(`${toolName}: ${key} is required (${purpose})`);
91
+ }
92
+ }
93
+
94
+ // A value outside its declared list: name the list.
95
+ for (const [key, raw] of Object.entries(input as Record<string, unknown>)) {
96
+ if (typeof raw !== "string") continue;
97
+ const values = acceptedValues(properties[key]);
98
+ if (values.length === 0 || values.includes(raw)) continue;
99
+ throw new Error(
100
+ `${toolName}: ${key} ${quoted(raw)} is not accepted. Accepted: ${values
101
+ .map(quoted)
102
+ .join(", ")}`,
103
+ );
104
+ }
105
+ }
@@ -155,6 +155,30 @@ let _failSafeHandle: ReturnType<typeof setTimeout> | null = null;
155
155
  // Test hook: override the fail-safe bound (null restores the default).
156
156
  let _failSafeMsOverride: number | null = null;
157
157
 
158
+ /**
159
+ * Why the last turn could not be sent at all, when the reason is the SHAPE of
160
+ * the request rather than the state of the provider. A context-length refusal
161
+ * is permanent for a given context: every later turn carrying the same payload
162
+ * is refused the same way, so an ungated wake that starts one is not a retry,
163
+ * it is the same failure under a fresh request id.
164
+ */
165
+ let _requestShapeFailure: string | null = null;
166
+
167
+ /** Record that the last turn failed on request shape (a context-length refusal). */
168
+ export function noteRequestShapeFailure(detail: string): void {
169
+ _requestShapeFailure = detail;
170
+ }
171
+
172
+ /** The recorded request-shape failure, or null. */
173
+ export function requestShapeFailure(): string | null {
174
+ return _requestShapeFailure;
175
+ }
176
+
177
+ /** Clear the record (a request that fits went through, or a new session). */
178
+ export function clearRequestShapeFailure(): void {
179
+ _requestShapeFailure = null;
180
+ }
181
+
158
182
  function failSafeMs(): number {
159
183
  return _failSafeMsOverride ?? RUN_REGION_MAX_MS;
160
184
  }
@@ -170,18 +194,47 @@ function clearFailSafe(): void {
170
194
  function armRunRegion(): void {
171
195
  _runRegionActive = true;
172
196
  clearFailSafe();
197
+ scheduleFailSafe();
198
+ // Do not keep the process alive for a stuck gate.
199
+ unrefFailSafe();
200
+ }
201
+
202
+ /** Let the process exit while a fail-safe window is pending. */
203
+ function unrefFailSafe(): void {
204
+ const handle = _failSafeHandle as { unref?: () => void } | null;
205
+ if (typeof handle?.unref === "function") handle.unref();
206
+ }
207
+
208
+ /**
209
+ * One fail-safe window. Normally the gate opens here: a gate stuck closed by a
210
+ * pre-flight abort rewrites every wake into a queued steer that never starts a
211
+ * turn, which is its own failure.
212
+ *
213
+ * The exception is a recorded request-shape failure. There, opening the gate
214
+ * buys no safety - it starts the same doomed request again, and again. So the
215
+ * gate stays closed and the window re-arms: wakes keep arriving as steers into
216
+ * the session (the shape that reads them when a run does start) without
217
+ * starting one.
218
+ */
219
+ function scheduleFailSafe(): void {
173
220
  _failSafeHandle = setTimeout(() => {
174
221
  _failSafeHandle = null;
222
+ if (_requestShapeFailure) {
223
+ log.warn(
224
+ `[wake-gate] fail-safe: keeping triggerTurn wakes gated - the last turn was refused on ` +
225
+ `request shape (context length), so the request it would start cannot succeed. ` +
226
+ `Remedy: compact the session. Detail: ${_requestShapeFailure}`,
227
+ );
228
+ scheduleFailSafe();
229
+ unrefFailSafe();
230
+ return;
231
+ }
175
232
  _runRegionActive = false;
176
233
  log.warn(
177
234
  `[wake-gate] fail-safe: run region auto-cleared after ${failSafeMs()}ms without a release event ` +
178
235
  `(pre-flight abort?) — triggerTurn wakes ungated again`,
179
236
  );
180
237
  }, failSafeMs());
181
- // Do not keep the process alive for a stuck gate.
182
- if (typeof (_failSafeHandle as { unref?: () => void } | null)?.unref === "function") {
183
- (_failSafeHandle as { unref: () => void }).unref();
184
- }
185
238
  }
186
239
 
187
240
  /** Release the gate and cancel the fail-safe timer. */
@@ -200,6 +253,7 @@ export function resetWakeGateForTests(): void {
200
253
  releaseRunRegion();
201
254
  _lastAgentCtx = null;
202
255
  _failSafeMsOverride = null;
256
+ _requestShapeFailure = null;
203
257
  }
204
258
 
205
259
  /** Test hook: shorten/extend the fail-safe bound (null restores the default). */
@@ -274,6 +328,7 @@ export function registerWakeGate(pi: {
274
328
  );
275
329
  (pi.on as (event: string, handler: (...args: any[]) => any) => void)(SESSION_SHUTDOWN, () => {
276
330
  releaseRunRegion();
331
+ _requestShapeFailure = null; // a new session starts without a shape verdict
277
332
  _lastAgentCtx = null; // no live session after shutdown: fail open until the next capture
278
333
  });
279
334
  }