@codelia/core 0.1.84 → 0.1.85

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
@@ -2753,13 +2753,14 @@ var executeToolCall = async ({
2753
2753
  toolCall.function.arguments,
2754
2754
  createToolContext(signal)
2755
2755
  );
2756
+ const displayContent = result.display_content && typeof result.display_content === "string" ? result.display_content : tool.displayResult;
2756
2757
  return {
2757
2758
  message: {
2758
2759
  role: "tool",
2759
2760
  tool_call_id: toolCall.id,
2760
2761
  tool_name: toolName,
2761
2762
  content: toolResultToContent(result),
2762
- ...tool.displayResult ? { display_content: tool.displayResult } : {}
2763
+ ...displayContent ? { display_content: displayContent } : {}
2763
2764
  }
2764
2765
  };
2765
2766
  } catch (error) {
@@ -2940,6 +2941,16 @@ var Agent = class {
2940
2941
  );
2941
2942
  this.usageService.updateUsageSummary(usage);
2942
2943
  if (compacted && compactedMessages) {
2944
+ const boundary = options.runContextBoundary;
2945
+ if (boundary) {
2946
+ const currentUsers = new Set(
2947
+ this.history.getViewMessages().slice(boundary.index).filter((message) => message.role === "user")
2948
+ );
2949
+ const firstRetainedUser = compactedMessages.findIndex(
2950
+ (message) => message.role === "user" && currentUsers.has(message)
2951
+ );
2952
+ boundary.index = firstRetainedUser < 0 ? compactedMessages.length : firstRetainedUser;
2953
+ }
2943
2954
  this.history.replaceViewMessages(compactedMessages);
2944
2955
  this.imageUsageBaseline = void 0;
2945
2956
  }
@@ -3026,7 +3037,7 @@ var Agent = class {
3026
3037
  }
3027
3038
  });
3028
3039
  }
3029
- async *invokeModelWithRetry(input, context, signal, streamDeltas = false) {
3040
+ async *invokeModelWithRetry(input, context, signal, streamDeltas = false, accounting) {
3030
3041
  const estimate = estimateImageContext(
3031
3042
  input,
3032
3043
  this.llm,
@@ -3040,6 +3051,9 @@ var Agent = class {
3040
3051
  signal,
3041
3052
  this.attachmentImageResolver
3042
3053
  );
3054
+ throwIfAborted(signal);
3055
+ if (accounting) await accounting.observer.started(accounting.seq);
3056
+ let uncertain = false;
3043
3057
  const response = yield* withProviderStatus(
3044
3058
  (emit, progressSignal) => invokeWithRetry({
3045
3059
  operation: async (attemptSignal) => {
@@ -3065,6 +3079,9 @@ var Agent = class {
3065
3079
  },
3066
3080
  { ...context, onProviderStatus: emit }
3067
3081
  );
3082
+ } catch (error) {
3083
+ uncertain = true;
3084
+ throw error;
3068
3085
  } finally {
3069
3086
  open = false;
3070
3087
  }
@@ -3079,6 +3096,12 @@ var Agent = class {
3079
3096
  }),
3080
3097
  signal
3081
3098
  );
3099
+ if (accounting)
3100
+ await accounting.observer.completed(
3101
+ accounting.seq,
3102
+ response.usage,
3103
+ uncertain
3104
+ );
3082
3105
  this.imageUsageBaseline = response.usage ? {
3083
3106
  messages: input.messages.slice(),
3084
3107
  estimated: estimate.total_tokens,
@@ -3128,8 +3151,27 @@ var Agent = class {
3128
3151
  yield finalResponseEvent2;
3129
3152
  return;
3130
3153
  }
3131
- await this.recordOriginals(session, [{ role: "user", content: message }]);
3132
- this.history.enqueueUserMessage(message);
3154
+ const runContext = options.runContext ? {
3155
+ message: {
3156
+ role: "user",
3157
+ content: options.runContext
3158
+ },
3159
+ boundary: { index: this.history.getViewMessages().length }
3160
+ } : void 0;
3161
+ if (!options.runtimeInitiated) {
3162
+ await this.recordOriginals(session, [{ role: "user", content: message }]);
3163
+ this.history.enqueueUserMessage(message);
3164
+ }
3165
+ const withRunContext = (input) => {
3166
+ if (!runContext) return input;
3167
+ const messages = input.messages.slice();
3168
+ messages.splice(runContext.boundary.index, 0, runContext.message);
3169
+ return { ...input, messages };
3170
+ };
3171
+ const compactionOptions = {
3172
+ session,
3173
+ runContextBoundary: runContext?.boundary
3174
+ };
3133
3175
  const normalizePolledMessage = (item) => typeof item === "string" ? { kind: "hidden", content: item } : item;
3134
3176
  const toPolledAgentEvent = (entry) => entry.kind === "steer" ? {
3135
3177
  type: "steer_applied",
@@ -3173,10 +3215,12 @@ var Agent = class {
3173
3215
  ...this.hostedTools
3174
3216
  ];
3175
3217
  this.lastToolDefinitions = toolDefinitions;
3176
- let invokeInput = this.history.prepareInvokeInput({
3177
- tools: toolDefinitions,
3178
- toolChoice: runToolChoice
3179
- });
3218
+ let invokeInput = withRunContext(
3219
+ this.history.prepareInvokeInput({
3220
+ tools: toolDefinitions,
3221
+ toolChoice: runToolChoice
3222
+ })
3223
+ );
3180
3224
  const imageEstimate = estimateImageContext(
3181
3225
  invokeInput,
3182
3226
  this.llm,
@@ -3188,11 +3232,16 @@ var Agent = class {
3188
3232
  const estimatedInputTokens = baseline && baseline.messages.every(
3189
3233
  (message2, index) => invokeInput.messages[index] === message2
3190
3234
  ) ? 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
3235
+ yield* this.checkAndCompact(signal, {
3236
+ ...compactionOptions,
3237
+ estimatedInputTokens
3195
3238
  });
3239
+ invokeInput = withRunContext(
3240
+ this.history.prepareInvokeInput({
3241
+ tools: invokeInput.tools,
3242
+ toolChoice: runToolChoice
3243
+ })
3244
+ );
3196
3245
  }
3197
3246
  const invokeContext = this.buildInvokeContext(session, turnKey);
3198
3247
  const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
@@ -3200,7 +3249,8 @@ var Agent = class {
3200
3249
  invokeInput,
3201
3250
  invokeContext,
3202
3251
  signal,
3203
- options.streamDeltas === true
3252
+ options.streamDeltas === true,
3253
+ seq !== null && options.modelCallObserver ? { seq, observer: options.modelCallObserver } : void 0
3204
3254
  );
3205
3255
  this.recordLlmResponse(session, seq, response);
3206
3256
  this.usageService.updateUsageSummary(response.usage);
@@ -3265,7 +3315,7 @@ var Agent = class {
3265
3315
  }
3266
3316
  if (!hasToolCalls) {
3267
3317
  if (!this.requireDoneTool) {
3268
- yield* this.checkAndCompact(signal, { session });
3318
+ yield* this.checkAndCompact(signal, compactionOptions);
3269
3319
  const incoming = await receiveMessages();
3270
3320
  if (incoming.length > 0) {
3271
3321
  if (shouldEmitFinalOnly) {
@@ -3293,7 +3343,7 @@ var Agent = class {
3293
3343
  yield finalResponseEvent2;
3294
3344
  return;
3295
3345
  } else {
3296
- yield* this.checkAndCompact(signal, { session });
3346
+ yield* this.checkAndCompact(signal, compactionOptions);
3297
3347
  }
3298
3348
  continue;
3299
3349
  }
@@ -3436,13 +3486,15 @@ var Agent = class {
3436
3486
  yield stepCompleteEvent;
3437
3487
  }
3438
3488
  }
3439
- yield* this.checkAndCompact(signal, { session });
3489
+ yield* this.checkAndCompact(signal, compactionOptions);
3440
3490
  }
3441
3491
  if (signal?.aborted) throw createAbortError2();
3442
3492
  const finalResponse = await this.generateFinalResponse(
3443
3493
  session,
3444
3494
  signal,
3445
- turnKey
3495
+ turnKey,
3496
+ options.modelCallObserver,
3497
+ withRunContext
3446
3498
  );
3447
3499
  const finalResponseEvent = {
3448
3500
  type: "final",
@@ -3452,19 +3504,17 @@ var Agent = class {
3452
3504
  yield finalResponseEvent;
3453
3505
  return;
3454
3506
  }
3455
- async generateFinalResponse(session, signal, turnKey) {
3507
+ async generateFinalResponse(session, signal, turnKey, observer, withRunContext = (input) => input) {
3456
3508
  const summaryMessage = {
3457
3509
  role: "user",
3458
3510
  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
3511
  };
3460
3512
  try {
3461
- const input = {
3513
+ const input = withRunContext({
3462
3514
  messages: [...this.history.getViewMessages(), summaryMessage],
3463
- // temporal messages for summary
3464
3515
  tools: null,
3465
- // no tools are allowed at this point
3466
3516
  toolChoice: "none"
3467
- };
3517
+ });
3468
3518
  const invokeContext = this.buildInvokeContext(session, turnKey);
3469
3519
  const seq = this.recordLlmRequest(session, input, invokeContext);
3470
3520
  validateImagePayload(
@@ -3476,19 +3526,22 @@ var Agent = class {
3476
3526
  ),
3477
3527
  this.llm
3478
3528
  );
3529
+ const messages = await materializeImageReferences(
3530
+ input.messages,
3531
+ this.services.resolveImage,
3532
+ signal,
3533
+ this.attachmentImageResolver
3534
+ );
3535
+ if (seq !== null && observer) {
3536
+ throwIfAborted(signal);
3537
+ await observer.started(seq);
3538
+ }
3479
3539
  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
- },
3540
+ { ...input, messages, ...signal ? { signal } : {} },
3490
3541
  invokeContext
3491
3542
  );
3543
+ if (seq !== null && observer)
3544
+ await observer.completed(seq, summary.usage, false);
3492
3545
  this.recordLlmResponse(session, seq, summary);
3493
3546
  await this.recordOriginals(session, summary.messages);
3494
3547
  this.usageService.updateUsageSummary(summary.usage);
@@ -3498,7 +3551,7 @@ var Agent = class {
3498
3551
  ${assistantTexts.join("\n").trim()}`;
3499
3552
  return finalResponse;
3500
3553
  } catch (error) {
3501
- if (error instanceof ConversationPersistenceError) throw error;
3554
+ if (error instanceof ConversationPersistenceError || observer) throw error;
3502
3555
  if (signal?.aborted) {
3503
3556
  throw createAbortError2();
3504
3557
  }
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
 
@@ -501,6 +504,13 @@ type SessionHeader = {
501
504
  };
502
505
  type RunStartRecord = {
503
506
  type: "run.start";
507
+ source?: "goal";
508
+ goal?: {
509
+ goal_id: string;
510
+ revision: number;
511
+ activation_id: string;
512
+ continuation_id?: string;
513
+ };
504
514
  run_id: string;
505
515
  session_id?: string;
506
516
  ts: string;
@@ -678,9 +688,17 @@ type PolledMessage = string | {
678
688
  content: string | ContentPart[];
679
689
  steer_id?: string;
680
690
  };
691
+ type ModelCallObserver = {
692
+ started(seq: number): Promise<void>;
693
+ completed(seq: number, usage: ChatInvokeUsage | null | undefined, uncertain: boolean): Promise<void>;
694
+ };
681
695
  type AgentRunOptions = {
682
696
  /** Untrusted messages polled only between model/tool batches; never starts a nested run. */
683
697
  pollMessages?: () => Promise<PolledMessage[]>;
698
+ /** Runtime context is presented at user priority without becoming archival chat. */
699
+ runContext?: string;
700
+ runtimeInitiated?: boolean;
701
+ modelCallObserver?: ModelCallObserver;
684
702
  session?: AgentSession;
685
703
  signal?: AbortSignal;
686
704
  forceCompaction?: boolean;
@@ -1215,4 +1233,4 @@ declare class TaskComplete extends Error {
1215
1233
  constructor(finalMessage?: string);
1216
1234
  }
1217
1235
 
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 };
1236
+ 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, type ChatInvokeUsage, 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 };
package/dist/index.js CHANGED
@@ -2670,13 +2670,14 @@ var executeToolCall = async ({
2670
2670
  toolCall.function.arguments,
2671
2671
  createToolContext(signal)
2672
2672
  );
2673
+ const displayContent = result.display_content && typeof result.display_content === "string" ? result.display_content : tool.displayResult;
2673
2674
  return {
2674
2675
  message: {
2675
2676
  role: "tool",
2676
2677
  tool_call_id: toolCall.id,
2677
2678
  tool_name: toolName,
2678
2679
  content: toolResultToContent(result),
2679
- ...tool.displayResult ? { display_content: tool.displayResult } : {}
2680
+ ...displayContent ? { display_content: displayContent } : {}
2680
2681
  }
2681
2682
  };
2682
2683
  } catch (error) {
@@ -2857,6 +2858,16 @@ var Agent = class {
2857
2858
  );
2858
2859
  this.usageService.updateUsageSummary(usage);
2859
2860
  if (compacted && compactedMessages) {
2861
+ const boundary = options.runContextBoundary;
2862
+ if (boundary) {
2863
+ const currentUsers = new Set(
2864
+ this.history.getViewMessages().slice(boundary.index).filter((message) => message.role === "user")
2865
+ );
2866
+ const firstRetainedUser = compactedMessages.findIndex(
2867
+ (message) => message.role === "user" && currentUsers.has(message)
2868
+ );
2869
+ boundary.index = firstRetainedUser < 0 ? compactedMessages.length : firstRetainedUser;
2870
+ }
2860
2871
  this.history.replaceViewMessages(compactedMessages);
2861
2872
  this.imageUsageBaseline = void 0;
2862
2873
  }
@@ -2943,7 +2954,7 @@ var Agent = class {
2943
2954
  }
2944
2955
  });
2945
2956
  }
2946
- async *invokeModelWithRetry(input, context, signal, streamDeltas = false) {
2957
+ async *invokeModelWithRetry(input, context, signal, streamDeltas = false, accounting) {
2947
2958
  const estimate = estimateImageContext(
2948
2959
  input,
2949
2960
  this.llm,
@@ -2957,6 +2968,9 @@ var Agent = class {
2957
2968
  signal,
2958
2969
  this.attachmentImageResolver
2959
2970
  );
2971
+ throwIfAborted(signal);
2972
+ if (accounting) await accounting.observer.started(accounting.seq);
2973
+ let uncertain = false;
2960
2974
  const response = yield* withProviderStatus(
2961
2975
  (emit, progressSignal) => invokeWithRetry({
2962
2976
  operation: async (attemptSignal) => {
@@ -2982,6 +2996,9 @@ var Agent = class {
2982
2996
  },
2983
2997
  { ...context, onProviderStatus: emit }
2984
2998
  );
2999
+ } catch (error) {
3000
+ uncertain = true;
3001
+ throw error;
2985
3002
  } finally {
2986
3003
  open = false;
2987
3004
  }
@@ -2996,6 +3013,12 @@ var Agent = class {
2996
3013
  }),
2997
3014
  signal
2998
3015
  );
3016
+ if (accounting)
3017
+ await accounting.observer.completed(
3018
+ accounting.seq,
3019
+ response.usage,
3020
+ uncertain
3021
+ );
2999
3022
  this.imageUsageBaseline = response.usage ? {
3000
3023
  messages: input.messages.slice(),
3001
3024
  estimated: estimate.total_tokens,
@@ -3045,8 +3068,27 @@ var Agent = class {
3045
3068
  yield finalResponseEvent2;
3046
3069
  return;
3047
3070
  }
3048
- await this.recordOriginals(session, [{ role: "user", content: message }]);
3049
- this.history.enqueueUserMessage(message);
3071
+ const runContext = options.runContext ? {
3072
+ message: {
3073
+ role: "user",
3074
+ content: options.runContext
3075
+ },
3076
+ boundary: { index: this.history.getViewMessages().length }
3077
+ } : void 0;
3078
+ if (!options.runtimeInitiated) {
3079
+ await this.recordOriginals(session, [{ role: "user", content: message }]);
3080
+ this.history.enqueueUserMessage(message);
3081
+ }
3082
+ const withRunContext = (input) => {
3083
+ if (!runContext) return input;
3084
+ const messages = input.messages.slice();
3085
+ messages.splice(runContext.boundary.index, 0, runContext.message);
3086
+ return { ...input, messages };
3087
+ };
3088
+ const compactionOptions = {
3089
+ session,
3090
+ runContextBoundary: runContext?.boundary
3091
+ };
3050
3092
  const normalizePolledMessage = (item) => typeof item === "string" ? { kind: "hidden", content: item } : item;
3051
3093
  const toPolledAgentEvent = (entry) => entry.kind === "steer" ? {
3052
3094
  type: "steer_applied",
@@ -3090,10 +3132,12 @@ var Agent = class {
3090
3132
  ...this.hostedTools
3091
3133
  ];
3092
3134
  this.lastToolDefinitions = toolDefinitions;
3093
- let invokeInput = this.history.prepareInvokeInput({
3094
- tools: toolDefinitions,
3095
- toolChoice: runToolChoice
3096
- });
3135
+ let invokeInput = withRunContext(
3136
+ this.history.prepareInvokeInput({
3137
+ tools: toolDefinitions,
3138
+ toolChoice: runToolChoice
3139
+ })
3140
+ );
3097
3141
  const imageEstimate = estimateImageContext(
3098
3142
  invokeInput,
3099
3143
  this.llm,
@@ -3105,11 +3149,16 @@ var Agent = class {
3105
3149
  const estimatedInputTokens = baseline && baseline.messages.every(
3106
3150
  (message2, index) => invokeInput.messages[index] === message2
3107
3151
  ) ? 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
3152
+ yield* this.checkAndCompact(signal, {
3153
+ ...compactionOptions,
3154
+ estimatedInputTokens
3112
3155
  });
3156
+ invokeInput = withRunContext(
3157
+ this.history.prepareInvokeInput({
3158
+ tools: invokeInput.tools,
3159
+ toolChoice: runToolChoice
3160
+ })
3161
+ );
3113
3162
  }
3114
3163
  const invokeContext = this.buildInvokeContext(session, turnKey);
3115
3164
  const seq = this.recordLlmRequest(session, invokeInput, invokeContext);
@@ -3117,7 +3166,8 @@ var Agent = class {
3117
3166
  invokeInput,
3118
3167
  invokeContext,
3119
3168
  signal,
3120
- options.streamDeltas === true
3169
+ options.streamDeltas === true,
3170
+ seq !== null && options.modelCallObserver ? { seq, observer: options.modelCallObserver } : void 0
3121
3171
  );
3122
3172
  this.recordLlmResponse(session, seq, response);
3123
3173
  this.usageService.updateUsageSummary(response.usage);
@@ -3182,7 +3232,7 @@ var Agent = class {
3182
3232
  }
3183
3233
  if (!hasToolCalls) {
3184
3234
  if (!this.requireDoneTool) {
3185
- yield* this.checkAndCompact(signal, { session });
3235
+ yield* this.checkAndCompact(signal, compactionOptions);
3186
3236
  const incoming = await receiveMessages();
3187
3237
  if (incoming.length > 0) {
3188
3238
  if (shouldEmitFinalOnly) {
@@ -3210,7 +3260,7 @@ var Agent = class {
3210
3260
  yield finalResponseEvent2;
3211
3261
  return;
3212
3262
  } else {
3213
- yield* this.checkAndCompact(signal, { session });
3263
+ yield* this.checkAndCompact(signal, compactionOptions);
3214
3264
  }
3215
3265
  continue;
3216
3266
  }
@@ -3353,13 +3403,15 @@ var Agent = class {
3353
3403
  yield stepCompleteEvent;
3354
3404
  }
3355
3405
  }
3356
- yield* this.checkAndCompact(signal, { session });
3406
+ yield* this.checkAndCompact(signal, compactionOptions);
3357
3407
  }
3358
3408
  if (signal?.aborted) throw createAbortError2();
3359
3409
  const finalResponse = await this.generateFinalResponse(
3360
3410
  session,
3361
3411
  signal,
3362
- turnKey
3412
+ turnKey,
3413
+ options.modelCallObserver,
3414
+ withRunContext
3363
3415
  );
3364
3416
  const finalResponseEvent = {
3365
3417
  type: "final",
@@ -3369,19 +3421,17 @@ var Agent = class {
3369
3421
  yield finalResponseEvent;
3370
3422
  return;
3371
3423
  }
3372
- async generateFinalResponse(session, signal, turnKey) {
3424
+ async generateFinalResponse(session, signal, turnKey, observer, withRunContext = (input) => input) {
3373
3425
  const summaryMessage = {
3374
3426
  role: "user",
3375
3427
  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
3428
  };
3377
3429
  try {
3378
- const input = {
3430
+ const input = withRunContext({
3379
3431
  messages: [...this.history.getViewMessages(), summaryMessage],
3380
- // temporal messages for summary
3381
3432
  tools: null,
3382
- // no tools are allowed at this point
3383
3433
  toolChoice: "none"
3384
- };
3434
+ });
3385
3435
  const invokeContext = this.buildInvokeContext(session, turnKey);
3386
3436
  const seq = this.recordLlmRequest(session, input, invokeContext);
3387
3437
  validateImagePayload(
@@ -3393,19 +3443,22 @@ var Agent = class {
3393
3443
  ),
3394
3444
  this.llm
3395
3445
  );
3446
+ const messages = await materializeImageReferences(
3447
+ input.messages,
3448
+ this.services.resolveImage,
3449
+ signal,
3450
+ this.attachmentImageResolver
3451
+ );
3452
+ if (seq !== null && observer) {
3453
+ throwIfAborted(signal);
3454
+ await observer.started(seq);
3455
+ }
3396
3456
  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
- },
3457
+ { ...input, messages, ...signal ? { signal } : {} },
3407
3458
  invokeContext
3408
3459
  );
3460
+ if (seq !== null && observer)
3461
+ await observer.completed(seq, summary.usage, false);
3409
3462
  this.recordLlmResponse(session, seq, summary);
3410
3463
  await this.recordOriginals(session, summary.messages);
3411
3464
  this.usageService.updateUsageSummary(summary.usage);
@@ -3415,7 +3468,7 @@ var Agent = class {
3415
3468
  ${assistantTexts.join("\n").trim()}`;
3416
3469
  return finalResponse;
3417
3470
  } catch (error) {
3418
- if (error instanceof ConversationPersistenceError) throw error;
3471
+ if (error instanceof ConversationPersistenceError || observer) throw error;
3419
3472
  if (signal?.aborted) {
3420
3473
  throw createAbortError2();
3421
3474
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelia/core",
3
- "version": "0.1.84",
3
+ "version": "0.1.85",
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.85",
30
+ "@codelia/shared-types": "0.1.85",
31
31
  "@google/genai": "2.32.0",
32
32
  "image-size": "^2.0.2",
33
33
  "json-schema": "^0.4.0",