@codelia/core 0.1.84 → 0.1.86

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.
package/dist/index.cjs CHANGED
@@ -71,13 +71,15 @@ __export(index_exports, {
71
71
  isProviderFailureError: () => isProviderFailureError,
72
72
  isUsableModelSpec: () => isUsableModelSpec,
73
73
  listModels: () => listModels,
74
+ prepareToolInvocation: () => prepareToolInvocation,
74
75
  registerModels: () => registerModels,
75
76
  resolveDeepSeekEffort: () => resolveDeepSeekEffort,
76
77
  resolveModel: () => resolveModel,
77
78
  resolveProviderModelId: () => resolveProviderModelId,
78
79
  stringifyContent: () => stringifyContent,
79
80
  stringifyContentParts: () => stringifyContentParts,
80
- supportsFastMode: () => supportsFastMode
81
+ supportsFastMode: () => supportsFastMode,
82
+ toolPermissionClarificationFields: () => toolPermissionClarificationFields
81
83
  });
82
84
  module.exports = __toCommonJS(index_exports);
83
85
 
@@ -1196,53 +1198,23 @@ var DEEPSEEK_MODELS = [
1196
1198
  var resolveDeepSeekEffort = (requested) => requested === "medium" || requested === "xhigh" ? "high" : requested;
1197
1199
 
1198
1200
  // src/models/google.ts
1199
- var GOOGLE_DEFAULT_MODEL = "gemini-3.8-flash";
1201
+ var GOOGLE_DEFAULT_MODEL = "gemini-4-hydrogen";
1200
1202
  var GOOGLE_MODELS = [
1201
- ...["gemini-4-carbon", "gemini-4-hydrogen"].map(
1202
- (id) => ({
1203
- id,
1204
- provider: "google",
1205
- contextWindow: 1048576,
1206
- // Gemini 4 shares input, thinking and output in one context window.
1207
- maxInputTokens: 983040,
1208
- maxOutputTokens: 65536,
1209
- supportsTools: true,
1210
- supportsVision: true,
1211
- supportsReasoning: true
1212
- })
1213
- ),
1214
- {
1215
- id: "gemini-4-argon",
1216
- provider: "google",
1217
- contextWindow: 1048576,
1218
- maxInputTokens: 983040,
1219
- maxOutputTokens: 65536,
1220
- supportsTools: true,
1221
- supportsVision: true,
1222
- supportsReasoning: true
1223
- },
1224
- {
1225
- id: GOOGLE_DEFAULT_MODEL,
1226
- provider: "google",
1227
- aliases: ["default"],
1228
- contextWindow: 1048576,
1229
- maxInputTokens: 1048576,
1230
- maxOutputTokens: 65536,
1231
- supportsTools: true,
1232
- supportsVision: true,
1233
- supportsReasoning: true
1234
- },
1235
- {
1236
- id: "gemini-3.5-flash-lite",
1237
- provider: "google",
1238
- contextWindow: 1048576,
1239
- maxInputTokens: 1048576,
1240
- maxOutputTokens: 65536,
1241
- supportsTools: true,
1242
- supportsVision: true,
1243
- supportsReasoning: true
1244
- }
1245
- ];
1203
+ GOOGLE_DEFAULT_MODEL,
1204
+ "gemini-4-carbon",
1205
+ "gemini-4-argon"
1206
+ ].map((id) => ({
1207
+ id,
1208
+ provider: "google",
1209
+ ...id === GOOGLE_DEFAULT_MODEL ? { aliases: ["default"] } : {},
1210
+ // Gemini 4 shares input, thinking and output in one context window.
1211
+ contextWindow: 1048576,
1212
+ maxInputTokens: 983040,
1213
+ maxOutputTokens: 65536,
1214
+ supportsTools: true,
1215
+ supportsVision: true,
1216
+ supportsReasoning: true
1217
+ }));
1246
1218
 
1247
1219
  // src/models/moonshot.ts
1248
1220
  var MOONSHOT_DEFAULT_MODEL = "kimi-k3";
@@ -2653,6 +2625,13 @@ var TaskComplete = class extends Error {
2653
2625
  };
2654
2626
 
2655
2627
  // src/types/permissions.ts
2628
+ var toolPermissionClarificationFields = [
2629
+ "target",
2630
+ "destination",
2631
+ "scope",
2632
+ "effect",
2633
+ "authorization"
2634
+ ];
2656
2635
  var ToolPermissionDenied = class extends Error {
2657
2636
  constructor(decision) {
2658
2637
  super(`Permission denied${decision.reason ? `: ${decision.reason}` : ""}`);
@@ -2692,7 +2671,11 @@ var createToolContext = (signal) => {
2692
2671
  };
2693
2672
  var permissionDeniedResult = (toolCall, decision) => {
2694
2673
  const toolName = toolCall.function.name;
2695
- const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
2674
+ const deniedContent = decision.clarification ? JSON.stringify({
2675
+ code: "review_user_decision_required",
2676
+ missing: decision.clarification.missing,
2677
+ message: decision.reason
2678
+ }) : `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
2696
2679
  return {
2697
2680
  message: {
2698
2681
  role: "tool",
@@ -2753,13 +2736,14 @@ var executeToolCall = async ({
2753
2736
  toolCall.function.arguments,
2754
2737
  createToolContext(signal)
2755
2738
  );
2739
+ const displayContent = result.display_content && typeof result.display_content === "string" ? result.display_content : tool.displayResult;
2756
2740
  return {
2757
2741
  message: {
2758
2742
  role: "tool",
2759
2743
  tool_call_id: toolCall.id,
2760
2744
  tool_name: toolName,
2761
2745
  content: toolResultToContent(result),
2762
- ...tool.displayResult ? { display_content: tool.displayResult } : {}
2746
+ ...displayContent ? { display_content: displayContent } : {}
2763
2747
  }
2764
2748
  };
2765
2749
  } catch (error) {
@@ -2902,10 +2886,10 @@ var Agent = class {
2902
2886
  getHistoryMessages() {
2903
2887
  return this.history.getViewMessages();
2904
2888
  }
2905
- async recordOriginals(session, messages) {
2889
+ async recordOriginals(session, messages, origins) {
2906
2890
  if (!session?.recordMessages || messages.length === 0) return;
2907
2891
  try {
2908
- await session.recordMessages(messages);
2892
+ await session.recordMessages(messages, origins);
2909
2893
  } catch (cause) {
2910
2894
  throw new ConversationPersistenceError(cause);
2911
2895
  }
@@ -2940,6 +2924,16 @@ var Agent = class {
2940
2924
  );
2941
2925
  this.usageService.updateUsageSummary(usage);
2942
2926
  if (compacted && compactedMessages) {
2927
+ const boundary = options.runContextBoundary;
2928
+ if (boundary) {
2929
+ const currentUsers = new Set(
2930
+ this.history.getViewMessages().slice(boundary.index).filter((message) => message.role === "user")
2931
+ );
2932
+ const firstRetainedUser = compactedMessages.findIndex(
2933
+ (message) => message.role === "user" && currentUsers.has(message)
2934
+ );
2935
+ boundary.index = firstRetainedUser < 0 ? compactedMessages.length : firstRetainedUser;
2936
+ }
2943
2937
  this.history.replaceViewMessages(compactedMessages);
2944
2938
  this.imageUsageBaseline = void 0;
2945
2939
  }
@@ -3026,7 +3020,7 @@ var Agent = class {
3026
3020
  }
3027
3021
  });
3028
3022
  }
3029
- async *invokeModelWithRetry(input, context, signal, streamDeltas = false) {
3023
+ async *invokeModelWithRetry(input, context, signal, streamDeltas = false, accounting) {
3030
3024
  const estimate = estimateImageContext(
3031
3025
  input,
3032
3026
  this.llm,
@@ -3040,6 +3034,9 @@ var Agent = class {
3040
3034
  signal,
3041
3035
  this.attachmentImageResolver
3042
3036
  );
3037
+ throwIfAborted(signal);
3038
+ if (accounting) await accounting.observer.started(accounting.seq);
3039
+ let uncertain = false;
3043
3040
  const response = yield* withProviderStatus(
3044
3041
  (emit, progressSignal) => invokeWithRetry({
3045
3042
  operation: async (attemptSignal) => {
@@ -3065,6 +3062,9 @@ var Agent = class {
3065
3062
  },
3066
3063
  { ...context, onProviderStatus: emit }
3067
3064
  );
3065
+ } catch (error) {
3066
+ uncertain = true;
3067
+ throw error;
3068
3068
  } finally {
3069
3069
  open = false;
3070
3070
  }
@@ -3079,6 +3079,12 @@ var Agent = class {
3079
3079
  }),
3080
3080
  signal
3081
3081
  );
3082
+ if (accounting)
3083
+ await accounting.observer.completed(
3084
+ accounting.seq,
3085
+ response.usage,
3086
+ uncertain
3087
+ );
3082
3088
  this.imageUsageBaseline = response.usage ? {
3083
3089
  messages: input.messages.slice(),
3084
3090
  estimated: estimate.total_tokens,
@@ -3128,8 +3134,31 @@ var Agent = class {
3128
3134
  yield finalResponseEvent2;
3129
3135
  return;
3130
3136
  }
3131
- await this.recordOriginals(session, [{ role: "user", content: message }]);
3132
- this.history.enqueueUserMessage(message);
3137
+ const runContext = options.runContext ? {
3138
+ message: {
3139
+ role: "user",
3140
+ content: options.runContext
3141
+ },
3142
+ boundary: { index: this.history.getViewMessages().length }
3143
+ } : void 0;
3144
+ if (!options.runtimeInitiated) {
3145
+ await this.recordOriginals(
3146
+ session,
3147
+ [{ role: "user", content: message }],
3148
+ [{ source: "user_input" }]
3149
+ );
3150
+ this.history.enqueueUserMessage(message);
3151
+ }
3152
+ const withRunContext = (input) => {
3153
+ if (!runContext) return input;
3154
+ const messages = input.messages.slice();
3155
+ messages.splice(runContext.boundary.index, 0, runContext.message);
3156
+ return { ...input, messages };
3157
+ };
3158
+ const compactionOptions = {
3159
+ session,
3160
+ runContextBoundary: runContext?.boundary
3161
+ };
3133
3162
  const normalizePolledMessage = (item) => typeof item === "string" ? { kind: "hidden", content: item } : item;
3134
3163
  const toPolledAgentEvent = (entry) => entry.kind === "steer" ? {
3135
3164
  type: "steer_applied",
@@ -3148,7 +3177,10 @@ var Agent = class {
3148
3177
  if (messages.length > 0) {
3149
3178
  await this.recordOriginals(
3150
3179
  session,
3151
- messages.map((entry) => ({ role: "user", content: entry.content }))
3180
+ messages.map((entry) => ({ role: "user", content: entry.content })),
3181
+ messages.map(
3182
+ (entry) => entry.kind === "steer" && entry.steer_id ? { source: "user_steer", steerId: entry.steer_id } : { source: "internal_input" }
3183
+ )
3152
3184
  );
3153
3185
  throwIfAborted(signal);
3154
3186
  }
@@ -3173,10 +3205,12 @@ var Agent = class {
3173
3205
  ...this.hostedTools
3174
3206
  ];
3175
3207
  this.lastToolDefinitions = toolDefinitions;
3176
- let invokeInput = this.history.prepareInvokeInput({
3177
- tools: toolDefinitions,
3178
- toolChoice: runToolChoice
3179
- });
3208
+ let invokeInput = withRunContext(
3209
+ this.history.prepareInvokeInput({
3210
+ tools: toolDefinitions,
3211
+ toolChoice: runToolChoice
3212
+ })
3213
+ );
3180
3214
  const imageEstimate = estimateImageContext(
3181
3215
  invokeInput,
3182
3216
  this.llm,
@@ -3188,11 +3222,16 @@ var Agent = class {
3188
3222
  const estimatedInputTokens = baseline && baseline.messages.every(
3189
3223
  (message2, index) => invokeInput.messages[index] === message2
3190
3224
  ) ? baseline.observed + Math.max(0, imageEstimate.total_tokens - baseline.estimated) : imageEstimate.total_tokens;
3191
- yield* this.checkAndCompact(signal, { session, estimatedInputTokens });
3192
- invokeInput = this.history.prepareInvokeInput({
3193
- tools: invokeInput.tools,
3194
- toolChoice: runToolChoice
3225
+ yield* this.checkAndCompact(signal, {
3226
+ ...compactionOptions,
3227
+ estimatedInputTokens
3195
3228
  });
3229
+ invokeInput = withRunContext(
3230
+ this.history.prepareInvokeInput({
3231
+ tools: invokeInput.tools,
3232
+ toolChoice: runToolChoice
3233
+ })
3234
+ );
3196
3235
  }
3197
3236
  const invokeContext = this.buildInvokeContext(session, turnKey);
3198
3237
  const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
@@ -3200,7 +3239,8 @@ var Agent = class {
3200
3239
  invokeInput,
3201
3240
  invokeContext,
3202
3241
  signal,
3203
- options.streamDeltas === true
3242
+ options.streamDeltas === true,
3243
+ seq !== null && options.modelCallObserver ? { seq, observer: options.modelCallObserver } : void 0
3204
3244
  );
3205
3245
  this.recordLlmResponse(session, seq, response);
3206
3246
  this.usageService.updateUsageSummary(response.usage);
@@ -3265,7 +3305,7 @@ var Agent = class {
3265
3305
  }
3266
3306
  if (!hasToolCalls) {
3267
3307
  if (!this.requireDoneTool) {
3268
- yield* this.checkAndCompact(signal, { session });
3308
+ yield* this.checkAndCompact(signal, compactionOptions);
3269
3309
  const incoming = await receiveMessages();
3270
3310
  if (incoming.length > 0) {
3271
3311
  if (shouldEmitFinalOnly) {
@@ -3293,7 +3333,7 @@ var Agent = class {
3293
3333
  yield finalResponseEvent2;
3294
3334
  return;
3295
3335
  } else {
3296
- yield* this.checkAndCompact(signal, { session });
3336
+ yield* this.checkAndCompact(signal, compactionOptions);
3297
3337
  }
3298
3338
  continue;
3299
3339
  }
@@ -3436,13 +3476,15 @@ var Agent = class {
3436
3476
  yield stepCompleteEvent;
3437
3477
  }
3438
3478
  }
3439
- yield* this.checkAndCompact(signal, { session });
3479
+ yield* this.checkAndCompact(signal, compactionOptions);
3440
3480
  }
3441
3481
  if (signal?.aborted) throw createAbortError2();
3442
3482
  const finalResponse = await this.generateFinalResponse(
3443
3483
  session,
3444
3484
  signal,
3445
- turnKey
3485
+ turnKey,
3486
+ options.modelCallObserver,
3487
+ withRunContext
3446
3488
  );
3447
3489
  const finalResponseEvent = {
3448
3490
  type: "final",
@@ -3452,19 +3494,17 @@ var Agent = class {
3452
3494
  yield finalResponseEvent;
3453
3495
  return;
3454
3496
  }
3455
- async generateFinalResponse(session, signal, turnKey) {
3497
+ async generateFinalResponse(session, signal, turnKey, observer, withRunContext = (input) => input) {
3456
3498
  const summaryMessage = {
3457
3499
  role: "user",
3458
3500
  content: `You are generating the final response for the user after the agent reached max iterations. Summarize what was completed, what is pending, and any blockers. Be concise, user-facing, and do not mention internal agent mechanics. If there is a clear next step, suggest it as a short list.`
3459
3501
  };
3460
3502
  try {
3461
- const input = {
3503
+ const input = withRunContext({
3462
3504
  messages: [...this.history.getViewMessages(), summaryMessage],
3463
- // temporal messages for summary
3464
3505
  tools: null,
3465
- // no tools are allowed at this point
3466
3506
  toolChoice: "none"
3467
- };
3507
+ });
3468
3508
  const invokeContext = this.buildInvokeContext(session, turnKey);
3469
3509
  const seq = this.recordLlmRequest(session, input, invokeContext);
3470
3510
  validateImagePayload(
@@ -3476,19 +3516,22 @@ var Agent = class {
3476
3516
  ),
3477
3517
  this.llm
3478
3518
  );
3519
+ const messages = await materializeImageReferences(
3520
+ input.messages,
3521
+ this.services.resolveImage,
3522
+ signal,
3523
+ this.attachmentImageResolver
3524
+ );
3525
+ if (seq !== null && observer) {
3526
+ throwIfAborted(signal);
3527
+ await observer.started(seq);
3528
+ }
3479
3529
  const summary = await this.llm.ainvoke(
3480
- {
3481
- ...input,
3482
- messages: await materializeImageReferences(
3483
- input.messages,
3484
- this.services.resolveImage,
3485
- signal,
3486
- this.attachmentImageResolver
3487
- ),
3488
- ...signal ? { signal } : {}
3489
- },
3530
+ { ...input, messages, ...signal ? { signal } : {} },
3490
3531
  invokeContext
3491
3532
  );
3533
+ if (seq !== null && observer)
3534
+ await observer.completed(seq, summary.usage, false);
3492
3535
  this.recordLlmResponse(session, seq, summary);
3493
3536
  await this.recordOriginals(session, summary.messages);
3494
3537
  this.usageService.updateUsageSummary(summary.usage);
@@ -3498,7 +3541,8 @@ var Agent = class {
3498
3541
  ${assistantTexts.join("\n").trim()}`;
3499
3542
  return finalResponse;
3500
3543
  } catch (error) {
3501
- if (error instanceof ConversationPersistenceError) throw error;
3544
+ if (error instanceof ConversationPersistenceError || observer)
3545
+ throw error;
3502
3546
  if (signal?.aborted) {
3503
3547
  throw createAbortError2();
3504
3548
  }
@@ -10124,13 +10168,46 @@ function toToolResult(value) {
10124
10168
  return { type: "parts", parts: value };
10125
10169
  return { type: "json", value };
10126
10170
  }
10171
+ var preparations = /* @__PURE__ */ new WeakMap();
10172
+ function prepareToolInvocation(tool, raw) {
10173
+ const registration = preparations.get(tool);
10174
+ if (!registration || registration.executeRaw !== tool.executeRaw || registration.validateRaw !== tool.validateRaw)
10175
+ return void 0;
10176
+ return registration.prepare(raw);
10177
+ }
10127
10178
  function defineTool(toolOptions) {
10128
10179
  const parameters = (0, import_zod.toJSONSchema)(toolOptions.input, {
10129
10180
  target: "draft-07",
10130
10181
  io: "input"
10131
10182
  });
10132
10183
  const modelParameters = withTopLevelObjectTypeForObjectUnions(parameters);
10133
- return {
10184
+ const parse = (rawArgsJson) => {
10185
+ let rawArgs;
10186
+ try {
10187
+ rawArgs = JSON.parse(rawArgsJson);
10188
+ } catch (error) {
10189
+ throw new Error(
10190
+ `Invalid tool arguments JSON for ${toolOptions.name}: ${String(error)}`
10191
+ );
10192
+ }
10193
+ const parsed = toolOptions.input.safeParse(rawArgs);
10194
+ if (!parsed.success) {
10195
+ throw new Error(
10196
+ `Tool input validation failed for ${toolOptions.name}: ${parsed.error.message}`
10197
+ );
10198
+ }
10199
+ return parsed.data;
10200
+ };
10201
+ const execute = (input, context) => {
10202
+ const result = toolOptions.execute(input, context);
10203
+ if (result instanceof Promise) return result.then(toToolResult);
10204
+ return Promise.resolve(toToolResult(result));
10205
+ };
10206
+ const prepare = (raw) => {
10207
+ const input = parse(raw);
10208
+ return { input, execute: (context) => execute(input, context) };
10209
+ };
10210
+ const tool = {
10134
10211
  name: toolOptions.name,
10135
10212
  description: toolOptions.description,
10136
10213
  ...toolOptions.displayResult ? { displayResult: toolOptions.displayResult } : {},
@@ -10140,28 +10217,17 @@ function defineTool(toolOptions) {
10140
10217
  parameters: modelParameters,
10141
10218
  strict: false
10142
10219
  },
10143
- executeRaw: (rawArgsJson, ctx) => {
10144
- let rawArgs;
10145
- try {
10146
- rawArgs = JSON.parse(rawArgsJson);
10147
- } catch (error) {
10148
- throw new Error(
10149
- `Invalid tool arguments JSON for ${toolOptions.name}: ${String(error)}`
10150
- );
10151
- }
10152
- const parsed = toolOptions.input.safeParse(rawArgs);
10153
- if (!parsed.success) {
10154
- throw new Error(
10155
- `Tool input validation failed for ${toolOptions.name}: ${parsed.error.message}`
10156
- );
10157
- }
10158
- const result = toolOptions.execute(parsed.data, ctx);
10159
- if (result instanceof Promise) {
10160
- return result.then((result2) => toToolResult(result2));
10161
- }
10162
- return Promise.resolve(toToolResult(result));
10163
- }
10220
+ validateRaw: (raw) => {
10221
+ parse(raw);
10222
+ },
10223
+ executeRaw: (raw, context) => execute(parse(raw), context)
10164
10224
  };
10225
+ preparations.set(tool, {
10226
+ executeRaw: tool.executeRaw,
10227
+ validateRaw: tool.validateRaw,
10228
+ prepare
10229
+ });
10230
+ return tool;
10165
10231
  }
10166
10232
  // Annotate the CommonJS export names for ESM import in node:
10167
10233
  0 && (module.exports = {
@@ -10206,11 +10272,13 @@ function defineTool(toolOptions) {
10206
10272
  isProviderFailureError,
10207
10273
  isUsableModelSpec,
10208
10274
  listModels,
10275
+ prepareToolInvocation,
10209
10276
  registerModels,
10210
10277
  resolveDeepSeekEffort,
10211
10278
  resolveModel,
10212
10279
  resolveProviderModelId,
10213
10280
  stringifyContent,
10214
10281
  stringifyContentParts,
10215
- supportsFastMode
10282
+ supportsFastMode,
10283
+ toolPermissionClarificationFields
10216
10284
  });
package/dist/index.d.ts CHANGED
@@ -70,7 +70,7 @@ type ToolChoice = "auto" | "required" | "none" | string;
70
70
  type JsonValue = string | number | boolean | null | {
71
71
  [key: string]: JsonValue;
72
72
  } | JsonValue[];
73
- type ToolResult = {
73
+ type ToolResult = ({
74
74
  type: "text";
75
75
  text: string;
76
76
  } | {
@@ -79,6 +79,9 @@ type ToolResult = {
79
79
  } | {
80
80
  type: "json";
81
81
  value: unknown;
82
+ }) & {
83
+ /** Optional transcript and diagnostics text for this result. */
84
+ display_content?: string;
82
85
  };
83
86
  type ToolReturn = ToolResult | string | ContentPart[] | JsonValue;
84
87
 
@@ -443,6 +446,8 @@ type Tool = {
443
446
  description: string;
444
447
  displayResult?: string;
445
448
  definition: ToolDefinition;
449
+ /** Validate arguments without executing the tool. */
450
+ validateRaw?: (rawArgsJson: string) => void;
446
451
  executeRaw: (rawArgsJson: string, ctx: ToolContext) => Promise<ToolResult>;
447
452
  };
448
453
  type ToolExecution = {
@@ -454,8 +459,13 @@ type ToolExecution = {
454
459
  type ToolPermissionDecision = {
455
460
  decision: "allow" | "deny";
456
461
  reason?: string;
462
+ clarification?: {
463
+ missing: ToolPermissionClarificationField | "unspecified";
464
+ };
457
465
  stop_turn?: boolean;
458
466
  };
467
+ declare const toolPermissionClarificationFields: readonly ["target", "destination", "scope", "effect", "authorization"];
468
+ type ToolPermissionClarificationField = (typeof toolPermissionClarificationFields)[number];
459
469
  /** Carries a permission decision made inside a tool's shared execution gate. */
460
470
  declare class ToolPermissionDenied extends Error {
461
471
  readonly decision: ToolPermissionDecision;
@@ -501,6 +511,13 @@ type SessionHeader = {
501
511
  };
502
512
  type RunStartRecord = {
503
513
  type: "run.start";
514
+ source?: "goal";
515
+ goal?: {
516
+ goal_id: string;
517
+ revision: number;
518
+ activation_id: string;
519
+ continuation_id?: string;
520
+ };
504
521
  run_id: string;
505
522
  session_id?: string;
506
523
  ts: string;
@@ -602,6 +619,18 @@ type RunErrorRecord = {
602
619
  };
603
620
  meta?: Record<string, unknown>;
604
621
  };
622
+ /** Bounded diagnostic fields only. Review request and response data stay out of the log. */
623
+ type ApprovalReviewFailureRecord = {
624
+ type: "approval.review_failure";
625
+ run_id: string;
626
+ ts: string;
627
+ request_id: string;
628
+ reason: string;
629
+ code: string;
630
+ http_status?: number;
631
+ location?: string;
632
+ position?: number;
633
+ };
605
634
  type RunEndRecord = {
606
635
  type: "run.end";
607
636
  run_id: string;
@@ -610,7 +639,7 @@ type RunEndRecord = {
610
639
  final?: string;
611
640
  meta?: Record<string, unknown>;
612
641
  };
613
- type SessionRecord = SessionHeader | RunStartRecord | RunContextRecord | AgentEventRecord | ToolOutputRecord | LlmRequestRecord | LlmResponseRecord | LlmUsageRecord | RunStatusRecord | RunErrorRecord | RunEndRecord;
642
+ type SessionRecord = SessionHeader | RunStartRecord | RunContextRecord | AgentEventRecord | ToolOutputRecord | LlmRequestRecord | LlmResponseRecord | LlmUsageRecord | RunStatusRecord | RunErrorRecord | ApprovalReviewFailureRecord | RunEndRecord;
614
643
  type SessionStore = {
615
644
  filePath?: string;
616
645
  append: (record: SessionRecord) => Promise<void> | void;
@@ -643,11 +672,41 @@ type ConversationSearchResult = {
643
672
  matches: ConversationMessage[];
644
673
  next_cursor?: string;
645
674
  };
675
+ /** Supplied by the conversation producer, never by message text. */
676
+ type ConversationInputOrigin = {
677
+ source: "user_input" | "internal_input";
678
+ } | {
679
+ source: "user_steer";
680
+ steerId: string;
681
+ };
682
+ type ConversationApprovalScope = {
683
+ workspace: string;
684
+ cwd: string;
685
+ workspaceIdentity: string;
686
+ cwdIdentity: string;
687
+ };
688
+ type ConversationApprovalProvenance = {
689
+ source: "internal_input";
690
+ } | (ConversationApprovalScope & {
691
+ source: "assistant";
692
+ }) | (ConversationApprovalScope & {
693
+ source: "user_input";
694
+ text: string;
695
+ }) | (ConversationApprovalScope & {
696
+ source: "user_steer";
697
+ text: string;
698
+ runId: string;
699
+ steerId: string;
700
+ });
701
+ type ConversationApprovalContext = {
702
+ userMessages: readonly ConversationMessage[];
703
+ proposal?: ConversationMessage;
704
+ };
646
705
  type SessionStateStore = {
647
706
  load: (sessionId: string) => Promise<SessionState | null>;
648
707
  save: (state: SessionState) => Promise<void>;
649
708
  list: () => Promise<SessionStateSummary[]>;
650
- appendMessages?: (sessionId: string, messages: BaseMessage[]) => Promise<void>;
709
+ appendMessages?: (sessionId: string, messages: BaseMessage[], provenance?: readonly (ConversationApprovalProvenance | undefined)[]) => Promise<void>;
651
710
  searchMessages?: (sessionId: string, options: {
652
711
  query: string;
653
712
  cursor?: string;
@@ -658,6 +717,11 @@ type SessionStateStore = {
658
717
  offset?: number;
659
718
  limit?: number;
660
719
  }) => Promise<ConversationMessage | null>;
720
+ readApprovalContext?: (sessionId: string, references: ConversationApprovalScope & {
721
+ userMessageId: string;
722
+ proposalMessageId?: string;
723
+ }) => Promise<ConversationApprovalContext | null>;
724
+ confirmApprovalSteer?: (sessionId: string, runId: string, steerId: string) => Promise<void>;
661
725
  updateMetadata?: (sessionId: string, patch: {
662
726
  pinned?: boolean;
663
727
  archived?: boolean;
@@ -670,7 +734,7 @@ type AgentSession = {
670
734
  on_error?: (error: unknown, record: SessionRecord) => void;
671
735
  append: (record: SessionRecord) => void;
672
736
  /** Await durable originals before admitting messages or discarding context. */
673
- recordMessages?: (messages: BaseMessage[]) => Promise<void>;
737
+ recordMessages?: (messages: BaseMessage[], origins?: readonly (ConversationInputOrigin | undefined)[]) => Promise<void>;
674
738
  };
675
739
 
676
740
  type PolledMessage = string | {
@@ -678,9 +742,17 @@ type PolledMessage = string | {
678
742
  content: string | ContentPart[];
679
743
  steer_id?: string;
680
744
  };
745
+ type ModelCallObserver = {
746
+ started(seq: number): Promise<void>;
747
+ completed(seq: number, usage: ChatInvokeUsage | null | undefined, uncertain: boolean): Promise<void>;
748
+ };
681
749
  type AgentRunOptions = {
682
750
  /** Untrusted messages polled only between model/tool batches; never starts a nested run. */
683
751
  pollMessages?: () => Promise<PolledMessage[]>;
752
+ /** Runtime context is presented at user priority without becoming archival chat. */
753
+ runContext?: string;
754
+ runtimeInitiated?: boolean;
755
+ modelCallObserver?: ModelCallObserver;
684
756
  session?: AgentSession;
685
757
  signal?: AbortSignal;
686
758
  forceCompaction?: boolean;
@@ -1185,7 +1257,7 @@ declare const DEEPSEEK_MODELS: ({
1185
1257
  /** DeepSeek documents medium/xhigh as aliases of high. */
1186
1258
  declare const resolveDeepSeekEffort: (requested: ModelReasoningLevel) => "low" | "high" | "max";
1187
1259
 
1188
- declare const GOOGLE_DEFAULT_MODEL = "gemini-3.8-flash";
1260
+ declare const GOOGLE_DEFAULT_MODEL = "gemini-4-hydrogen";
1189
1261
  declare const GOOGLE_MODELS: ModelSpec[];
1190
1262
 
1191
1263
  declare const MOONSHOT_DEFAULT_MODEL = "kimi-k3";
@@ -1208,6 +1280,12 @@ declare const DEFAULT_MODEL_REGISTRY: ModelRegistry;
1208
1280
 
1209
1281
  declare const getDefaultSystemPromptPath: () => string;
1210
1282
 
1283
+ type PreparedToolInvocation = {
1284
+ input: unknown;
1285
+ execute: (context: ToolContext) => Promise<ToolResult>;
1286
+ };
1287
+ /** Bind validated input to an exact defineTool executor before runtime admission. */
1288
+ declare function prepareToolInvocation(tool: Tool, raw: string): PreparedToolInvocation | undefined;
1211
1289
  declare function defineTool<TInput, TResult extends ToolReturn>(toolOptions: DefineToolOptions<TInput, TResult>): Tool;
1212
1290
 
1213
1291
  declare class TaskComplete extends Error {
@@ -1215,4 +1293,4 @@ declare class TaskComplete extends Error {
1215
1293
  constructor(finalMessage?: string);
1216
1294
  }
1217
1295
 
1218
- export { ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_MODELS, Agent, type AgentEventRecord, type AgentOptions, type AgentRunOptions, type AgentServices, type AgentSession, type BaseChatModel, type BaseMessage, ChatAnthropic, ChatDeepSeek, ChatGoogle, type ChatInvokeContext, type ChatInvokeInput, ChatMoonshot, ChatOpenAI, ChatOpenRouter, ChatResponses, type ChatStreamDelta, type ChatStreamDeltaSink, ChatXai, ChatZai, type ConversationMessage, type ConversationSearchResult, DEEPSEEK_DEFAULT_MODEL, DEEPSEEK_MODELS, DEFAULT_MODEL_REGISTRY, type DependencyKey, GOOGLE_DEFAULT_MODEL, GOOGLE_MODELS, type ImageTokenEstimate, type ImageTokenInput, type LlmRequestRecord, type LlmResponseRecord, type LlmUsageRecord, MOONSHOT_DEFAULT_MODEL, MOONSHOT_K3_1_MODELS, MOONSHOT_MODELS, type ModelCapabilities, type ModelCost, type ModelEntry, type ModelLimits, type ModelMetadataIndex, type ModelMetadataService, type ModelRegistry, type ModelSpec, OPENAI_DEFAULT_MODEL, OPENAI_DEFAULT_REASONING_EFFORT, OPENAI_MODELS, type PolledMessage, type ProviderFailure, type ProviderFailureClassifier, ProviderFailureError, type ProviderFailureKind, type ResolveStorageOptions, type ResponsesInvokeOptions, type RetryDelaySource, type RunContextRecord, type RunEndRecord, type RunErrorRecord, type RunEventStoreFactory, type RunEventStoreInit, type RunStartRecord, type RunStatusRecord, type SessionHeader, type SessionRecord, type SessionState, type SessionStateStore, type SessionStateSummary, type SessionStore, type StorageLayout, type StoragePathService, type StoragePaths, type StringifyContentMode, type StringifyContentOptions, TaskComplete, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolExecution, type ToolOutputCacheConfig, type ToolOutputCacheReadOptions, type ToolOutputCacheRecord, type ToolOutputCacheSearchOptions, ToolOutputCacheService, type ToolOutputCacheStore, type ToolOutputRecord, type ToolOutputRef, type ToolPermissionDecision, ToolPermissionDenied, type ToolPermissionHook, type ToolResult, XAI_DEFAULT_MODEL, XAI_DEFAULT_REASONING_EFFORT, XAI_MODELS, ZAI_DEFAULT_MODEL, ZAI_MODELS, ZAI_REASONING_EFFORT_MODELS, applyModelMetadata, createModelRegistry, createProviderResponseError, defineTool, getDefaultSystemPromptPath, isProviderFailureError, isUsableModelSpec, listModels, registerModels, resolveDeepSeekEffort, resolveModel, resolveProviderModelId, stringifyContent, stringifyContentParts, supportsFastMode };
1296
+ export { ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_MODELS, Agent, type AgentEventRecord, type AgentOptions, type AgentRunOptions, type AgentServices, type AgentSession, type ApprovalReviewFailureRecord, type BaseChatModel, type BaseMessage, ChatAnthropic, ChatDeepSeek, ChatGoogle, type ChatInvokeContext, type ChatInvokeInput, type ChatInvokeUsage, ChatMoonshot, ChatOpenAI, ChatOpenRouter, ChatResponses, type ChatStreamDelta, type ChatStreamDeltaSink, ChatXai, ChatZai, type ConversationApprovalContext, type ConversationApprovalProvenance, type ConversationApprovalScope, type ConversationInputOrigin, type ConversationMessage, type ConversationSearchResult, DEEPSEEK_DEFAULT_MODEL, DEEPSEEK_MODELS, DEFAULT_MODEL_REGISTRY, type DependencyKey, GOOGLE_DEFAULT_MODEL, GOOGLE_MODELS, type ImageTokenEstimate, type ImageTokenInput, type LlmRequestRecord, type LlmResponseRecord, type LlmUsageRecord, MOONSHOT_DEFAULT_MODEL, MOONSHOT_K3_1_MODELS, MOONSHOT_MODELS, type ModelCapabilities, type ModelCost, type ModelEntry, type ModelLimits, type ModelMetadataIndex, type ModelMetadataService, type ModelRegistry, type ModelSpec, OPENAI_DEFAULT_MODEL, OPENAI_DEFAULT_REASONING_EFFORT, OPENAI_MODELS, type PolledMessage, type ProviderFailure, type ProviderFailureClassifier, ProviderFailureError, type ProviderFailureKind, type ResolveStorageOptions, type ResponsesInvokeOptions, type RetryDelaySource, type RunContextRecord, type RunEndRecord, type RunErrorRecord, type RunEventStoreFactory, type RunEventStoreInit, type RunStartRecord, type RunStatusRecord, type SessionHeader, type SessionRecord, type SessionState, type SessionStateStore, type SessionStateSummary, type SessionStore, type StorageLayout, type StoragePathService, type StoragePaths, type StringifyContentMode, type StringifyContentOptions, TaskComplete, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolExecution, type ToolOutputCacheConfig, type ToolOutputCacheReadOptions, type ToolOutputCacheRecord, type ToolOutputCacheSearchOptions, ToolOutputCacheService, type ToolOutputCacheStore, type ToolOutputRecord, type ToolOutputRef, type ToolPermissionClarificationField, type ToolPermissionDecision, ToolPermissionDenied, type ToolPermissionHook, type ToolResult, XAI_DEFAULT_MODEL, XAI_DEFAULT_REASONING_EFFORT, XAI_MODELS, ZAI_DEFAULT_MODEL, ZAI_MODELS, ZAI_REASONING_EFFORT_MODELS, applyModelMetadata, createModelRegistry, createProviderResponseError, defineTool, getDefaultSystemPromptPath, isProviderFailureError, isUsableModelSpec, listModels, prepareToolInvocation, registerModels, resolveDeepSeekEffort, resolveModel, resolveProviderModelId, stringifyContent, stringifyContentParts, supportsFastMode, toolPermissionClarificationFields };
package/dist/index.js CHANGED
@@ -1113,53 +1113,23 @@ var DEEPSEEK_MODELS = [
1113
1113
  var resolveDeepSeekEffort = (requested) => requested === "medium" || requested === "xhigh" ? "high" : requested;
1114
1114
 
1115
1115
  // src/models/google.ts
1116
- var GOOGLE_DEFAULT_MODEL = "gemini-3.8-flash";
1116
+ var GOOGLE_DEFAULT_MODEL = "gemini-4-hydrogen";
1117
1117
  var GOOGLE_MODELS = [
1118
- ...["gemini-4-carbon", "gemini-4-hydrogen"].map(
1119
- (id) => ({
1120
- id,
1121
- provider: "google",
1122
- contextWindow: 1048576,
1123
- // Gemini 4 shares input, thinking and output in one context window.
1124
- maxInputTokens: 983040,
1125
- maxOutputTokens: 65536,
1126
- supportsTools: true,
1127
- supportsVision: true,
1128
- supportsReasoning: true
1129
- })
1130
- ),
1131
- {
1132
- id: "gemini-4-argon",
1133
- provider: "google",
1134
- contextWindow: 1048576,
1135
- maxInputTokens: 983040,
1136
- maxOutputTokens: 65536,
1137
- supportsTools: true,
1138
- supportsVision: true,
1139
- supportsReasoning: true
1140
- },
1141
- {
1142
- id: GOOGLE_DEFAULT_MODEL,
1143
- provider: "google",
1144
- aliases: ["default"],
1145
- contextWindow: 1048576,
1146
- maxInputTokens: 1048576,
1147
- maxOutputTokens: 65536,
1148
- supportsTools: true,
1149
- supportsVision: true,
1150
- supportsReasoning: true
1151
- },
1152
- {
1153
- id: "gemini-3.5-flash-lite",
1154
- provider: "google",
1155
- contextWindow: 1048576,
1156
- maxInputTokens: 1048576,
1157
- maxOutputTokens: 65536,
1158
- supportsTools: true,
1159
- supportsVision: true,
1160
- supportsReasoning: true
1161
- }
1162
- ];
1118
+ GOOGLE_DEFAULT_MODEL,
1119
+ "gemini-4-carbon",
1120
+ "gemini-4-argon"
1121
+ ].map((id) => ({
1122
+ id,
1123
+ provider: "google",
1124
+ ...id === GOOGLE_DEFAULT_MODEL ? { aliases: ["default"] } : {},
1125
+ // Gemini 4 shares input, thinking and output in one context window.
1126
+ contextWindow: 1048576,
1127
+ maxInputTokens: 983040,
1128
+ maxOutputTokens: 65536,
1129
+ supportsTools: true,
1130
+ supportsVision: true,
1131
+ supportsReasoning: true
1132
+ }));
1163
1133
 
1164
1134
  // src/models/moonshot.ts
1165
1135
  var MOONSHOT_DEFAULT_MODEL = "kimi-k3";
@@ -2570,6 +2540,13 @@ var TaskComplete = class extends Error {
2570
2540
  };
2571
2541
 
2572
2542
  // src/types/permissions.ts
2543
+ var toolPermissionClarificationFields = [
2544
+ "target",
2545
+ "destination",
2546
+ "scope",
2547
+ "effect",
2548
+ "authorization"
2549
+ ];
2573
2550
  var ToolPermissionDenied = class extends Error {
2574
2551
  constructor(decision) {
2575
2552
  super(`Permission denied${decision.reason ? `: ${decision.reason}` : ""}`);
@@ -2609,7 +2586,11 @@ var createToolContext = (signal) => {
2609
2586
  };
2610
2587
  var permissionDeniedResult = (toolCall, decision) => {
2611
2588
  const toolName = toolCall.function.name;
2612
- const deniedContent = `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
2589
+ const deniedContent = decision.clarification ? JSON.stringify({
2590
+ code: "review_user_decision_required",
2591
+ missing: decision.clarification.missing,
2592
+ message: decision.reason
2593
+ }) : `Permission denied${decision.reason ? `: ${decision.reason}` : ""}`;
2613
2594
  return {
2614
2595
  message: {
2615
2596
  role: "tool",
@@ -2670,13 +2651,14 @@ var executeToolCall = async ({
2670
2651
  toolCall.function.arguments,
2671
2652
  createToolContext(signal)
2672
2653
  );
2654
+ const displayContent = result.display_content && typeof result.display_content === "string" ? result.display_content : tool.displayResult;
2673
2655
  return {
2674
2656
  message: {
2675
2657
  role: "tool",
2676
2658
  tool_call_id: toolCall.id,
2677
2659
  tool_name: toolName,
2678
2660
  content: toolResultToContent(result),
2679
- ...tool.displayResult ? { display_content: tool.displayResult } : {}
2661
+ ...displayContent ? { display_content: displayContent } : {}
2680
2662
  }
2681
2663
  };
2682
2664
  } catch (error) {
@@ -2819,10 +2801,10 @@ var Agent = class {
2819
2801
  getHistoryMessages() {
2820
2802
  return this.history.getViewMessages();
2821
2803
  }
2822
- async recordOriginals(session, messages) {
2804
+ async recordOriginals(session, messages, origins) {
2823
2805
  if (!session?.recordMessages || messages.length === 0) return;
2824
2806
  try {
2825
- await session.recordMessages(messages);
2807
+ await session.recordMessages(messages, origins);
2826
2808
  } catch (cause) {
2827
2809
  throw new ConversationPersistenceError(cause);
2828
2810
  }
@@ -2857,6 +2839,16 @@ var Agent = class {
2857
2839
  );
2858
2840
  this.usageService.updateUsageSummary(usage);
2859
2841
  if (compacted && compactedMessages) {
2842
+ const boundary = options.runContextBoundary;
2843
+ if (boundary) {
2844
+ const currentUsers = new Set(
2845
+ this.history.getViewMessages().slice(boundary.index).filter((message) => message.role === "user")
2846
+ );
2847
+ const firstRetainedUser = compactedMessages.findIndex(
2848
+ (message) => message.role === "user" && currentUsers.has(message)
2849
+ );
2850
+ boundary.index = firstRetainedUser < 0 ? compactedMessages.length : firstRetainedUser;
2851
+ }
2860
2852
  this.history.replaceViewMessages(compactedMessages);
2861
2853
  this.imageUsageBaseline = void 0;
2862
2854
  }
@@ -2943,7 +2935,7 @@ var Agent = class {
2943
2935
  }
2944
2936
  });
2945
2937
  }
2946
- async *invokeModelWithRetry(input, context, signal, streamDeltas = false) {
2938
+ async *invokeModelWithRetry(input, context, signal, streamDeltas = false, accounting) {
2947
2939
  const estimate = estimateImageContext(
2948
2940
  input,
2949
2941
  this.llm,
@@ -2957,6 +2949,9 @@ var Agent = class {
2957
2949
  signal,
2958
2950
  this.attachmentImageResolver
2959
2951
  );
2952
+ throwIfAborted(signal);
2953
+ if (accounting) await accounting.observer.started(accounting.seq);
2954
+ let uncertain = false;
2960
2955
  const response = yield* withProviderStatus(
2961
2956
  (emit, progressSignal) => invokeWithRetry({
2962
2957
  operation: async (attemptSignal) => {
@@ -2982,6 +2977,9 @@ var Agent = class {
2982
2977
  },
2983
2978
  { ...context, onProviderStatus: emit }
2984
2979
  );
2980
+ } catch (error) {
2981
+ uncertain = true;
2982
+ throw error;
2985
2983
  } finally {
2986
2984
  open = false;
2987
2985
  }
@@ -2996,6 +2994,12 @@ var Agent = class {
2996
2994
  }),
2997
2995
  signal
2998
2996
  );
2997
+ if (accounting)
2998
+ await accounting.observer.completed(
2999
+ accounting.seq,
3000
+ response.usage,
3001
+ uncertain
3002
+ );
2999
3003
  this.imageUsageBaseline = response.usage ? {
3000
3004
  messages: input.messages.slice(),
3001
3005
  estimated: estimate.total_tokens,
@@ -3045,8 +3049,31 @@ var Agent = class {
3045
3049
  yield finalResponseEvent2;
3046
3050
  return;
3047
3051
  }
3048
- await this.recordOriginals(session, [{ role: "user", content: message }]);
3049
- this.history.enqueueUserMessage(message);
3052
+ const runContext = options.runContext ? {
3053
+ message: {
3054
+ role: "user",
3055
+ content: options.runContext
3056
+ },
3057
+ boundary: { index: this.history.getViewMessages().length }
3058
+ } : void 0;
3059
+ if (!options.runtimeInitiated) {
3060
+ await this.recordOriginals(
3061
+ session,
3062
+ [{ role: "user", content: message }],
3063
+ [{ source: "user_input" }]
3064
+ );
3065
+ this.history.enqueueUserMessage(message);
3066
+ }
3067
+ const withRunContext = (input) => {
3068
+ if (!runContext) return input;
3069
+ const messages = input.messages.slice();
3070
+ messages.splice(runContext.boundary.index, 0, runContext.message);
3071
+ return { ...input, messages };
3072
+ };
3073
+ const compactionOptions = {
3074
+ session,
3075
+ runContextBoundary: runContext?.boundary
3076
+ };
3050
3077
  const normalizePolledMessage = (item) => typeof item === "string" ? { kind: "hidden", content: item } : item;
3051
3078
  const toPolledAgentEvent = (entry) => entry.kind === "steer" ? {
3052
3079
  type: "steer_applied",
@@ -3065,7 +3092,10 @@ var Agent = class {
3065
3092
  if (messages.length > 0) {
3066
3093
  await this.recordOriginals(
3067
3094
  session,
3068
- messages.map((entry) => ({ role: "user", content: entry.content }))
3095
+ messages.map((entry) => ({ role: "user", content: entry.content })),
3096
+ messages.map(
3097
+ (entry) => entry.kind === "steer" && entry.steer_id ? { source: "user_steer", steerId: entry.steer_id } : { source: "internal_input" }
3098
+ )
3069
3099
  );
3070
3100
  throwIfAborted(signal);
3071
3101
  }
@@ -3090,10 +3120,12 @@ var Agent = class {
3090
3120
  ...this.hostedTools
3091
3121
  ];
3092
3122
  this.lastToolDefinitions = toolDefinitions;
3093
- let invokeInput = this.history.prepareInvokeInput({
3094
- tools: toolDefinitions,
3095
- toolChoice: runToolChoice
3096
- });
3123
+ let invokeInput = withRunContext(
3124
+ this.history.prepareInvokeInput({
3125
+ tools: toolDefinitions,
3126
+ toolChoice: runToolChoice
3127
+ })
3128
+ );
3097
3129
  const imageEstimate = estimateImageContext(
3098
3130
  invokeInput,
3099
3131
  this.llm,
@@ -3105,11 +3137,16 @@ var Agent = class {
3105
3137
  const estimatedInputTokens = baseline && baseline.messages.every(
3106
3138
  (message2, index) => invokeInput.messages[index] === message2
3107
3139
  ) ? baseline.observed + Math.max(0, imageEstimate.total_tokens - baseline.estimated) : imageEstimate.total_tokens;
3108
- yield* this.checkAndCompact(signal, { session, estimatedInputTokens });
3109
- invokeInput = this.history.prepareInvokeInput({
3110
- tools: invokeInput.tools,
3111
- toolChoice: runToolChoice
3140
+ yield* this.checkAndCompact(signal, {
3141
+ ...compactionOptions,
3142
+ estimatedInputTokens
3112
3143
  });
3144
+ invokeInput = withRunContext(
3145
+ this.history.prepareInvokeInput({
3146
+ tools: invokeInput.tools,
3147
+ toolChoice: runToolChoice
3148
+ })
3149
+ );
3113
3150
  }
3114
3151
  const invokeContext = this.buildInvokeContext(session, turnKey);
3115
3152
  const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
@@ -3117,7 +3154,8 @@ var Agent = class {
3117
3154
  invokeInput,
3118
3155
  invokeContext,
3119
3156
  signal,
3120
- options.streamDeltas === true
3157
+ options.streamDeltas === true,
3158
+ seq !== null && options.modelCallObserver ? { seq, observer: options.modelCallObserver } : void 0
3121
3159
  );
3122
3160
  this.recordLlmResponse(session, seq, response);
3123
3161
  this.usageService.updateUsageSummary(response.usage);
@@ -3182,7 +3220,7 @@ var Agent = class {
3182
3220
  }
3183
3221
  if (!hasToolCalls) {
3184
3222
  if (!this.requireDoneTool) {
3185
- yield* this.checkAndCompact(signal, { session });
3223
+ yield* this.checkAndCompact(signal, compactionOptions);
3186
3224
  const incoming = await receiveMessages();
3187
3225
  if (incoming.length > 0) {
3188
3226
  if (shouldEmitFinalOnly) {
@@ -3210,7 +3248,7 @@ var Agent = class {
3210
3248
  yield finalResponseEvent2;
3211
3249
  return;
3212
3250
  } else {
3213
- yield* this.checkAndCompact(signal, { session });
3251
+ yield* this.checkAndCompact(signal, compactionOptions);
3214
3252
  }
3215
3253
  continue;
3216
3254
  }
@@ -3353,13 +3391,15 @@ var Agent = class {
3353
3391
  yield stepCompleteEvent;
3354
3392
  }
3355
3393
  }
3356
- yield* this.checkAndCompact(signal, { session });
3394
+ yield* this.checkAndCompact(signal, compactionOptions);
3357
3395
  }
3358
3396
  if (signal?.aborted) throw createAbortError2();
3359
3397
  const finalResponse = await this.generateFinalResponse(
3360
3398
  session,
3361
3399
  signal,
3362
- turnKey
3400
+ turnKey,
3401
+ options.modelCallObserver,
3402
+ withRunContext
3363
3403
  );
3364
3404
  const finalResponseEvent = {
3365
3405
  type: "final",
@@ -3369,19 +3409,17 @@ var Agent = class {
3369
3409
  yield finalResponseEvent;
3370
3410
  return;
3371
3411
  }
3372
- async generateFinalResponse(session, signal, turnKey) {
3412
+ async generateFinalResponse(session, signal, turnKey, observer, withRunContext = (input) => input) {
3373
3413
  const summaryMessage = {
3374
3414
  role: "user",
3375
3415
  content: `You are generating the final response for the user after the agent reached max iterations. Summarize what was completed, what is pending, and any blockers. Be concise, user-facing, and do not mention internal agent mechanics. If there is a clear next step, suggest it as a short list.`
3376
3416
  };
3377
3417
  try {
3378
- const input = {
3418
+ const input = withRunContext({
3379
3419
  messages: [...this.history.getViewMessages(), summaryMessage],
3380
- // temporal messages for summary
3381
3420
  tools: null,
3382
- // no tools are allowed at this point
3383
3421
  toolChoice: "none"
3384
- };
3422
+ });
3385
3423
  const invokeContext = this.buildInvokeContext(session, turnKey);
3386
3424
  const seq = this.recordLlmRequest(session, input, invokeContext);
3387
3425
  validateImagePayload(
@@ -3393,19 +3431,22 @@ var Agent = class {
3393
3431
  ),
3394
3432
  this.llm
3395
3433
  );
3434
+ const messages = await materializeImageReferences(
3435
+ input.messages,
3436
+ this.services.resolveImage,
3437
+ signal,
3438
+ this.attachmentImageResolver
3439
+ );
3440
+ if (seq !== null && observer) {
3441
+ throwIfAborted(signal);
3442
+ await observer.started(seq);
3443
+ }
3396
3444
  const summary = await this.llm.ainvoke(
3397
- {
3398
- ...input,
3399
- messages: await materializeImageReferences(
3400
- input.messages,
3401
- this.services.resolveImage,
3402
- signal,
3403
- this.attachmentImageResolver
3404
- ),
3405
- ...signal ? { signal } : {}
3406
- },
3445
+ { ...input, messages, ...signal ? { signal } : {} },
3407
3446
  invokeContext
3408
3447
  );
3448
+ if (seq !== null && observer)
3449
+ await observer.completed(seq, summary.usage, false);
3409
3450
  this.recordLlmResponse(session, seq, summary);
3410
3451
  await this.recordOriginals(session, summary.messages);
3411
3452
  this.usageService.updateUsageSummary(summary.usage);
@@ -3415,7 +3456,8 @@ var Agent = class {
3415
3456
  ${assistantTexts.join("\n").trim()}`;
3416
3457
  return finalResponse;
3417
3458
  } catch (error) {
3418
- if (error instanceof ConversationPersistenceError) throw error;
3459
+ if (error instanceof ConversationPersistenceError || observer)
3460
+ throw error;
3419
3461
  if (signal?.aborted) {
3420
3462
  throw createAbortError2();
3421
3463
  }
@@ -10041,13 +10083,46 @@ function toToolResult(value) {
10041
10083
  return { type: "parts", parts: value };
10042
10084
  return { type: "json", value };
10043
10085
  }
10086
+ var preparations = /* @__PURE__ */ new WeakMap();
10087
+ function prepareToolInvocation(tool, raw) {
10088
+ const registration = preparations.get(tool);
10089
+ if (!registration || registration.executeRaw !== tool.executeRaw || registration.validateRaw !== tool.validateRaw)
10090
+ return void 0;
10091
+ return registration.prepare(raw);
10092
+ }
10044
10093
  function defineTool(toolOptions) {
10045
10094
  const parameters = toJSONSchema(toolOptions.input, {
10046
10095
  target: "draft-07",
10047
10096
  io: "input"
10048
10097
  });
10049
10098
  const modelParameters = withTopLevelObjectTypeForObjectUnions(parameters);
10050
- return {
10099
+ const parse = (rawArgsJson) => {
10100
+ let rawArgs;
10101
+ try {
10102
+ rawArgs = JSON.parse(rawArgsJson);
10103
+ } catch (error) {
10104
+ throw new Error(
10105
+ `Invalid tool arguments JSON for ${toolOptions.name}: ${String(error)}`
10106
+ );
10107
+ }
10108
+ const parsed = toolOptions.input.safeParse(rawArgs);
10109
+ if (!parsed.success) {
10110
+ throw new Error(
10111
+ `Tool input validation failed for ${toolOptions.name}: ${parsed.error.message}`
10112
+ );
10113
+ }
10114
+ return parsed.data;
10115
+ };
10116
+ const execute = (input, context) => {
10117
+ const result = toolOptions.execute(input, context);
10118
+ if (result instanceof Promise) return result.then(toToolResult);
10119
+ return Promise.resolve(toToolResult(result));
10120
+ };
10121
+ const prepare = (raw) => {
10122
+ const input = parse(raw);
10123
+ return { input, execute: (context) => execute(input, context) };
10124
+ };
10125
+ const tool = {
10051
10126
  name: toolOptions.name,
10052
10127
  description: toolOptions.description,
10053
10128
  ...toolOptions.displayResult ? { displayResult: toolOptions.displayResult } : {},
@@ -10057,28 +10132,17 @@ function defineTool(toolOptions) {
10057
10132
  parameters: modelParameters,
10058
10133
  strict: false
10059
10134
  },
10060
- executeRaw: (rawArgsJson, ctx) => {
10061
- let rawArgs;
10062
- try {
10063
- rawArgs = JSON.parse(rawArgsJson);
10064
- } catch (error) {
10065
- throw new Error(
10066
- `Invalid tool arguments JSON for ${toolOptions.name}: ${String(error)}`
10067
- );
10068
- }
10069
- const parsed = toolOptions.input.safeParse(rawArgs);
10070
- if (!parsed.success) {
10071
- throw new Error(
10072
- `Tool input validation failed for ${toolOptions.name}: ${parsed.error.message}`
10073
- );
10074
- }
10075
- const result = toolOptions.execute(parsed.data, ctx);
10076
- if (result instanceof Promise) {
10077
- return result.then((result2) => toToolResult(result2));
10078
- }
10079
- return Promise.resolve(toToolResult(result));
10080
- }
10135
+ validateRaw: (raw) => {
10136
+ parse(raw);
10137
+ },
10138
+ executeRaw: (raw, context) => execute(parse(raw), context)
10081
10139
  };
10140
+ preparations.set(tool, {
10141
+ executeRaw: tool.executeRaw,
10142
+ validateRaw: tool.validateRaw,
10143
+ prepare
10144
+ });
10145
+ return tool;
10082
10146
  }
10083
10147
  export {
10084
10148
  ANTHROPIC_DEFAULT_MODEL,
@@ -10122,11 +10186,13 @@ export {
10122
10186
  isProviderFailureError,
10123
10187
  isUsableModelSpec,
10124
10188
  listModels,
10189
+ prepareToolInvocation,
10125
10190
  registerModels,
10126
10191
  resolveDeepSeekEffort,
10127
10192
  resolveModel,
10128
10193
  resolveProviderModelId,
10129
10194
  stringifyContent,
10130
10195
  stringifyContentParts,
10131
- supportsFastMode
10196
+ supportsFastMode,
10197
+ toolPermissionClarificationFields
10132
10198
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelia/core",
3
- "version": "0.1.84",
3
+ "version": "0.1.86",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "files": [
@@ -26,8 +26,8 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@anthropic-ai/sdk": "^0.110.0",
29
- "@codelia/config": "0.1.84",
30
- "@codelia/shared-types": "0.1.84",
29
+ "@codelia/config": "0.1.86",
30
+ "@codelia/shared-types": "0.1.86",
31
31
  "@google/genai": "2.32.0",
32
32
  "image-size": "^2.0.2",
33
33
  "json-schema": "^0.4.0",