@codelia/core 0.1.85 → 0.1.89

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",
@@ -2903,10 +2886,10 @@ var Agent = class {
2903
2886
  getHistoryMessages() {
2904
2887
  return this.history.getViewMessages();
2905
2888
  }
2906
- async recordOriginals(session, messages) {
2889
+ async recordOriginals(session, messages, origins) {
2907
2890
  if (!session?.recordMessages || messages.length === 0) return;
2908
2891
  try {
2909
- await session.recordMessages(messages);
2892
+ await session.recordMessages(messages, origins);
2910
2893
  } catch (cause) {
2911
2894
  throw new ConversationPersistenceError(cause);
2912
2895
  }
@@ -3159,7 +3142,11 @@ var Agent = class {
3159
3142
  boundary: { index: this.history.getViewMessages().length }
3160
3143
  } : void 0;
3161
3144
  if (!options.runtimeInitiated) {
3162
- await this.recordOriginals(session, [{ role: "user", content: message }]);
3145
+ await this.recordOriginals(
3146
+ session,
3147
+ [{ role: "user", content: message }],
3148
+ [{ source: "user_input" }]
3149
+ );
3163
3150
  this.history.enqueueUserMessage(message);
3164
3151
  }
3165
3152
  const withRunContext = (input) => {
@@ -3190,7 +3177,10 @@ var Agent = class {
3190
3177
  if (messages.length > 0) {
3191
3178
  await this.recordOriginals(
3192
3179
  session,
3193
- 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
+ )
3194
3184
  );
3195
3185
  throwIfAborted(signal);
3196
3186
  }
@@ -3551,7 +3541,8 @@ var Agent = class {
3551
3541
  ${assistantTexts.join("\n").trim()}`;
3552
3542
  return finalResponse;
3553
3543
  } catch (error) {
3554
- if (error instanceof ConversationPersistenceError || observer) throw error;
3544
+ if (error instanceof ConversationPersistenceError || observer)
3545
+ throw error;
3555
3546
  if (signal?.aborted) {
3556
3547
  throw createAbortError2();
3557
3548
  }
@@ -10177,13 +10168,46 @@ function toToolResult(value) {
10177
10168
  return { type: "parts", parts: value };
10178
10169
  return { type: "json", value };
10179
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
+ }
10180
10178
  function defineTool(toolOptions) {
10181
10179
  const parameters = (0, import_zod.toJSONSchema)(toolOptions.input, {
10182
10180
  target: "draft-07",
10183
10181
  io: "input"
10184
10182
  });
10185
10183
  const modelParameters = withTopLevelObjectTypeForObjectUnions(parameters);
10186
- 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 = {
10187
10211
  name: toolOptions.name,
10188
10212
  description: toolOptions.description,
10189
10213
  ...toolOptions.displayResult ? { displayResult: toolOptions.displayResult } : {},
@@ -10193,28 +10217,17 @@ function defineTool(toolOptions) {
10193
10217
  parameters: modelParameters,
10194
10218
  strict: false
10195
10219
  },
10196
- executeRaw: (rawArgsJson, ctx) => {
10197
- let rawArgs;
10198
- try {
10199
- rawArgs = JSON.parse(rawArgsJson);
10200
- } catch (error) {
10201
- throw new Error(
10202
- `Invalid tool arguments JSON for ${toolOptions.name}: ${String(error)}`
10203
- );
10204
- }
10205
- const parsed = toolOptions.input.safeParse(rawArgs);
10206
- if (!parsed.success) {
10207
- throw new Error(
10208
- `Tool input validation failed for ${toolOptions.name}: ${parsed.error.message}`
10209
- );
10210
- }
10211
- const result = toolOptions.execute(parsed.data, ctx);
10212
- if (result instanceof Promise) {
10213
- return result.then((result2) => toToolResult(result2));
10214
- }
10215
- return Promise.resolve(toToolResult(result));
10216
- }
10220
+ validateRaw: (raw) => {
10221
+ parse(raw);
10222
+ },
10223
+ executeRaw: (raw, context) => execute(parse(raw), context)
10217
10224
  };
10225
+ preparations.set(tool, {
10226
+ executeRaw: tool.executeRaw,
10227
+ validateRaw: tool.validateRaw,
10228
+ prepare
10229
+ });
10230
+ return tool;
10218
10231
  }
10219
10232
  // Annotate the CommonJS export names for ESM import in node:
10220
10233
  0 && (module.exports = {
@@ -10259,11 +10272,13 @@ function defineTool(toolOptions) {
10259
10272
  isProviderFailureError,
10260
10273
  isUsableModelSpec,
10261
10274
  listModels,
10275
+ prepareToolInvocation,
10262
10276
  registerModels,
10263
10277
  resolveDeepSeekEffort,
10264
10278
  resolveModel,
10265
10279
  resolveProviderModelId,
10266
10280
  stringifyContent,
10267
10281
  stringifyContentParts,
10268
- supportsFastMode
10282
+ supportsFastMode,
10283
+ toolPermissionClarificationFields
10269
10284
  });
package/dist/index.d.ts CHANGED
@@ -446,6 +446,8 @@ type Tool = {
446
446
  description: string;
447
447
  displayResult?: string;
448
448
  definition: ToolDefinition;
449
+ /** Validate arguments without executing the tool. */
450
+ validateRaw?: (rawArgsJson: string) => void;
449
451
  executeRaw: (rawArgsJson: string, ctx: ToolContext) => Promise<ToolResult>;
450
452
  };
451
453
  type ToolExecution = {
@@ -457,8 +459,13 @@ type ToolExecution = {
457
459
  type ToolPermissionDecision = {
458
460
  decision: "allow" | "deny";
459
461
  reason?: string;
462
+ clarification?: {
463
+ missing: ToolPermissionClarificationField | "unspecified";
464
+ };
460
465
  stop_turn?: boolean;
461
466
  };
467
+ declare const toolPermissionClarificationFields: readonly ["target", "destination", "scope", "effect", "authorization"];
468
+ type ToolPermissionClarificationField = (typeof toolPermissionClarificationFields)[number];
462
469
  /** Carries a permission decision made inside a tool's shared execution gate. */
463
470
  declare class ToolPermissionDenied extends Error {
464
471
  readonly decision: ToolPermissionDecision;
@@ -612,6 +619,18 @@ type RunErrorRecord = {
612
619
  };
613
620
  meta?: Record<string, unknown>;
614
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
+ };
615
634
  type RunEndRecord = {
616
635
  type: "run.end";
617
636
  run_id: string;
@@ -620,7 +639,7 @@ type RunEndRecord = {
620
639
  final?: string;
621
640
  meta?: Record<string, unknown>;
622
641
  };
623
- 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;
624
643
  type SessionStore = {
625
644
  filePath?: string;
626
645
  append: (record: SessionRecord) => Promise<void> | void;
@@ -653,11 +672,41 @@ type ConversationSearchResult = {
653
672
  matches: ConversationMessage[];
654
673
  next_cursor?: string;
655
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
+ };
656
705
  type SessionStateStore = {
657
706
  load: (sessionId: string) => Promise<SessionState | null>;
658
707
  save: (state: SessionState) => Promise<void>;
659
708
  list: () => Promise<SessionStateSummary[]>;
660
- appendMessages?: (sessionId: string, messages: BaseMessage[]) => Promise<void>;
709
+ appendMessages?: (sessionId: string, messages: BaseMessage[], provenance?: readonly (ConversationApprovalProvenance | undefined)[]) => Promise<void>;
661
710
  searchMessages?: (sessionId: string, options: {
662
711
  query: string;
663
712
  cursor?: string;
@@ -668,6 +717,11 @@ type SessionStateStore = {
668
717
  offset?: number;
669
718
  limit?: number;
670
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>;
671
725
  updateMetadata?: (sessionId: string, patch: {
672
726
  pinned?: boolean;
673
727
  archived?: boolean;
@@ -680,7 +734,7 @@ type AgentSession = {
680
734
  on_error?: (error: unknown, record: SessionRecord) => void;
681
735
  append: (record: SessionRecord) => void;
682
736
  /** Await durable originals before admitting messages or discarding context. */
683
- recordMessages?: (messages: BaseMessage[]) => Promise<void>;
737
+ recordMessages?: (messages: BaseMessage[], origins?: readonly (ConversationInputOrigin | undefined)[]) => Promise<void>;
684
738
  };
685
739
 
686
740
  type PolledMessage = string | {
@@ -790,8 +844,12 @@ type StoragePaths = {
790
844
  root: string;
791
845
  configDir: string;
792
846
  configFile: string;
847
+ credentialsDir: string;
793
848
  authFile: string;
794
849
  mcpAuthFile: string;
850
+ legacyAuthFile: string;
851
+ legacyMcpAuthFile: string;
852
+ authStateFile: string;
795
853
  projectsFile: string;
796
854
  cacheDir: string;
797
855
  toolOutputCacheDir: string;
@@ -1203,7 +1261,7 @@ declare const DEEPSEEK_MODELS: ({
1203
1261
  /** DeepSeek documents medium/xhigh as aliases of high. */
1204
1262
  declare const resolveDeepSeekEffort: (requested: ModelReasoningLevel) => "low" | "high" | "max";
1205
1263
 
1206
- declare const GOOGLE_DEFAULT_MODEL = "gemini-3.8-flash";
1264
+ declare const GOOGLE_DEFAULT_MODEL = "gemini-4-hydrogen";
1207
1265
  declare const GOOGLE_MODELS: ModelSpec[];
1208
1266
 
1209
1267
  declare const MOONSHOT_DEFAULT_MODEL = "kimi-k3";
@@ -1226,6 +1284,12 @@ declare const DEFAULT_MODEL_REGISTRY: ModelRegistry;
1226
1284
 
1227
1285
  declare const getDefaultSystemPromptPath: () => string;
1228
1286
 
1287
+ type PreparedToolInvocation = {
1288
+ input: unknown;
1289
+ execute: (context: ToolContext) => Promise<ToolResult>;
1290
+ };
1291
+ /** Bind validated input to an exact defineTool executor before runtime admission. */
1292
+ declare function prepareToolInvocation(tool: Tool, raw: string): PreparedToolInvocation | undefined;
1229
1293
  declare function defineTool<TInput, TResult extends ToolReturn>(toolOptions: DefineToolOptions<TInput, TResult>): Tool;
1230
1294
 
1231
1295
  declare class TaskComplete extends Error {
@@ -1233,4 +1297,4 @@ declare class TaskComplete extends Error {
1233
1297
  constructor(finalMessage?: string);
1234
1298
  }
1235
1299
 
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 };
1300
+ 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",
@@ -2820,10 +2801,10 @@ var Agent = class {
2820
2801
  getHistoryMessages() {
2821
2802
  return this.history.getViewMessages();
2822
2803
  }
2823
- async recordOriginals(session, messages) {
2804
+ async recordOriginals(session, messages, origins) {
2824
2805
  if (!session?.recordMessages || messages.length === 0) return;
2825
2806
  try {
2826
- await session.recordMessages(messages);
2807
+ await session.recordMessages(messages, origins);
2827
2808
  } catch (cause) {
2828
2809
  throw new ConversationPersistenceError(cause);
2829
2810
  }
@@ -3076,7 +3057,11 @@ var Agent = class {
3076
3057
  boundary: { index: this.history.getViewMessages().length }
3077
3058
  } : void 0;
3078
3059
  if (!options.runtimeInitiated) {
3079
- await this.recordOriginals(session, [{ role: "user", content: message }]);
3060
+ await this.recordOriginals(
3061
+ session,
3062
+ [{ role: "user", content: message }],
3063
+ [{ source: "user_input" }]
3064
+ );
3080
3065
  this.history.enqueueUserMessage(message);
3081
3066
  }
3082
3067
  const withRunContext = (input) => {
@@ -3107,7 +3092,10 @@ var Agent = class {
3107
3092
  if (messages.length > 0) {
3108
3093
  await this.recordOriginals(
3109
3094
  session,
3110
- 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
+ )
3111
3099
  );
3112
3100
  throwIfAborted(signal);
3113
3101
  }
@@ -3468,7 +3456,8 @@ var Agent = class {
3468
3456
  ${assistantTexts.join("\n").trim()}`;
3469
3457
  return finalResponse;
3470
3458
  } catch (error) {
3471
- if (error instanceof ConversationPersistenceError || observer) throw error;
3459
+ if (error instanceof ConversationPersistenceError || observer)
3460
+ throw error;
3472
3461
  if (signal?.aborted) {
3473
3462
  throw createAbortError2();
3474
3463
  }
@@ -10094,13 +10083,46 @@ function toToolResult(value) {
10094
10083
  return { type: "parts", parts: value };
10095
10084
  return { type: "json", value };
10096
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
+ }
10097
10093
  function defineTool(toolOptions) {
10098
10094
  const parameters = toJSONSchema(toolOptions.input, {
10099
10095
  target: "draft-07",
10100
10096
  io: "input"
10101
10097
  });
10102
10098
  const modelParameters = withTopLevelObjectTypeForObjectUnions(parameters);
10103
- 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 = {
10104
10126
  name: toolOptions.name,
10105
10127
  description: toolOptions.description,
10106
10128
  ...toolOptions.displayResult ? { displayResult: toolOptions.displayResult } : {},
@@ -10110,28 +10132,17 @@ function defineTool(toolOptions) {
10110
10132
  parameters: modelParameters,
10111
10133
  strict: false
10112
10134
  },
10113
- executeRaw: (rawArgsJson, ctx) => {
10114
- let rawArgs;
10115
- try {
10116
- rawArgs = JSON.parse(rawArgsJson);
10117
- } catch (error) {
10118
- throw new Error(
10119
- `Invalid tool arguments JSON for ${toolOptions.name}: ${String(error)}`
10120
- );
10121
- }
10122
- const parsed = toolOptions.input.safeParse(rawArgs);
10123
- if (!parsed.success) {
10124
- throw new Error(
10125
- `Tool input validation failed for ${toolOptions.name}: ${parsed.error.message}`
10126
- );
10127
- }
10128
- const result = toolOptions.execute(parsed.data, ctx);
10129
- if (result instanceof Promise) {
10130
- return result.then((result2) => toToolResult(result2));
10131
- }
10132
- return Promise.resolve(toToolResult(result));
10133
- }
10135
+ validateRaw: (raw) => {
10136
+ parse(raw);
10137
+ },
10138
+ executeRaw: (raw, context) => execute(parse(raw), context)
10134
10139
  };
10140
+ preparations.set(tool, {
10141
+ executeRaw: tool.executeRaw,
10142
+ validateRaw: tool.validateRaw,
10143
+ prepare
10144
+ });
10145
+ return tool;
10135
10146
  }
10136
10147
  export {
10137
10148
  ANTHROPIC_DEFAULT_MODEL,
@@ -10175,11 +10186,13 @@ export {
10175
10186
  isProviderFailureError,
10176
10187
  isUsableModelSpec,
10177
10188
  listModels,
10189
+ prepareToolInvocation,
10178
10190
  registerModels,
10179
10191
  resolveDeepSeekEffort,
10180
10192
  resolveModel,
10181
10193
  resolveProviderModelId,
10182
10194
  stringifyContent,
10183
10195
  stringifyContentParts,
10184
- supportsFastMode
10196
+ supportsFastMode,
10197
+ toolPermissionClarificationFields
10185
10198
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelia/core",
3
- "version": "0.1.85",
3
+ "version": "0.1.89",
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.85",
30
- "@codelia/shared-types": "0.1.85",
29
+ "@codelia/config": "0.1.89",
30
+ "@codelia/shared-types": "0.1.89",
31
31
  "@google/genai": "2.32.0",
32
32
  "image-size": "^2.0.2",
33
33
  "json-schema": "^0.4.0",