@gajae-code/agent-core 0.1.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 (55) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/README.md +473 -0
  3. package/dist/types/agent-loop.d.ts +55 -0
  4. package/dist/types/agent.d.ts +334 -0
  5. package/dist/types/append-only-context.d.ts +113 -0
  6. package/dist/types/compaction/branch-summarization.d.ts +94 -0
  7. package/dist/types/compaction/compaction.d.ts +166 -0
  8. package/dist/types/compaction/entries.d.ts +103 -0
  9. package/dist/types/compaction/errors.d.ts +26 -0
  10. package/dist/types/compaction/index.d.ts +11 -0
  11. package/dist/types/compaction/messages.d.ts +61 -0
  12. package/dist/types/compaction/openai.d.ts +58 -0
  13. package/dist/types/compaction/pruning.d.ts +18 -0
  14. package/dist/types/compaction/utils.d.ts +32 -0
  15. package/dist/types/compaction.d.ts +1 -0
  16. package/dist/types/harmony-leak.d.ts +99 -0
  17. package/dist/types/index.d.ts +10 -0
  18. package/dist/types/proxy.d.ts +84 -0
  19. package/dist/types/run-collector.d.ts +196 -0
  20. package/dist/types/telemetry.d.ts +588 -0
  21. package/dist/types/thinking.d.ts +17 -0
  22. package/dist/types/types.d.ts +407 -0
  23. package/package.json +75 -0
  24. package/src/agent-loop.ts +1279 -0
  25. package/src/agent.ts +1399 -0
  26. package/src/append-only-context.ts +297 -0
  27. package/src/compaction/branch-summarization.ts +339 -0
  28. package/src/compaction/compaction.ts +1065 -0
  29. package/src/compaction/entries.ts +133 -0
  30. package/src/compaction/errors.ts +31 -0
  31. package/src/compaction/index.ts +12 -0
  32. package/src/compaction/messages.ts +212 -0
  33. package/src/compaction/openai.ts +552 -0
  34. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  35. package/src/compaction/prompts/branch-summary-context.md +5 -0
  36. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  37. package/src/compaction/prompts/branch-summary.md +30 -0
  38. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  39. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  40. package/src/compaction/prompts/compaction-summary.md +38 -0
  41. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  42. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  43. package/src/compaction/prompts/file-operations.md +10 -0
  44. package/src/compaction/prompts/handoff-document.md +49 -0
  45. package/src/compaction/prompts/summarization-system.md +3 -0
  46. package/src/compaction/pruning.ts +92 -0
  47. package/src/compaction/utils.ts +185 -0
  48. package/src/compaction.ts +1 -0
  49. package/src/harmony-leak.ts +427 -0
  50. package/src/index.ts +19 -0
  51. package/src/proxy.ts +326 -0
  52. package/src/run-collector.ts +631 -0
  53. package/src/telemetry.ts +2018 -0
  54. package/src/thinking.ts +19 -0
  55. package/src/types.ts +467 -0
@@ -0,0 +1,427 @@
1
+ /**
2
+ * GPT-5 Harmony-header leakage detection and recovery.
3
+ *
4
+ * Background and policy: see `docs/ERRATA-GPT5-HARMONY.md`. This module
5
+ * implements §3 of that document: detection by signal fusion, plus a
6
+ * truncate-and-resume primitive for the `edit` tool when its input is in
7
+ * hashline DSL form. Other tools and surfaces fall through to
8
+ * abort-and-retry handled by the agent loop.
9
+ */
10
+ import type { AssistantMessage, Model, ToolCall } from "@gajae-code/ai";
11
+
12
+ // Single source of truth for the marker pattern. `M` in the errata.
13
+ // Use a fresh non-global instance for `.test()` to avoid lastIndex pitfalls.
14
+ const MARKER_RE = /\bto=functions\.[A-Za-z_]\w*/g;
15
+ const HARMONY_RE = /<\|(start|end|channel|message|call|return)\|>/g;
16
+
17
+ // Channel-word adjacency (`C`): channel/role name appearing immediately before the marker.
18
+ const CHANNEL_WORD_RE = /\b(?:analysis|commentary|assistant|user|system|developer|tool)\s+to=functions\./;
19
+
20
+ // Glitch-token adjacency (`G`). The Japgolly literal is escaped so this regex
21
+ // source itself does not trip detection if the file is scanned (e.g. when
22
+ // editing this module via the same agent that detects).
23
+ const GLITCH_RE = /\b(?:changedFiles|RTLU|Jsii(?:_commentary)?|\x4aapgolly)\b/;
24
+
25
+ // Body-channel cascade (`B`): marker followed by ` code` then another marker
26
+ // within 200 chars. Single regex; no manual slicing needed.
27
+ const BODY_CASCADE_RE = /to=functions\.\w+\s+code\b[\s\S]{0,200}?to=functions\./;
28
+
29
+ // Fake-result framing (`R`): marker followed within 80 chars by Cell N: framing.
30
+ const FAKE_RESULT_RE = /to=functions\.\w+[\s\S]{0,80}?code_output\s*\nCell\s+\d+:/;
31
+
32
+ const FENCE_RE = /^\s*(?:```+|~~~+)/;
33
+
34
+ // Non-Latin scripts seen in the corpus: CJK + ext, Cyrillic, Thai, Georgian,
35
+ // Armenian, Kannada, Telugu, Devanagari, Arabic, Malayalam.
36
+ const SCRIPT_CLASS =
37
+ "\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u0400-\u04FF\u0E00-\u0E7F\u10A0-\u10FF\u0530-\u058F\u0C80-\u0CFF\u0C00-\u0C7F\u0900-\u097F\u0600-\u06FF\u0D00-\u0D7F";
38
+ const SCRIPT_RUN_RE = new RegExp(`[${SCRIPT_CLASS}]{2,}`, "u");
39
+
40
+ // Recovery registry. Each entry's parser must recognize the configured
41
+ // sentinel (per-tool, see eval/parse.ts and hashline/parser.ts) and surface
42
+ // a warning to the model so it knows to re-issue any remaining work.
43
+ // `accepts` gates on input shape: tools whose contaminated input doesn't
44
+ // match the parser's expected DSL fall through to abort-and-retry.
45
+ //
46
+ // • `edit`: hashline DSL input begins with `@<path>`. Apply_patch envelopes
47
+ // (`*** Begin Patch …`) and JSON-schema variants are not recoverable —
48
+ // their parsers don't recognize `*** Abort`.
49
+ // • `eval`: any string is a parseable cell sequence (the parser is lenient
50
+ // and falls back to implicit-cell mode on bare strings).
51
+ interface RecoveryConfig {
52
+ sentinel: string;
53
+ accepts: (input: string) => boolean;
54
+ }
55
+ const RECOVERY_REGISTRY: Record<string, RecoveryConfig> = {
56
+ edit: {
57
+ sentinel: "\n*** Abort\n",
58
+ accepts: input => input.replace(/^\s+/, "").startsWith("@"),
59
+ },
60
+ eval: {
61
+ sentinel: "\n*** Abort\n",
62
+ accepts: () => true,
63
+ },
64
+ };
65
+
66
+ const SIGNAL_ORDER = ["M", "C", "G", "S", "B", "R", "T"] as const;
67
+
68
+ export type HarmonySignalClass = "H" | (typeof SIGNAL_ORDER)[number];
69
+
70
+ export type HarmonySurface = "assistant_text" | "assistant_thinking" | "tool_arg";
71
+
72
+ export interface HarmonySignal {
73
+ classes: HarmonySignalClass[];
74
+ start: number;
75
+ end: number;
76
+ text: string;
77
+ }
78
+
79
+ export interface HarmonyDetection {
80
+ surface: HarmonySurface;
81
+ contentIndex?: number;
82
+ toolName?: string;
83
+ toolCallId?: string;
84
+ signals: HarmonySignal[];
85
+ }
86
+
87
+ export interface HarmonyAuditEvent {
88
+ action: "truncate_resume" | "abort_retry" | "escalated";
89
+ surface: HarmonySurface;
90
+ signal: string;
91
+ retryN: number;
92
+ model: string;
93
+ provider: string;
94
+ toolName?: string;
95
+ removedLen: number;
96
+ removedSha8: string;
97
+ removedPreview: string;
98
+ removedBlob?: string;
99
+ }
100
+
101
+ export interface HarmonyRecoveredToolCall {
102
+ message: AssistantMessage;
103
+ removed: string;
104
+ }
105
+
106
+ /**
107
+ * Whether to run leak detection on responses from this model. We default-on
108
+ * for every OpenAI code provider model rather than enumerating ids, so a future
109
+ * gpt-5.6 (or whatever) doesn't silently bypass the mitigation. Detection
110
+ * itself is cheap; the cost of missing a leak on a new model is not.
111
+ */
112
+ export function isHarmonyLeakMitigationTarget(model: Model): boolean {
113
+ return model.provider === "openai-codex";
114
+ }
115
+
116
+ export function signalListLabel(signals: readonly HarmonySignal[]): string {
117
+ const seen: string[] = [];
118
+ for (const signal of signals) {
119
+ const label = signal.classes.join("+");
120
+ if (!seen.includes(label)) seen.push(label);
121
+ }
122
+ return seen.join(",") || "none";
123
+ }
124
+
125
+ /**
126
+ * Detect harmony-protocol leakage in `text`. Returns undefined if clean.
127
+ *
128
+ * Trip rule: `H` alone, or `M` paired with at least one co-signal
129
+ * (`C`/`G`/`S`/`B`/`R`/`T`). Bare `M` does not trip — this document, its
130
+ * tests, and bug reports legitimately carry the marker.
131
+ *
132
+ * `parsedEnd`, when supplied, marks the byte at which a structurally valid
133
+ * tool-argument parse ends; markers strictly after it set the `T` co-signal.
134
+ * `contentIndex`/`toolName`/`toolCallId` flow through to the returned
135
+ * detection for downstream auditing.
136
+ */
137
+ export function detectHarmonyLeak(
138
+ text: string,
139
+ surface: HarmonySurface,
140
+ options: {
141
+ parsedEnd?: number;
142
+ contentIndex?: number;
143
+ toolName?: string;
144
+ toolCallId?: string;
145
+ } = {},
146
+ ): HarmonyDetection | undefined {
147
+ const fences = computeFenceRanges(text);
148
+ const signals: HarmonySignal[] = [];
149
+
150
+ for (const match of text.matchAll(HARMONY_RE)) {
151
+ const start = match.index ?? 0;
152
+ if (isInsideFence(fences, start)) continue;
153
+ signals.push(makeSignal(["H"], start, start + match[0].length, match[0]));
154
+ }
155
+
156
+ for (const match of text.matchAll(MARKER_RE)) {
157
+ const start = match.index ?? 0;
158
+ if (isInsideFence(fences, start)) continue;
159
+ const end = start + match[0].length;
160
+ const classes: HarmonySignalClass[] = ["M"];
161
+
162
+ const adjacent = text.slice(Math.max(0, start - 64), Math.min(text.length, end + 16));
163
+ const near = text.slice(Math.max(0, start - 16), Math.min(text.length, end + 16));
164
+ const forward = text.slice(start, Math.min(text.length, start + 240));
165
+
166
+ if (CHANNEL_WORD_RE.test(adjacent)) classes.push("C");
167
+ if (GLITCH_RE.test(near)) classes.push("G");
168
+ if (hasScriptMismatchNear(text, start, end)) classes.push("S");
169
+ if (BODY_CASCADE_RE.test(forward)) classes.push("B");
170
+ if (FAKE_RESULT_RE.test(forward)) classes.push("R");
171
+ if (options.parsedEnd !== undefined && start >= options.parsedEnd) classes.push("T");
172
+
173
+ // `M` alone never trips: legitimate documentation/tests carry it.
174
+ if (classes.length > 1) {
175
+ signals.push(makeSignal(classes, start, end, match[0]));
176
+ }
177
+ }
178
+
179
+ if (signals.length === 0) return undefined;
180
+ signals.sort((a, b) => a.start - b.start || a.end - b.end);
181
+ return {
182
+ surface,
183
+ contentIndex: options.contentIndex,
184
+ toolName: options.toolName,
185
+ toolCallId: options.toolCallId,
186
+ signals,
187
+ };
188
+ }
189
+
190
+ /** Scan an assistant message's content blocks; return the first detection. */
191
+ export function detectHarmonyLeakInAssistantMessage(message: AssistantMessage): HarmonyDetection | undefined {
192
+ for (let i = 0; i < message.content.length; i++) {
193
+ const block = message.content[i];
194
+ if (block.type === "text") {
195
+ const d = detectHarmonyLeak(block.text, "assistant_text", { contentIndex: i });
196
+ if (d) return d;
197
+ } else if (block.type === "thinking") {
198
+ const d = detectHarmonyLeak(block.thinking, "assistant_thinking", { contentIndex: i });
199
+ if (d) return d;
200
+ } else if (block.type === "toolCall") {
201
+ const argText = getToolArgumentText(block);
202
+ if (argText !== undefined) {
203
+ const d = detectHarmonyLeak(argText, "tool_arg", {
204
+ contentIndex: i,
205
+ toolName: block.name,
206
+ toolCallId: block.id,
207
+ });
208
+ if (d) return d;
209
+ }
210
+ }
211
+ }
212
+ return undefined;
213
+ }
214
+
215
+ /**
216
+ * Truncate a contaminated tool call at the start of the contaminated line and
217
+ * append the tool's recovery sentinel. Returns a recovered AssistantMessage
218
+ * (containing only the cleaned tool call), a synthetic continuation user
219
+ * message asking the model to re-issue the rest, and the removed substring
220
+ * for auditing. Returns undefined when the tool is not recovery-eligible or
221
+ * the truncation would leave nothing meaningful to dispatch.
222
+ *
223
+ * `providerPayload` is dropped from the recovered message: for OpenAI code backend the
224
+ * encrypted reasoning blob is opaque/signed and we cannot validate that it is
225
+ * uncontaminated. The model re-reasons on the next turn.
226
+ */
227
+ export function recoverHarmonyToolCall(
228
+ message: AssistantMessage,
229
+ detection: HarmonyDetection,
230
+ ): HarmonyRecoveredToolCall | undefined {
231
+ if (detection.surface !== "tool_arg" || detection.contentIndex === undefined) return undefined;
232
+ const block = message.content[detection.contentIndex];
233
+ if (!block || block.type !== "toolCall") return undefined;
234
+
235
+ const config = RECOVERY_REGISTRY[block.name];
236
+ if (!config) return undefined;
237
+
238
+ const input = block.arguments?.input;
239
+ if (typeof input !== "string") return undefined;
240
+ if (!config.accepts(input)) return undefined;
241
+
242
+ const offset = detection.signals[0]?.start;
243
+ if (offset === undefined) return undefined;
244
+
245
+ const truncated = truncateAtLineAndAppendSentinel(input, offset, config.sentinel);
246
+ if (truncated === undefined) return undefined;
247
+
248
+ const cleanToolCall: ToolCall = {
249
+ ...block,
250
+ arguments: { ...block.arguments, input: truncated.clean },
251
+ };
252
+ const cleanMessage: AssistantMessage = {
253
+ ...message,
254
+ content: [cleanToolCall],
255
+ // Drop encrypted reasoning blob: opaque, possibly carries the leak forward.
256
+ providerPayload: undefined,
257
+ stopReason: "toolUse",
258
+ errorMessage: undefined,
259
+ };
260
+ return { message: cleanMessage, removed: truncated.removed };
261
+ }
262
+
263
+ /**
264
+ * Return the contaminated substring from `message` for audit purposes when
265
+ * recovery is not applicable (abort path). Walks from the first detected
266
+ * signal to end-of-content within the relevant block. Returns "" if the
267
+ * detection cannot be resolved against the message.
268
+ */
269
+ export function extractHarmonyRemoved(message: AssistantMessage, detection: HarmonyDetection): string {
270
+ if (detection.contentIndex === undefined) return "";
271
+ const block = message.content[detection.contentIndex];
272
+ if (!block) return "";
273
+ const start = detection.signals[0]?.start ?? 0;
274
+ if (block.type === "text") return block.text.slice(start);
275
+ if (block.type === "thinking") return block.thinking.slice(start);
276
+ if (block.type === "toolCall") {
277
+ const text = getToolArgumentText(block);
278
+ return text ? text.slice(start) : "";
279
+ }
280
+ return "";
281
+ }
282
+
283
+ export function createHarmonyAuditEvent(params: {
284
+ action: HarmonyAuditEvent["action"];
285
+ detection: HarmonyDetection;
286
+ model: Model;
287
+ retryN: number;
288
+ removed: string;
289
+ }): HarmonyAuditEvent {
290
+ return {
291
+ action: params.action,
292
+ surface: params.detection.surface,
293
+ signal: signalListLabel(params.detection.signals),
294
+ retryN: params.retryN,
295
+ model: params.model.id,
296
+ provider: params.model.provider,
297
+ toolName: params.detection.toolName,
298
+ removedLen: params.removed.length,
299
+ removedSha8: sha8(params.removed),
300
+ removedPreview: redactedJunkPreview(params.removed),
301
+ removedBlob: Bun.env.GJC_HARMONY_DEBUG === "1" ? params.removed : undefined,
302
+ };
303
+ }
304
+
305
+ // ─── internals ──────────────────────────────────────────────────────────────
306
+
307
+ function makeSignal(classes: HarmonySignalClass[], start: number, end: number, text: string): HarmonySignal {
308
+ if (classes[0] === "H") return { classes: ["H"], start, end, text };
309
+ const sorted: HarmonySignalClass[] = [];
310
+ for (const cls of SIGNAL_ORDER) {
311
+ if (classes.includes(cls)) sorted.push(cls);
312
+ }
313
+ return { classes: sorted, start, end, text };
314
+ }
315
+
316
+ /**
317
+ * Precompute fenced-code-block ranges once per text. Each range is a
318
+ * [start, end) span of bytes inside any ```/~~~ fence. O(n) once instead of
319
+ * O(n) per detected match.
320
+ */
321
+ function computeFenceRanges(text: string): Array<[number, number]> {
322
+ const ranges: Array<[number, number]> = [];
323
+ let inFence = false;
324
+ let fenceStart = 0;
325
+ let lineStart = 0;
326
+ while (lineStart <= text.length) {
327
+ const newline = text.indexOf("\n", lineStart);
328
+ const lineEnd = newline === -1 ? text.length : newline;
329
+ const line = text.slice(lineStart, lineEnd);
330
+ if (FENCE_RE.test(line)) {
331
+ if (inFence) {
332
+ ranges.push([fenceStart, lineEnd]);
333
+ inFence = false;
334
+ } else {
335
+ fenceStart = lineStart;
336
+ inFence = true;
337
+ }
338
+ }
339
+ if (newline === -1) break;
340
+ lineStart = newline + 1;
341
+ }
342
+ if (inFence) ranges.push([fenceStart, text.length]);
343
+ return ranges;
344
+ }
345
+
346
+ function isInsideFence(ranges: Array<[number, number]>, position: number): boolean {
347
+ for (const [start, end] of ranges) {
348
+ if (position >= start && position < end) return true;
349
+ if (start > position) break;
350
+ }
351
+ return false;
352
+ }
353
+
354
+ function hasScriptMismatchNear(text: string, start: number, end: number): boolean {
355
+ const near = text.slice(Math.max(0, start - 32), Math.min(text.length, end + 32));
356
+ if (!SCRIPT_RUN_RE.test(near)) return false;
357
+ const surrounding = text.slice(Math.max(0, start - 200), Math.min(text.length, end + 200));
358
+ if (surrounding.length === 0) return false;
359
+ let ascii = 0;
360
+ for (let i = 0; i < surrounding.length; i++) {
361
+ if (surrounding.charCodeAt(i) < 128) ascii++;
362
+ }
363
+ return ascii / surrounding.length >= 0.85;
364
+ }
365
+
366
+ /**
367
+ * Tool-call argument text used for detection scanning. For tools whose args
368
+ * include a free-form `input` string we scan that directly so reported byte
369
+ * offsets line up with the original. For everything else we fall back to a
370
+ * JSON-stringified blob so detection still fires; that path's offsets are
371
+ * NOT meaningful for slicing the original args, but the recovery path gates
372
+ * on `block.arguments.input` being a string and only ever slices that.
373
+ */
374
+ function getToolArgumentText(toolCall: ToolCall): string | undefined {
375
+ if (typeof toolCall.arguments?.input === "string") return toolCall.arguments.input;
376
+ try {
377
+ return JSON.stringify(toolCall.arguments);
378
+ } catch {
379
+ return undefined;
380
+ }
381
+ }
382
+
383
+ function truncateAtLineAndAppendSentinel(
384
+ input: string,
385
+ offset: number,
386
+ sentinel: string,
387
+ ): { clean: string; removed: string } | undefined {
388
+ const lineStart = offset <= 0 ? 0 : input.lastIndexOf("\n", offset - 1) + 1;
389
+ if (lineStart === 0) return undefined; // would cut everything
390
+ const head = input.slice(0, lineStart).replace(/\s+$/, "");
391
+ if (head.length === 0) return undefined;
392
+ return {
393
+ clean: head + sentinel,
394
+ removed: input.slice(lineStart),
395
+ };
396
+ }
397
+
398
+ function sha8(text: string): string {
399
+ return Bun.sha(text, "hex").slice(0, 8);
400
+ }
401
+
402
+ const PREVIEW_KEEP_RE = new RegExp(`[${SCRIPT_CLASS}\\s】【”“…」「、。]`, "u");
403
+ const PREVIEW_TOKEN_RE =
404
+ /^(?:to=functions\.[A-Za-z_]\w*|analysis|commentary|assistant|user|system|developer|tool|changedFiles|RTLU|Jsii(?:_commentary)?|\x4aapgolly)/;
405
+
406
+ /**
407
+ * Privacy-safe preview for the audit log: keeps marker/channel/glitch tokens,
408
+ * non-Latin script chars, and CJK punctuation; replaces everything else
409
+ * (potential source/secrets) with `·`. Sufficient to grow the glitch-token
410
+ * denylist from logs without exposing source content. Capped at 64 chars.
411
+ */
412
+ function redactedJunkPreview(text: string): string {
413
+ const source = text.slice(0, 64);
414
+ let out = "";
415
+ for (let i = 0; i < source.length; ) {
416
+ const tok = PREVIEW_TOKEN_RE.exec(source.slice(i));
417
+ if (tok) {
418
+ out += tok[0];
419
+ i += tok[0].length;
420
+ continue;
421
+ }
422
+ const ch = source[i] ?? "";
423
+ out += PREVIEW_KEEP_RE.test(ch) ? ch : "·";
424
+ i++;
425
+ }
426
+ return out;
427
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ // Core Agent
2
+ export * from "./agent";
3
+ // Loop functions
4
+ export * from "./agent-loop";
5
+ // Append-only context mode
6
+ export * from "./append-only-context";
7
+ // Compaction
8
+ export * from "./compaction";
9
+ export * from "./harmony-leak";
10
+ // Proxy utilities
11
+ export * from "./proxy";
12
+ // Run-level telemetry collector + aggregators
13
+ export * from "./run-collector";
14
+ // Telemetry
15
+ export * from "./telemetry";
16
+ // Thinking selectors
17
+ export * from "./thinking";
18
+ // Types
19
+ export * from "./types";