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