jeopi-agent-core 16.2.13

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 (66) hide show
  1. package/CHANGELOG.md +1016 -0
  2. package/README.md +473 -0
  3. package/dist/types/agent-loop.d.ts +66 -0
  4. package/dist/types/agent.d.ts +427 -0
  5. package/dist/types/append-only-context.d.ts +133 -0
  6. package/dist/types/compaction/branch-summarization.d.ts +101 -0
  7. package/dist/types/compaction/compaction-v2-streaming.d.ts +82 -0
  8. package/dist/types/compaction/compaction.d.ts +283 -0
  9. package/dist/types/compaction/entries.d.ts +110 -0
  10. package/dist/types/compaction/errors.d.ts +26 -0
  11. package/dist/types/compaction/index.d.ts +12 -0
  12. package/dist/types/compaction/messages.d.ts +77 -0
  13. package/dist/types/compaction/openai.d.ts +77 -0
  14. package/dist/types/compaction/pruning.d.ts +105 -0
  15. package/dist/types/compaction/shake.d.ts +92 -0
  16. package/dist/types/compaction/tool-protection.d.ts +17 -0
  17. package/dist/types/compaction/utils.d.ts +58 -0
  18. package/dist/types/compaction.d.ts +1 -0
  19. package/dist/types/index.d.ts +12 -0
  20. package/dist/types/proxy.d.ts +85 -0
  21. package/dist/types/replay-policy.d.ts +5 -0
  22. package/dist/types/run-collector.d.ts +196 -0
  23. package/dist/types/telemetry.d.ts +590 -0
  24. package/dist/types/thinking.d.ts +17 -0
  25. package/dist/types/tokenizer.d.ts +1 -0
  26. package/dist/types/types.d.ts +640 -0
  27. package/dist/types/utils/yield.d.ts +71 -0
  28. package/package.json +78 -0
  29. package/src/agent-loop.ts +2188 -0
  30. package/src/agent.ts +1457 -0
  31. package/src/append-only-context.ts +348 -0
  32. package/src/compaction/branch-summarization.ts +370 -0
  33. package/src/compaction/compaction-v2-streaming.ts +719 -0
  34. package/src/compaction/compaction.ts +1553 -0
  35. package/src/compaction/entries.ts +142 -0
  36. package/src/compaction/errors.ts +31 -0
  37. package/src/compaction/index.ts +13 -0
  38. package/src/compaction/messages.ts +237 -0
  39. package/src/compaction/openai.ts +581 -0
  40. package/src/compaction/prompts/auto-handoff-threshold-focus.md +1 -0
  41. package/src/compaction/prompts/branch-summary-context.md +5 -0
  42. package/src/compaction/prompts/branch-summary-preamble.md +2 -0
  43. package/src/compaction/prompts/branch-summary.md +30 -0
  44. package/src/compaction/prompts/compaction-short-summary.md +9 -0
  45. package/src/compaction/prompts/compaction-summary-context.md +5 -0
  46. package/src/compaction/prompts/compaction-summary.md +38 -0
  47. package/src/compaction/prompts/compaction-turn-prefix.md +17 -0
  48. package/src/compaction/prompts/compaction-update-summary.md +45 -0
  49. package/src/compaction/prompts/file-operations.md +5 -0
  50. package/src/compaction/prompts/handoff-document.md +49 -0
  51. package/src/compaction/prompts/snapcompact-archive-context.md +3 -0
  52. package/src/compaction/prompts/summarization-system.md +3 -0
  53. package/src/compaction/pruning.ts +424 -0
  54. package/src/compaction/shake.ts +429 -0
  55. package/src/compaction/tool-protection.ts +55 -0
  56. package/src/compaction/utils.ts +323 -0
  57. package/src/compaction.ts +1 -0
  58. package/src/index.ts +24 -0
  59. package/src/proxy.ts +376 -0
  60. package/src/replay-policy.ts +13 -0
  61. package/src/run-collector.ts +631 -0
  62. package/src/telemetry.ts +2034 -0
  63. package/src/thinking.ts +19 -0
  64. package/src/tokenizer.ts +17 -0
  65. package/src/types.ts +718 -0
  66. package/src/utils/yield.ts +183 -0
package/src/types.ts ADDED
@@ -0,0 +1,718 @@
1
+ import type {
2
+ ApiKey,
3
+ AssistantMessage,
4
+ AssistantMessageEvent,
5
+ AssistantMessageEventStream,
6
+ Context,
7
+ Effort,
8
+ ImageContent,
9
+ Message,
10
+ Model,
11
+ ServiceTier,
12
+ SimpleStreamOptions,
13
+ Static,
14
+ streamSimple,
15
+ TextContent,
16
+ Tool,
17
+ ToolChoice,
18
+ ToolResultMessage,
19
+ TSchema,
20
+ } from "jeopi-ai";
21
+ import type { Dialect } from "jeopi-ai/dialect";
22
+ import type { HarmonyAuditEvent } from "jeopi-ai/utils/harmony-leak";
23
+ import type { AppendOnlyContextManager } from "./append-only-context";
24
+ import type { AgentRunCoverage, AgentRunSummary } from "./run-collector";
25
+ import type { AgentTelemetryConfig } from "./telemetry";
26
+
27
+ /** Stream function - can return sync or Promise for async config lookup */
28
+ export type StreamFn = (
29
+ ...args: Parameters<typeof streamSimple>
30
+ ) => AssistantMessageEventStream | Promise<AssistantMessageEventStream>;
31
+
32
+ /**
33
+ * An aside entry: a ready {@link AgentMessage}, or a sync thunk evaluated at
34
+ * injection time that returns the message to inject or `null` to skip it. Thunks
35
+ * let the producer make the final inject-or-drop decision against current state
36
+ * (e.g. dropping late diagnostics a newer edit superseded).
37
+ */
38
+ export type AsideMessage = AgentMessage | (() => AgentMessage | null);
39
+
40
+ export interface AgentTurnEndContext {
41
+ /** Assistant/user message that just completed this turn boundary. */
42
+ message: AgentMessage;
43
+ /** Tool results produced by this turn, already paired with `message` in the live context. */
44
+ toolResults: ToolResultMessage[];
45
+ /** True when the current tool-loop batch is continuing without yielding to post-turn steering. */
46
+ willContinue: boolean;
47
+ }
48
+
49
+ /**
50
+ * A soft tool requirement: the host wants `toolName` called before the loop
51
+ * runs other tools or yields, but WITHOUT paying the forced-`toolChoice` cost
52
+ * up front (changing `tool_choice` invalidates the provider message cache).
53
+ * Returned from {@link AgentLoopConfig.getToolChoice} in place of a hard
54
+ * {@link ToolChoice}: the loop injects `reminder` once when a new `id` becomes
55
+ * active, runs with `toolChoice` unchanged, and escalates to a one-turn forced
56
+ * choice only if the model fails to call `toolName`. Auto-clears when the host
57
+ * stops returning it or `toolName` is no longer an active tool.
58
+ */
59
+ export interface SoftToolRequirement {
60
+ /** Discriminates a soft requirement from a hard {@link ToolChoice}. */
61
+ soft: true;
62
+ /**
63
+ * Stable id of the *current* requirement. The loop injects `reminder` when
64
+ * this id first becomes active and again whenever it changes (e.g. one
65
+ * stacked preview resolves and the next becomes the head), but never
66
+ * re-injects for an unchanged id across turns.
67
+ */
68
+ id: string;
69
+ /** Tool that must be called before the loop runs other tools or yields. */
70
+ toolName: string;
71
+ /** Host-owned reminder messages, injected once per `id` activation. */
72
+ reminder: AgentMessage[];
73
+ }
74
+
75
+ /**
76
+ * A per-turn tool-choice directive: either a hard provider {@link ToolChoice}
77
+ * (applied verbatim) or a {@link SoftToolRequirement} (remind-then-escalate).
78
+ */
79
+ export type ToolChoiceDirective = ToolChoice | SoftToolRequirement;
80
+
81
+ /** True when a {@link ToolChoiceDirective} is a soft requirement, not a hard choice. */
82
+ export function isSoftToolRequirement(directive: ToolChoiceDirective | undefined): directive is SoftToolRequirement {
83
+ return typeof directive === "object" && directive !== null && (directive as SoftToolRequirement).soft === true;
84
+ }
85
+
86
+ /**
87
+ * Configuration for the agent loop.
88
+ */
89
+ export interface AgentLoopConfig extends SimpleStreamOptions {
90
+ model: Model;
91
+
92
+ /**
93
+ * When to interrupt tool execution for steering messages.
94
+ * - "immediate" = check after each tool call (default)
95
+ * - "wait" = defer steering until the current turn completes
96
+ */
97
+ interruptMode?: "immediate" | "wait";
98
+
99
+ /**
100
+ * Optional session identifier forwarded to LLM providers.
101
+ * Used by providers that support session-based caching (e.g., OpenAI Codex).
102
+ */
103
+ sessionId?: string;
104
+
105
+ /** Absolute wall-clock deadline in Unix epoch milliseconds. */
106
+ deadline?: number;
107
+
108
+ /**
109
+ * Optional resolver called per LLM request to produce request metadata.
110
+ * When set, the agent loop evaluates it **after** `getApiKey` resolves the
111
+ * session-sticky credential, ensuring the metadata's `account_uuid` reflects
112
+ * the credential actually used for the request (not the credential that was
113
+ * current when `AgentLoopConfig` was first constructed). Overrides the static
114
+ * `metadata` field when present.
115
+ */
116
+ metadataResolver?: (provider: string) => Record<string, unknown> | undefined;
117
+
118
+ /**
119
+ * Converts AgentMessage[] to LLM-compatible Message[] before each LLM call.
120
+ *
121
+ * Each AgentMessage must be converted to a UserMessage, AssistantMessage, or ToolResultMessage
122
+ * that the LLM can understand. AgentMessages that cannot be converted (e.g., UI-only notifications,
123
+ * status messages) should be filtered out.
124
+ *
125
+ * @example
126
+ * ```typescript
127
+ * convertToLlm: (messages) => messages.flatMap(m => {
128
+ * if (m.role === "custom") {
129
+ * // Convert custom message to user message
130
+ * return [{ role: "user", content: m.content, timestamp: m.timestamp }];
131
+ * }
132
+ * if (m.role === "notification") {
133
+ * // Filter out UI-only messages
134
+ * return [];
135
+ * }
136
+ * // Pass through standard LLM messages
137
+ * return [m];
138
+ * })
139
+ * ```
140
+ */
141
+ convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
142
+
143
+ /**
144
+ * Optional transform applied to the context before `convertToLlm`.
145
+ *
146
+ * Use this for operations that work at the AgentMessage level:
147
+ * - Context window management (pruning old messages)
148
+ * - Injecting context from external sources
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * transformContext: async (messages) => {
153
+ * if (estimateTokens(messages) > MAX_TOKENS) {
154
+ * return pruneOldMessages(messages);
155
+ * }
156
+ * return messages;
157
+ * }
158
+ * ```
159
+ */
160
+ transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
161
+
162
+ /**
163
+ * Optional transform applied to the final provider context after conversion,
164
+ * normalization, and append-only context handling, but before telemetry capture
165
+ * and provider send.
166
+ */
167
+ transformProviderContext?: (context: Context, model: Model) => Context | Promise<Context>;
168
+
169
+ /**
170
+ * Resolves the API key or resolver for the current model before each LLM call.
171
+ *
172
+ * Returning an ApiKeyResolver lets the stream retry policy refresh or rotate
173
+ * the model-scoped credential after auth/usage-limit errors.
174
+ */
175
+ getApiKey?: (model: Model) => Promise<ApiKey | undefined> | ApiKey | undefined;
176
+
177
+ /**
178
+ * Returns steering messages to inject into the conversation mid-run.
179
+ *
180
+ * Called at injection boundaries only (loop start and after a tool batch
181
+ * fully settles), so dequeued messages are immediately injected. The
182
+ * mid-batch interrupt poll uses {@link hasSteeringMessages} instead and
183
+ * never consumes the queue.
184
+ */
185
+ getSteeringMessages?: () => Promise<AgentMessage[]>;
186
+
187
+ /**
188
+ * Peeks whether steering messages are queued, without consuming them.
189
+ *
190
+ * Called after each tool execution (unless interruptMode is "wait") to decide
191
+ * whether to skip the remaining tool calls in the batch. The queue keeps
192
+ * owning its messages until the loop reaches the next injection boundary and
193
+ * dequeues via {@link getSteeringMessages} — so callers can still cancel or
194
+ * restore queued messages while in-flight tools settle, and an external
195
+ * abort in that window leaves the queue intact for a post-abort continue.
196
+ *
197
+ * When omitted, steering never interrupts a running tool batch; queued
198
+ * messages are still delivered at the next injection boundary.
199
+ */
200
+ hasSteeringMessages?: () => boolean | Promise<boolean>;
201
+
202
+ /**
203
+ * Peeks whether IRC messages should interrupt an interruptible waiting tool.
204
+ *
205
+ * Uses the same delivery rules as steering: the poll is non-consuming, only
206
+ * runs for interruptible tools, and is ignored when interruptMode is "wait".
207
+ * The host owns message injection at the next boundary.
208
+ */
209
+ hasIrcInterrupts?: () => boolean | Promise<boolean>;
210
+
211
+ /**
212
+ * Returns follow-up messages to process after the agent would otherwise stop.
213
+ *
214
+ * Called when the agent has no more tool calls and no steering messages.
215
+ * If messages are returned, they're added to the context and the agent
216
+ * continues with another turn.
217
+ */
218
+ getFollowUpMessages?: () => Promise<AgentMessage[]>;
219
+ /**
220
+ * Returns non-interrupting "aside" messages to inject at a step boundary.
221
+ *
222
+ * Polled after each tool batch (before the next LLM call) AND at the yield
223
+ * check. Unlike steering, these NEVER abort in-flight tools — they are passive
224
+ * notifications (e.g. background-job completions, late LSP diagnostics) that
225
+ * should reach the model between requests without waiting for the agent to
226
+ * fully stop. Returned messages are appended to the context with normal
227
+ * message events and keep the loop running so the model can react.
228
+ */
229
+ getAsideMessages?: () => Promise<AsideMessage[]>;
230
+ /**
231
+ * Hook fired right before the loop would exit.
232
+ *
233
+ * Called when the agent has no more tool calls and no steering messages,
234
+ * immediately before polling follow-up messages.
235
+ */
236
+ onBeforeYield?: () => Promise<void> | void;
237
+
238
+ /**
239
+ * Provides tool execution context, resolved per tool call.
240
+ * Use for late-bound UI or session state access.
241
+ */
242
+ getToolContext?: (toolCall?: ToolCallContext) => AgentToolContext | undefined;
243
+
244
+ /**
245
+ * Refreshes prompt/tool context from live session state before each model call.
246
+ * Use this when tool availability or the system prompt can change mid-turn.
247
+ */
248
+ syncContextBeforeModelCall?: (context: AgentContext) => void | Promise<void>;
249
+
250
+ /**
251
+ * Optional transform applied to tool call arguments before execution.
252
+ * Use for deobfuscating secrets or rewriting arguments.
253
+ */
254
+ transformToolCallArguments?: (args: Record<string, unknown>, toolName: string) => Record<string, unknown>;
255
+
256
+ /**
257
+ * Enable intent tracing for tool calls.
258
+ * When enabled, the harness injects a `string` field into tool schemas sent to the model,
259
+ * then strips from arguments before executing tools.
260
+ */
261
+ intentTracing?: boolean;
262
+ /**
263
+ * Strip tool descriptions (top-level + nested schema annotations) from the
264
+ * provider-bound tool specs. Use when the full catalog is rendered into the
265
+ * system prompt instead, so descriptions are not duplicated on the wire.
266
+ */
267
+ pruneToolDescriptions?: boolean;
268
+ /**
269
+ * Owned tool calling dialect.
270
+ *
271
+ * Undefined keeps provider-native tool calling. A dialect value sends no
272
+ * native `tools`, forces `toolChoice` off, appends that dialect's tool catalog
273
+ * instructions, re-encodes prior tool calls/results as text, and parses the
274
+ * model's text output back into canonical `toolCall` blocks.
275
+ */
276
+ dialect?: Dialect;
277
+ /**
278
+ * When owned (in-band) tool calling is active and the model starts
279
+ * fabricating a tool result inside its own turn, control how the loop reacts:
280
+ * - `true` (default): abort the provider request immediately so it stops
281
+ * generating the hallucinated continuation (cheaper, lower latency).
282
+ * - `false`: let the request finish and silently discard everything past the
283
+ * fabrication boundary (keeps the connection alive but pays for the tokens
284
+ * the model spends on the discarded tail).
285
+ * Only meaningful when {@link dialect} (or `PI_DIALECT`) selects an
286
+ * owned dialect; native tool calling never fabricates results in text.
287
+ */
288
+ abortOnFabricatedToolResult?: boolean;
289
+ /**
290
+ * Append-only context mode — stabilizes system prompt + tool spec bytes
291
+ * across turns so provider prefix caches hit at maximum rate.
292
+ *
293
+ * When set, the loop reads messages from the append-only log (stable
294
+ * byte prefix) and caches system prompt + tools. Tools exclude per-turn
295
+ * `i` intent fields.
296
+ */
297
+ appendOnlyContext?: AppendOnlyContextManager;
298
+
299
+ /**
300
+ * Inspect assistant streaming events before they are published to the outer agent event stream.
301
+ * Callers may abort synchronously to stop consuming buffered provider events.
302
+ */
303
+ onAssistantMessageEvent?: (message: AssistantMessage, event: AssistantMessageEvent) => void;
304
+
305
+ /**
306
+ * Called when GPT-5 Harmony protocol leakage is detected and mitigated.
307
+ */
308
+ onHarmonyLeak?: (event: HarmonyAuditEvent) => void | Promise<void>;
309
+
310
+ /**
311
+ * Dynamic tool-choice directive, resolved once per turn. Returns a hard
312
+ * {@link ToolChoice} (applied verbatim, overriding the static `toolChoice`),
313
+ * a {@link SoftToolRequirement} (the loop reminds-then-escalates instead of
314
+ * forcing `tool_choice` immediately, so a model that complies with the
315
+ * reminder pays no message-cache invalidation), or `undefined` to fall back
316
+ * to the static `toolChoice`.
317
+ */
318
+ getToolChoice?: () => ToolChoiceDirective | undefined;
319
+
320
+ /**
321
+ * Dynamic reasoning effort override, resolved per LLM call.
322
+ * When set and returns a value, overrides the static `reasoning` captured
323
+ * at run-loop start. Use this so mid-run thinking-level changes apply on
324
+ * the next model call instead of waiting for the next prompt.
325
+ */
326
+ getReasoning?: () => Effort | undefined;
327
+
328
+ /**
329
+ * Dynamic reasoning-disable override, resolved per LLM call. When set,
330
+ * its return value overrides the static `disableReasoning` from
331
+ * `SimpleStreamOptions` for that request. Pair with `getReasoning` so
332
+ * mid-run transitions into and out of the explicit `off` state propagate
333
+ * to the next provider call.
334
+ */
335
+ getDisableReasoning?: () => boolean | undefined;
336
+
337
+ /**
338
+ * Per-call effective service-tier resolver. Unlike {@link getReasoning},
339
+ * this is *authoritative*: when set, its return value (including
340
+ * `undefined`) fully replaces the static `serviceTier` for the request and
341
+ * its telemetry. The resolver receives the model being requested so the
342
+ * caller can scope the tier per provider/model without mutating the shared
343
+ * session `serviceTier` (e.g. opting a Fireworks model into the Priority
344
+ * serving path while leaving the OpenAI/Anthropic tier untouched).
345
+ */
346
+ getServiceTier?: (model: Model) => ServiceTier | undefined;
347
+
348
+ /**
349
+ * Per-call working-directory resolver, read once per LLM call. When set, its
350
+ * return value overrides the static {@link SimpleStreamOptions.cwd} for the
351
+ * request (falling back to that static `cwd` when it returns `undefined`).
352
+ * Lets the host reflect a session move (`/move`, which updates the working
353
+ * directory without reconstructing the loop config) into provider options —
354
+ * e.g. GitLab Duo Agent namespace/project discovery keys off this cwd's git
355
+ * remote, so a stale value would strand discovery on the original repo.
356
+ */
357
+ getCwd?: () => string | undefined;
358
+
359
+ /**
360
+ * Called after a tool call has been validated and is about to execute.
361
+ *
362
+ * Return `{ block: true }` to prevent execution. The loop emits an error tool
363
+ * result instead (using `reason` as the error text, or a default if omitted).
364
+ *
365
+ * Mutating `context.args` in place changes the arguments passed to `tool.execute`
366
+ * — the loop does **not** re-validate after this hook runs.
367
+ *
368
+ * The hook receives the tool abort signal (`signal`) and is responsible for
369
+ * honoring it. Throwing surfaces as a tool-error result and does not abort the
370
+ * rest of the batch.
371
+ */
372
+ beforeToolCall?: (
373
+ context: BeforeToolCallContext,
374
+ signal?: AbortSignal,
375
+ ) => Promise<BeforeToolCallResult | undefined> | BeforeToolCallResult | undefined;
376
+ /**
377
+ * Called after a turn ends and before the loop polls steering/asides for the
378
+ * next iteration. `context` carries the just-finished turn; `context.willContinue`
379
+ * is true when the current tool-loop batch is continuing without yielding to
380
+ * post-turn steering.
381
+ */
382
+ onTurnEnd?: (messages: AgentMessage[], signal?: AbortSignal, context?: AgentTurnEndContext) => Promise<void> | void;
383
+
384
+ /**
385
+ * Called once an assistant message is finalized from the model stream, before
386
+ * it is appended to the context, emitted as `message_end`, or its tool calls
387
+ * are validated and dispatched. The hook may mutate the message in place —
388
+ * both its text content and its tool-call arguments — and those edits are seen
389
+ * by the transcript, the UI, and tool execution alike (single source of truth).
390
+ *
391
+ * Used for inline macro expansion: rewriting `@[[runtime.name(args)]]` tokens
392
+ * to host-computed values before anything downstream consumes the message.
393
+ * Runs at most once per assistant message; must not throw (a throw would abort
394
+ * the turn).
395
+ */
396
+ transformAssistantMessage?: (message: AssistantMessage, signal?: AbortSignal) => Promise<void> | void;
397
+
398
+ /**
399
+ * Called after a tool finishes executing, before `tool_execution_end` and the
400
+ * tool-result message are emitted.
401
+ *
402
+ * Return an `AfterToolCallResult` to override individual fields of the executed
403
+ * tool result. Omitted fields keep their original values; there is no deep merge.
404
+ *
405
+ * Throwing surfaces as a tool-error result and does not abort the rest of the batch.
406
+ */
407
+ afterToolCall?: (
408
+ context: AfterToolCallContext,
409
+ signal?: AbortSignal,
410
+ ) => Promise<AfterToolCallResult | undefined> | AfterToolCallResult | undefined;
411
+ /**
412
+ * Opt-in OpenTelemetry instrumentation. Passing `{}` enables the loop's
413
+ * GenAI-semantic-convention spans (`invoke_agent`, `chat`, `execute_tool`)
414
+ * using the global tracer provider. Leaving this field undefined disables
415
+ * the instrumentation entirely — the loop performs zero tracer lookups.
416
+ *
417
+ * See {@link AgentTelemetryConfig} for the full surface (hooks, content
418
+ * capture, cost estimator, agent identity).
419
+ */
420
+ telemetry?: AgentTelemetryConfig;
421
+ }
422
+
423
+ /**
424
+ * Batch/sequencing metadata for the tool call currently being processed.
425
+ */
426
+ export interface ToolCallContext {
427
+ batchId: string;
428
+ index: number;
429
+ total: number;
430
+ toolCalls: Array<{ id: string; name: string }>;
431
+ }
432
+
433
+ /** A single tool-call content block emitted by an assistant message. */
434
+ export type AgentToolCall = Extract<AssistantMessage["content"][number], { type: "toolCall" }>;
435
+
436
+ /**
437
+ * Result returned from `beforeToolCall`.
438
+ *
439
+ * Set `block: true` to prevent the tool from executing. The loop emits an error tool
440
+ * result instead, using `reason` as the error text (or a default if omitted).
441
+ *
442
+ * Mutating the `args` reference passed in `BeforeToolCallContext` is supported and
443
+ * survives into execution — the loop does **not** re-validate after this hook runs.
444
+ */
445
+ export interface BeforeToolCallResult {
446
+ block?: boolean;
447
+ reason?: string;
448
+ }
449
+
450
+ /**
451
+ * Partial override returned from `afterToolCall`.
452
+ *
453
+ * Merge semantics are field-by-field; omitted fields keep the executed values.
454
+ * No deep merge is performed.
455
+ */
456
+ export interface AfterToolCallResult {
457
+ /** If provided, replaces the tool result content array in full. */
458
+ content?: (TextContent | ImageContent)[];
459
+ /** If provided, replaces the tool result details payload in full. */
460
+ details?: unknown;
461
+ /** If provided, replaces the error flag carried with the tool result. */
462
+ isError?: boolean;
463
+ /** If provided, replaces the contextually-useless flag carried with the tool result. */
464
+ useless?: boolean;
465
+ }
466
+
467
+ /** Context passed to `beforeToolCall`. */
468
+ export interface BeforeToolCallContext {
469
+ /** The assistant message that requested the tool call. */
470
+ assistantMessage: AssistantMessage;
471
+ /** The raw tool call block from `assistantMessage.content`. */
472
+ toolCall: AgentToolCall;
473
+ /**
474
+ * Validated tool arguments. The same reference is forwarded to `tool.execute`
475
+ * (after any `transformToolCallArguments` pass), so in-place mutations stick.
476
+ */
477
+ args: Record<string, unknown>;
478
+ /** Current agent context at the time the tool call is prepared. */
479
+ context: AgentContext;
480
+ }
481
+
482
+ /** Context passed to `afterToolCall`. */
483
+ export interface AfterToolCallContext {
484
+ /** The assistant message that requested the tool call. */
485
+ assistantMessage: AssistantMessage;
486
+ /** The raw tool call block from `assistantMessage.content`. */
487
+ toolCall: AgentToolCall;
488
+ /** Validated tool arguments used for execution (post `beforeToolCall` mutations). */
489
+ args: Record<string, unknown>;
490
+ /** The executed tool result before any `afterToolCall` overrides are applied. */
491
+ result: AgentToolResult<any>;
492
+ /** Whether the executed tool result is currently treated as an error. */
493
+ isError: boolean;
494
+ /** Current agent context at the time the tool call is finalized. */
495
+ context: AgentContext;
496
+ }
497
+
498
+ /**
499
+ * Extensible interface for custom app messages.
500
+ * Apps can extend via declaration merging:
501
+ *
502
+ * @example
503
+ * ```typescript
504
+ * declare module "jeopi-agent-core" {
505
+ * interface CustomAgentMessages {
506
+ * artifact: ArtifactMessage;
507
+ * notification: NotificationMessage;
508
+ * }
509
+ * }
510
+ * ```
511
+ */
512
+ export interface CustomAgentMessages {
513
+ // Empty by default - apps extend via declaration merging
514
+ }
515
+
516
+ /**
517
+ * AgentMessage: Union of LLM messages + custom messages.
518
+ * This abstraction allows apps to add custom message types while maintaining
519
+ * type safety and compatibility with the base LLM messages.
520
+ */
521
+ export type AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages];
522
+
523
+ /**
524
+ * Agent state containing all configuration and conversation data.
525
+ */
526
+ export interface AgentState {
527
+ systemPrompt: string[];
528
+ model: Model;
529
+ thinkingLevel?: Effort;
530
+ disableReasoning?: boolean;
531
+ tools: AgentTool<any>[];
532
+ messages: AgentMessage[]; // Can include attachments + custom message types
533
+ isStreaming: boolean;
534
+ streamMessage: AgentMessage | null;
535
+ pendingToolCalls: Set<string>;
536
+ error?: string;
537
+ }
538
+
539
+ export interface AgentToolResult<T = any, _TInput = unknown> {
540
+ // Content blocks supporting text and images
541
+ content: (TextContent | ImageContent)[];
542
+ // Details to be displayed in a UI or logged
543
+ details?: T;
544
+ // Marks a non-throwing failure (e.g. an aggregator catching per-entry errors).
545
+ // agent-loop honors this and surfaces it as a tool error on the wire.
546
+ isError?: boolean;
547
+ /** Marks the result as contextually useless: safe for compaction to elide once consumed (e.g. zero matches, wait timeout). Ignored when isError is set. */
548
+ useless?: boolean;
549
+ }
550
+
551
+ // Callback for streaming tool execution updates
552
+ export type AgentToolUpdateCallback<T = any, TInput = unknown> = (partialResult: AgentToolResult<T, TInput>) => void;
553
+
554
+ /** Options passed to renderResult */
555
+ export interface RenderResultOptions {
556
+ /** Whether the result view is expanded */
557
+ expanded: boolean;
558
+ /** Whether this is a partial/streaming result */
559
+ isPartial: boolean;
560
+ /** Current spinner frame index for animated elements (optional) */
561
+ spinnerFrame?: number;
562
+ }
563
+
564
+ /** Capability tier a tool exercises. Determines which approval modes auto-approve it. */
565
+ export type ToolTier = "read" | "write" | "exec";
566
+
567
+ /**
568
+ * Per-tool approval declaration.
569
+ * - bare tier ("read" / "write" / "exec") — static classification.
570
+ * - object form — adds a `reason` (shown in the prompt) and/or `override: true`
571
+ * (force-prompt even in modes that would otherwise auto-approve this tier).
572
+ * - function — dynamic, given parsed args. Returns either form above.
573
+ *
574
+ * Omitted approvals are treated as "exec" by callers that enforce approvals.
575
+ */
576
+ export type ToolApprovalDecision = ToolTier | { tier: ToolTier; reason?: string; override?: boolean };
577
+ export type ToolApproval = ToolApprovalDecision | ((args: unknown) => ToolApprovalDecision);
578
+
579
+ /**
580
+ * Context passed to tool execution.
581
+ * Apps can extend via declaration merging.
582
+ */
583
+ export interface AgentToolContext {
584
+ // Empty by default - apps extend via declaration merging
585
+ }
586
+
587
+ export type AgentToolExecFn<TParameters extends TSchema = TSchema, TDetails = any, TTheme = unknown> = (
588
+ this: AgentTool<TParameters, TDetails, TTheme>,
589
+ toolCallId: string,
590
+ params: Static<TParameters>,
591
+ signal?: AbortSignal,
592
+ onUpdate?: AgentToolUpdateCallback<TDetails, TParameters>,
593
+ context?: AgentToolContext,
594
+ ) => Promise<AgentToolResult<TDetails, TParameters>>;
595
+
596
+ // AgentTool extends Tool but adds the execute function
597
+ export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any, TTheme = unknown>
598
+ extends Tool<TParameters> {
599
+ // A human-readable label for the tool to be displayed in UI
600
+ label: string;
601
+ /** If true, tool is excluded unless explicitly listed in --tools or agent's tools field */
602
+ hidden?: boolean;
603
+ /** If true, tool can stage a pending action that requires explicit resolution via the resolve tool. */
604
+ deferrable?: boolean;
605
+ /** Built-in tool loading behavior. "essential" loads initially; "discoverable" can be activated by tool search. */
606
+ loadMode?: "essential" | "discoverable";
607
+ /** Short one-line summary used for tool discovery indexes. */
608
+ summary?: string;
609
+ /**
610
+ * Concurrency mode for tool scheduling when multiple calls are in one turn.
611
+ * - "shared": can run alongside other shared tools (default)
612
+ * - "exclusive": runs alone; other tools wait until it finishes
613
+ * - function: resolved per call from the (raw, pre-validation) arguments
614
+ */
615
+ concurrency?: "shared" | "exclusive" | ((args: Partial<Static<TParameters>>) => "shared" | "exclusive");
616
+ /** If true, argument validation errors are non-fatal: raw args are passed to execute() instead of returning an error to the LLM. */
617
+ lenientArgValidation?: boolean;
618
+ /**
619
+ * If true, the agent loop may abort this tool mid-execution to deliver a
620
+ * queued steering message (instead of waiting for the tool to finish on its
621
+ * own). Set only on tools that purely *wait* and observe their abort signal
622
+ * cleanly (e.g. the `job` poll), so the abort surfaces the tool's current
623
+ * snapshot rather than corrupting a side effect. Honored only when
624
+ * `interruptMode` is "immediate".
625
+ */
626
+ interruptible?: boolean;
627
+ /**
628
+ * Controls how the INTENT_FIELD (`i`) is handled for this tool.
629
+ * - `"require"` (default): `i` is injected and required in the parameter schema.
630
+ * - `"optional"`: `i` is injected as an optional/nullable field.
631
+ * - `"omit"`: `i` is NOT injected. Use for tools where intent is obvious (yield, resolve, todo, …).
632
+ * - function: `i` is NOT injected; intent is derived dynamically from (potentially partial / streaming) args.
633
+ */
634
+ intent?: "omit" | "optional" | "require" | ((args: Partial<Static<TParameters>>) => string | undefined);
635
+
636
+ /**
637
+ * Normalize (potentially partial) streamed arguments into the plain text that
638
+ * stream-content matchers (e.g. TTSR rules) should inspect — the real content
639
+ * the call introduces, without wire grammar such as patch prefixes or JSON
640
+ * string escaping. Return `undefined` to fall back to raw argument-delta
641
+ * matching.
642
+ */
643
+ matcherDigest?: (args: unknown) => string | undefined;
644
+
645
+ /**
646
+ * Surface the target file paths a (potentially partial) streamed call would
647
+ * touch, so path-scoped stream matchers (e.g. TTSR `tool:edit(*.ts)` globs)
648
+ * can match without a top-level `path`/`paths` argument. Used for tools whose
649
+ * wire grammar embeds paths inside the streamed payload (hashline section
650
+ * headers, apply_patch envelope markers). Return `undefined` (or an empty
651
+ * array) to fall back to the caller's top-level argument scan.
652
+ */
653
+ matcherPaths?: (args: unknown) => readonly string[] | undefined;
654
+
655
+ /**
656
+ * Per-file projection of a (potentially partial) streamed call, pairing each
657
+ * touched file path with the digest of only the lines added to that file.
658
+ * Path-scoped stream matchers (TTSR) evaluate each entry in isolation, so a
659
+ * scoped rule like `tool:edit(*.ts)` never fires on text that actually
660
+ * belongs to a sibling Markdown hunk in a multi-file payload. Takes
661
+ * precedence over {@link matcherDigest} + {@link matcherPaths} when present;
662
+ * returns `undefined` (or empty) to fall back to the combined hooks.
663
+ */
664
+ matcherEntries?: (args: unknown) => readonly { path: string; digest: string }[] | undefined;
665
+
666
+ /** Capability tier declaration used by approval gates. Omitted means "exec". */
667
+ approval?: ToolApproval;
668
+
669
+ /** Lines appended after the standard approval prompt header. */
670
+ formatApprovalDetails?: (args: unknown) => string | string[] | undefined;
671
+
672
+ /** The main execution callback for this tool. */
673
+ execute: AgentToolExecFn<TParameters, TDetails, TTheme>;
674
+
675
+ /** Optional custom rendering for tool call display (returns UI component) */
676
+ renderCall?: (args: Static<TParameters>, options: RenderResultOptions, theme: TTheme) => unknown;
677
+
678
+ /** Optional custom rendering for tool result display (returns UI component) */
679
+ renderResult?: (
680
+ result: AgentToolResult<TDetails, TParameters>,
681
+ options: RenderResultOptions,
682
+ theme: TTheme,
683
+ ) => unknown;
684
+ }
685
+
686
+ // AgentContext is like Context but uses AgentTool
687
+ export interface AgentContext {
688
+ systemPrompt: string[];
689
+ messages: AgentMessage[];
690
+ tools?: AgentTool<any>[];
691
+ }
692
+
693
+ /**
694
+ * Events emitted by the Agent for UI updates.
695
+ * These events provide fine-grained lifecycle information for messages, turns, and tool executions.
696
+ */
697
+ export type AgentEvent =
698
+ // Agent lifecycle
699
+ | { type: "agent_start" }
700
+ | {
701
+ type: "agent_end";
702
+ messages: AgentMessage[];
703
+ /** Present iff `AgentTelemetryConfig` was supplied on this run. */
704
+ telemetry?: AgentRunSummary;
705
+ coverage?: AgentRunCoverage;
706
+ }
707
+ // Turn lifecycle - a turn is one assistant response + any tool calls/results
708
+ | { type: "turn_start" }
709
+ | { type: "turn_end"; message: AgentMessage; toolResults: ToolResultMessage[] }
710
+ // Message lifecycle - emitted for user, assistant, and toolResult messages
711
+ | { type: "message_start"; message: AgentMessage }
712
+ // Only emitted for assistant messages during streaming
713
+ | { type: "message_update"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent }
714
+ | { type: "message_end"; message: AgentMessage }
715
+ // Tool execution lifecycle
716
+ | { type: "tool_execution_start"; toolCallId: string; toolName: string; args: any; intent?: string }
717
+ | { type: "tool_execution_update"; toolCallId: string; toolName: string; args: any; partialResult: any }
718
+ | { type: "tool_execution_end"; toolCallId: string; toolName: string; result: any; isError?: boolean };