@codelia/core 0.1.72 → 0.1.74

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
@@ -328,6 +328,9 @@ var stringifyContent = (content, options = {}) => {
328
328
  return stringifyContentParts(content, options);
329
329
  };
330
330
 
331
+ // src/agent/agent.ts
332
+ var import_node_perf_hooks = require("perf_hooks");
333
+
331
334
  // src/history/store.ts
332
335
  var MessageHistoryAdapter = class {
333
336
  messages = [];
@@ -1212,6 +1215,8 @@ var TaskComplete = class extends Error {
1212
1215
 
1213
1216
  // src/agent/agent.ts
1214
1217
  var DEFAULT_MAX_ITERATIONS = 200;
1218
+ var defaultMonotonicNowMs = () => import_node_perf_hooks.performance.now();
1219
+ var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
1215
1220
  function toolResultToContent(result) {
1216
1221
  if (result.type === "text") return result.text;
1217
1222
  if (result.type === "parts") return result.parts;
@@ -1362,6 +1367,7 @@ var Agent = class {
1362
1367
  services;
1363
1368
  modelRegistry;
1364
1369
  canExecuteTool;
1370
+ monotonicNowMs;
1365
1371
  //private readonly dependencyOverrides?: DependencyOverrides;
1366
1372
  history;
1367
1373
  usageService;
@@ -1375,6 +1381,7 @@ var Agent = class {
1375
1381
  this.toolChoice = options.toolChoice ?? void 0;
1376
1382
  this.requireDoneTool = options.requireDoneTool ?? false;
1377
1383
  this.services = options.services ?? {};
1384
+ this.monotonicNowMs = this.services.monotonicNowMs ?? defaultMonotonicNowMs;
1378
1385
  this.modelRegistry = options.modelRegistry ?? DEFAULT_MODEL_REGISTRY;
1379
1386
  this.compactionService = options.compaction === null ? null : new CompactionService(options.compaction ?? {}, {
1380
1387
  modelRegistry: this.modelRegistry
@@ -1699,7 +1706,7 @@ var Agent = class {
1699
1706
  tool_call_id: toolCall.id
1700
1707
  };
1701
1708
  yield toolCallEvent;
1702
- const startTime = Date.now();
1709
+ const monotonicStartedAt = this.monotonicNowMs();
1703
1710
  try {
1704
1711
  throwIfAborted(signal);
1705
1712
  const execution = await this.executeToolCall(
@@ -1736,7 +1743,10 @@ var Agent = class {
1736
1743
  is_error: processedMessage.is_error
1737
1744
  };
1738
1745
  yield toolResultEvent;
1739
- const durationMs = Date.now() - startTime;
1746
+ const durationMs = elapsedMilliseconds(
1747
+ monotonicStartedAt,
1748
+ this.monotonicNowMs
1749
+ );
1740
1750
  const stepCompleteEvent = {
1741
1751
  type: "step_complete",
1742
1752
  step_id: toolCall.id,
@@ -1791,7 +1801,10 @@ var Agent = class {
1791
1801
  is_error: true
1792
1802
  };
1793
1803
  yield toolResultEvent;
1794
- const durationMs = Date.now() - startTime;
1804
+ const durationMs = elapsedMilliseconds(
1805
+ monotonicStartedAt,
1806
+ this.monotonicNowMs
1807
+ );
1795
1808
  const stepCompleteEvent = {
1796
1809
  type: "step_complete",
1797
1810
  step_id: toolCall.id,
@@ -2569,7 +2582,10 @@ var ChatAnthropic = class {
2569
2582
  const response = this.fastMode ? await this.client.beta.messages.create(
2570
2583
  request,
2571
2584
  requestOptions
2572
- ) : await this.client.messages.create(request, requestOptions);
2585
+ ) : await this.client.messages.create(
2586
+ request,
2587
+ requestOptions
2588
+ );
2573
2589
  await this.debugResponseIfEnabled(response, debugSeq);
2574
2590
  return toChatInvokeCompletion(response, {
2575
2591
  reasoning_requested: this.reasoningLevelMeta.requested,
@@ -3252,6 +3268,9 @@ var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent)
3252
3268
  return stream.finalResponse();
3253
3269
  };
3254
3270
 
3271
+ // src/llm/openai/responses-reasoning.ts
3272
+ var toSdkReasoningEffort = (effort) => effort;
3273
+
3255
3274
  // src/llm/openai/serializer.ts
3256
3275
  var toOpenAiOtherPart = (kind, payload) => ({
3257
3276
  type: "other",
@@ -4478,7 +4497,10 @@ var ChatOpenAI = class {
4478
4497
  }
4479
4498
  request.include = Array.from(includeSet);
4480
4499
  const effort = reasoningEffort ?? this.defaultReasoningEffort;
4481
- request.reasoning = { effort, summary: DEFAULT_REASONING_SUMMARY };
4500
+ request.reasoning = {
4501
+ effort: toSdkReasoningEffort(effort),
4502
+ summary: DEFAULT_REASONING_SUMMARY
4503
+ };
4482
4504
  const verbosity = textVerbosity ?? this.defaultTextVerbosity;
4483
4505
  if (verbosity) {
4484
4506
  request.text = {
@@ -5479,7 +5501,10 @@ var ChatOpenRouter = class {
5479
5501
  }
5480
5502
  request.include = Array.from(includeSet);
5481
5503
  const effort = reasoningEffort ?? this.defaultReasoningEffort;
5482
- request.reasoning = { effort, summary: DEFAULT_REASONING_SUMMARY2 };
5504
+ request.reasoning = {
5505
+ effort: toSdkReasoningEffort(effort),
5506
+ summary: DEFAULT_REASONING_SUMMARY2
5507
+ };
5483
5508
  const verbosity = textVerbosity ?? this.defaultTextVerbosity;
5484
5509
  if (verbosity) {
5485
5510
  request.text = {
@@ -5652,10 +5677,6 @@ function toZaiTools(tools) {
5652
5677
  parameters: tool.parameters
5653
5678
  }
5654
5679
  });
5655
- continue;
5656
- }
5657
- if (isHostedSearchToolDefinition(tool)) {
5658
- continue;
5659
5680
  }
5660
5681
  }
5661
5682
  return mapped.length ? mapped : void 0;
@@ -6152,62 +6173,103 @@ var getDefaultSystemPromptPath = () => promptPath;
6152
6173
 
6153
6174
  // src/tools/define.ts
6154
6175
  var import_zod = require("zod");
6155
- var mapSchema = (schema, transform) => {
6156
- if (!schema || typeof schema !== "object") return schema;
6157
- const next = transform({ ...schema });
6158
- if (next.properties) {
6159
- const updated = {};
6160
- for (const [key, value] of Object.entries(next.properties)) {
6161
- updated[key] = mapSchema(value, transform);
6176
+ var schemaAllowsNull = (schema) => {
6177
+ if (schema.type === "null") return true;
6178
+ if (Array.isArray(schema.type) && schema.type.includes("null")) return true;
6179
+ return [...schema.anyOf ?? [], ...schema.oneOf ?? []].some(
6180
+ (variant) => variant !== true && variant !== false && schemaAllowsNull(variant)
6181
+ );
6182
+ };
6183
+ var withOptionalNullHint = (description) => {
6184
+ const hint = "Pass null to omit this optional value and use its default behavior.";
6185
+ if (!description) return hint;
6186
+ return description.includes(hint) ? description : `${description} ${hint}`;
6187
+ };
6188
+ var nullableOptionalProperty = (schema) => {
6189
+ if (schemaAllowsNull(schema)) {
6190
+ return { ...schema, description: withOptionalNullHint(schema.description) };
6191
+ }
6192
+ const { description, ...inner } = schema;
6193
+ return {
6194
+ description: withOptionalNullHint(description),
6195
+ anyOf: [inner, { type: "null" }]
6196
+ };
6197
+ };
6198
+ var toStrictToolSchema = (schema) => {
6199
+ const originalRequired = new Set(schema.required ?? []);
6200
+ const next = { ...schema };
6201
+ if (next.type === "object") {
6202
+ next.additionalProperties ??= false;
6203
+ if (next.properties) {
6204
+ const properties = {};
6205
+ for (const [key, property] of Object.entries(next.properties)) {
6206
+ const normalized = toStrictToolSchema(property);
6207
+ properties[key] = originalRequired.has(key) ? normalized : nullableOptionalProperty(normalized);
6208
+ }
6209
+ next.properties = properties;
6210
+ const propertyKeys = Object.keys(properties);
6211
+ if (propertyKeys.length > 0) next.required = propertyKeys;
6162
6212
  }
6163
- next.properties = updated;
6164
6213
  }
6165
6214
  if (next.items) {
6166
- if (Array.isArray(next.items)) {
6167
- next.items = next.items.map(
6168
- (item) => mapSchema(item, transform)
6169
- );
6170
- } else {
6171
- next.items = mapSchema(next.items, transform);
6172
- }
6215
+ next.items = Array.isArray(next.items) ? next.items.map((item) => toStrictToolSchema(item)) : toStrictToolSchema(next.items);
6173
6216
  }
6174
6217
  if (next.anyOf) {
6175
6218
  next.anyOf = next.anyOf.map(
6176
- (item) => mapSchema(item, transform)
6219
+ (item) => item === true || item === false ? item : toStrictToolSchema(item)
6177
6220
  );
6178
6221
  }
6179
6222
  if (next.oneOf) {
6180
6223
  next.oneOf = next.oneOf.map(
6181
- (item) => mapSchema(item, transform)
6224
+ (item) => item === true || item === false ? item : toStrictToolSchema(item)
6182
6225
  );
6183
6226
  }
6184
6227
  if (next.allOf) {
6185
6228
  next.allOf = next.allOf.map(
6186
- (item) => mapSchema(item, transform)
6229
+ (item) => item === true || item === false ? item : toStrictToolSchema(item)
6187
6230
  );
6188
6231
  }
6189
6232
  if (next.not) {
6190
- next.not = mapSchema(next.not, transform);
6233
+ next.not = toStrictToolSchema(next.not);
6234
+ }
6235
+ if (next.additionalProperties && next.additionalProperties !== true) {
6236
+ next.additionalProperties = toStrictToolSchema(
6237
+ next.additionalProperties
6238
+ );
6191
6239
  }
6192
6240
  return next;
6193
6241
  };
6194
- var withNoAdditionalProperties = (schema) => mapSchema(schema, (next) => {
6195
- if (next.type === "object" && next.additionalProperties === void 0) {
6196
- next.additionalProperties = false;
6242
+ var normalizeOptionalNulls = (value, schema) => {
6243
+ if (Array.isArray(value) && schema.items && !Array.isArray(schema.items)) {
6244
+ return value.map(
6245
+ (item) => normalizeOptionalNulls(item, schema.items)
6246
+ );
6197
6247
  }
6198
- return next;
6199
- });
6200
- var withRequiredProperties = (schema) => mapSchema(schema, (next) => {
6201
- if (next.type === "object" && next.properties) {
6202
- const propertyKeys = Object.keys(next.properties);
6203
- if (propertyKeys.length > 0) {
6204
- next.required = Array.from(
6205
- /* @__PURE__ */ new Set([...next.required ?? [], ...propertyKeys])
6248
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
6249
+ const normalized = { ...value };
6250
+ if (schema.type === "object" && schema.properties) {
6251
+ const required = new Set(schema.required ?? []);
6252
+ for (const [key, property] of Object.entries(schema.properties)) {
6253
+ if (!(key in normalized)) continue;
6254
+ if (normalized[key] === null && !required.has(key)) {
6255
+ delete normalized[key];
6256
+ continue;
6257
+ }
6258
+ normalized[key] = normalizeOptionalNulls(
6259
+ normalized[key],
6260
+ property
6206
6261
  );
6207
6262
  }
6208
6263
  }
6209
- return next;
6210
- });
6264
+ for (const variant of [...schema.anyOf ?? [], ...schema.oneOf ?? []]) {
6265
+ if (variant === true || variant === false) continue;
6266
+ Object.assign(
6267
+ normalized,
6268
+ normalizeOptionalNulls(normalized, variant)
6269
+ );
6270
+ }
6271
+ return normalized;
6272
+ };
6211
6273
  var withTopLevelObjectTypeForObjectUnions = (schema) => {
6212
6274
  if (schema.type !== void 0) return schema;
6213
6275
  const variants = (Array.isArray(schema.anyOf) && schema.anyOf.length > 0 ? schema.anyOf : Array.isArray(schema.oneOf) && schema.oneOf.length > 0 ? schema.oneOf : null) ?? null;
@@ -6233,7 +6295,7 @@ function defineTool(toolOptions) {
6233
6295
  io: "input"
6234
6296
  });
6235
6297
  const strictParameters = withTopLevelObjectTypeForObjectUnions(
6236
- withRequiredProperties(withNoAdditionalProperties(parameters))
6298
+ toStrictToolSchema(parameters)
6237
6299
  );
6238
6300
  return {
6239
6301
  name: toolOptions.name,
@@ -6253,7 +6315,9 @@ function defineTool(toolOptions) {
6253
6315
  `Invalid tool arguments JSON for ${toolOptions.name}: ${String(error)}`
6254
6316
  );
6255
6317
  }
6256
- const parsed = toolOptions.input.safeParse(rawArgs);
6318
+ const parsed = toolOptions.input.safeParse(
6319
+ normalizeOptionalNulls(rawArgs, parameters)
6320
+ );
6257
6321
  if (!parsed.success) {
6258
6322
  throw new Error(
6259
6323
  `Tool input validation failed for ${toolOptions.name}: ${parsed.error.message}`
package/dist/index.d.cts CHANGED
@@ -4,7 +4,7 @@ import { Logger } from 'openai/client';
4
4
  import { AgentEvent, SessionStateSummary as SessionStateSummary$1, ModelReasoningLevel } from '@codelia/shared-types';
5
5
  export { AgentEvent, FinalResponseEvent, ReasoningEvent, StepCompleteEvent, StepStartEvent, TextEvent, ToolCallEvent, ToolResultEvent } from '@codelia/shared-types';
6
6
  import Anthropic from '@anthropic-ai/sdk';
7
- import { MessageCreateParamsNonStreaming } from '@anthropic-ai/sdk/resources/messages/messages';
7
+ import { MessageCreateParamsNonStreaming, OutputConfig } from '@anthropic-ai/sdk/resources/messages/messages';
8
8
  import OpenAI, { ClientOptions } from 'openai';
9
9
  import { ResponsesClientEvent, ResponseCreateParamsBase, ResponseTextConfig } from 'openai/resources/responses/responses';
10
10
  import { ResponsesWS } from 'openai/resources/responses/ws';
@@ -221,6 +221,7 @@ interface ModelMetadataService {
221
221
  type AgentServices = {
222
222
  modelMetadata?: ModelMetadataService;
223
223
  toolOutputCacheStore?: ToolOutputCacheStore | null;
224
+ monotonicNowMs?: () => number;
224
225
  };
225
226
 
226
227
  type ProviderName = "openai" | "anthropic" | "openrouter" | "google" | "zai";
@@ -586,6 +587,7 @@ declare class Agent {
586
587
  private readonly services;
587
588
  private readonly modelRegistry;
588
589
  private readonly canExecuteTool?;
590
+ private readonly monotonicNowMs;
589
591
  private history;
590
592
  private usageService;
591
593
  constructor(options: AgentOptions);
@@ -638,7 +640,12 @@ interface StoragePathService {
638
640
  }
639
641
 
640
642
  declare const PROVIDER_NAME$3: "anthropic";
641
- type AnthropicMessageCreateParams = MessageCreateParamsNonStreaming & {
643
+ type AnthropicOutputEffort = NonNullable<OutputConfig["effort"]> | "xhigh";
644
+ type AnthropicOutputConfig = Omit<OutputConfig, "effort"> & {
645
+ effort?: AnthropicOutputEffort | null;
646
+ };
647
+ type AnthropicMessageCreateParams = Omit<MessageCreateParamsNonStreaming, "output_config"> & {
648
+ output_config?: AnthropicOutputConfig | null;
642
649
  speed?: "standard" | "fast" | null;
643
650
  betas?: string[];
644
651
  };
@@ -674,6 +681,12 @@ declare class ChatAnthropic implements BaseChatModel<typeof PROVIDER_NAME$3, Ant
674
681
  private debugResponseIfEnabled;
675
682
  }
676
683
 
684
+ /**
685
+ * Responses API reasoning values supported by Codelia models. The generated
686
+ * OpenAI SDK type can lag newly released provider values such as `max`.
687
+ */
688
+ type ResponsesReasoningEffort = ReasoningEffort | "max";
689
+
677
690
  type OpenAiWebsocketMode = "off" | "auto" | "on";
678
691
  type OpenAiWebsocketApiVersion = "v1" | "v2";
679
692
  type OpenAiResponsesWsLike = {
@@ -689,7 +702,7 @@ type OpenAiResponsesWsLike = {
689
702
  declare const PROVIDER_NAME$2: "openai";
690
703
  type OpenAITextVerbosity = Exclude<ResponseTextConfig["verbosity"], null>;
691
704
  type OpenAIInvokeOptions = Omit<ResponseCreateParamsBase, "model" | "input" | "tools" | "tool_choice" | "stream"> & {
692
- reasoningEffort?: ReasoningEffort;
705
+ reasoningEffort?: ResponsesReasoningEffort;
693
706
  textVerbosity?: OpenAITextVerbosity;
694
707
  serviceTier?: ResponseCreateParamsBase["service_tier"];
695
708
  };
@@ -702,7 +715,7 @@ type ChatOpenAIOptions = {
702
715
  clientOptions?: ClientOptions;
703
716
  model?: string;
704
717
  providerModel?: string;
705
- reasoningEffort?: ReasoningEffort;
718
+ reasoningEffort?: ResponsesReasoningEffort;
706
719
  reasoningLevelRequested?: ModelReasoningLevel;
707
720
  reasoningLevelApplied?: ModelReasoningLevel;
708
721
  reasoningFallbackApplied?: boolean;
@@ -761,14 +774,14 @@ declare class ChatOpenAI implements BaseChatModel<typeof PROVIDER_NAME$2, OpenAI
761
774
  declare const PROVIDER_NAME$1: "openrouter";
762
775
  type OpenRouterTextVerbosity = Exclude<ResponseTextConfig["verbosity"], null>;
763
776
  type OpenRouterInvokeOptions = Omit<ResponseCreateParamsBase, "model" | "input" | "tools" | "tool_choice" | "stream"> & {
764
- reasoningEffort?: ReasoningEffort;
777
+ reasoningEffort?: ResponsesReasoningEffort;
765
778
  textVerbosity?: OpenRouterTextVerbosity;
766
779
  };
767
780
  type ChatOpenRouterOptions = {
768
781
  client?: OpenAI;
769
782
  clientOptions?: ClientOptions;
770
783
  model?: string;
771
- reasoningEffort?: ReasoningEffort;
784
+ reasoningEffort?: ResponsesReasoningEffort;
772
785
  reasoningLevelRequested?: ModelReasoningLevel;
773
786
  reasoningLevelApplied?: ModelReasoningLevel;
774
787
  reasoningFallbackApplied?: boolean;
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { Logger } from 'openai/client';
4
4
  import { AgentEvent, SessionStateSummary as SessionStateSummary$1, ModelReasoningLevel } from '@codelia/shared-types';
5
5
  export { AgentEvent, FinalResponseEvent, ReasoningEvent, StepCompleteEvent, StepStartEvent, TextEvent, ToolCallEvent, ToolResultEvent } from '@codelia/shared-types';
6
6
  import Anthropic from '@anthropic-ai/sdk';
7
- import { MessageCreateParamsNonStreaming } from '@anthropic-ai/sdk/resources/messages/messages';
7
+ import { MessageCreateParamsNonStreaming, OutputConfig } from '@anthropic-ai/sdk/resources/messages/messages';
8
8
  import OpenAI, { ClientOptions } from 'openai';
9
9
  import { ResponsesClientEvent, ResponseCreateParamsBase, ResponseTextConfig } from 'openai/resources/responses/responses';
10
10
  import { ResponsesWS } from 'openai/resources/responses/ws';
@@ -221,6 +221,7 @@ interface ModelMetadataService {
221
221
  type AgentServices = {
222
222
  modelMetadata?: ModelMetadataService;
223
223
  toolOutputCacheStore?: ToolOutputCacheStore | null;
224
+ monotonicNowMs?: () => number;
224
225
  };
225
226
 
226
227
  type ProviderName = "openai" | "anthropic" | "openrouter" | "google" | "zai";
@@ -586,6 +587,7 @@ declare class Agent {
586
587
  private readonly services;
587
588
  private readonly modelRegistry;
588
589
  private readonly canExecuteTool?;
590
+ private readonly monotonicNowMs;
589
591
  private history;
590
592
  private usageService;
591
593
  constructor(options: AgentOptions);
@@ -638,7 +640,12 @@ interface StoragePathService {
638
640
  }
639
641
 
640
642
  declare const PROVIDER_NAME$3: "anthropic";
641
- type AnthropicMessageCreateParams = MessageCreateParamsNonStreaming & {
643
+ type AnthropicOutputEffort = NonNullable<OutputConfig["effort"]> | "xhigh";
644
+ type AnthropicOutputConfig = Omit<OutputConfig, "effort"> & {
645
+ effort?: AnthropicOutputEffort | null;
646
+ };
647
+ type AnthropicMessageCreateParams = Omit<MessageCreateParamsNonStreaming, "output_config"> & {
648
+ output_config?: AnthropicOutputConfig | null;
642
649
  speed?: "standard" | "fast" | null;
643
650
  betas?: string[];
644
651
  };
@@ -674,6 +681,12 @@ declare class ChatAnthropic implements BaseChatModel<typeof PROVIDER_NAME$3, Ant
674
681
  private debugResponseIfEnabled;
675
682
  }
676
683
 
684
+ /**
685
+ * Responses API reasoning values supported by Codelia models. The generated
686
+ * OpenAI SDK type can lag newly released provider values such as `max`.
687
+ */
688
+ type ResponsesReasoningEffort = ReasoningEffort | "max";
689
+
677
690
  type OpenAiWebsocketMode = "off" | "auto" | "on";
678
691
  type OpenAiWebsocketApiVersion = "v1" | "v2";
679
692
  type OpenAiResponsesWsLike = {
@@ -689,7 +702,7 @@ type OpenAiResponsesWsLike = {
689
702
  declare const PROVIDER_NAME$2: "openai";
690
703
  type OpenAITextVerbosity = Exclude<ResponseTextConfig["verbosity"], null>;
691
704
  type OpenAIInvokeOptions = Omit<ResponseCreateParamsBase, "model" | "input" | "tools" | "tool_choice" | "stream"> & {
692
- reasoningEffort?: ReasoningEffort;
705
+ reasoningEffort?: ResponsesReasoningEffort;
693
706
  textVerbosity?: OpenAITextVerbosity;
694
707
  serviceTier?: ResponseCreateParamsBase["service_tier"];
695
708
  };
@@ -702,7 +715,7 @@ type ChatOpenAIOptions = {
702
715
  clientOptions?: ClientOptions;
703
716
  model?: string;
704
717
  providerModel?: string;
705
- reasoningEffort?: ReasoningEffort;
718
+ reasoningEffort?: ResponsesReasoningEffort;
706
719
  reasoningLevelRequested?: ModelReasoningLevel;
707
720
  reasoningLevelApplied?: ModelReasoningLevel;
708
721
  reasoningFallbackApplied?: boolean;
@@ -761,14 +774,14 @@ declare class ChatOpenAI implements BaseChatModel<typeof PROVIDER_NAME$2, OpenAI
761
774
  declare const PROVIDER_NAME$1: "openrouter";
762
775
  type OpenRouterTextVerbosity = Exclude<ResponseTextConfig["verbosity"], null>;
763
776
  type OpenRouterInvokeOptions = Omit<ResponseCreateParamsBase, "model" | "input" | "tools" | "tool_choice" | "stream"> & {
764
- reasoningEffort?: ReasoningEffort;
777
+ reasoningEffort?: ResponsesReasoningEffort;
765
778
  textVerbosity?: OpenRouterTextVerbosity;
766
779
  };
767
780
  type ChatOpenRouterOptions = {
768
781
  client?: OpenAI;
769
782
  clientOptions?: ClientOptions;
770
783
  model?: string;
771
- reasoningEffort?: ReasoningEffort;
784
+ reasoningEffort?: ResponsesReasoningEffort;
772
785
  reasoningLevelRequested?: ModelReasoningLevel;
773
786
  reasoningLevelApplied?: ModelReasoningLevel;
774
787
  reasoningFallbackApplied?: boolean;
package/dist/index.js CHANGED
@@ -264,6 +264,9 @@ var stringifyContent = (content, options = {}) => {
264
264
  return stringifyContentParts(content, options);
265
265
  };
266
266
 
267
+ // src/agent/agent.ts
268
+ import { performance } from "perf_hooks";
269
+
267
270
  // src/history/store.ts
268
271
  var MessageHistoryAdapter = class {
269
272
  messages = [];
@@ -1148,6 +1151,8 @@ var TaskComplete = class extends Error {
1148
1151
 
1149
1152
  // src/agent/agent.ts
1150
1153
  var DEFAULT_MAX_ITERATIONS = 200;
1154
+ var defaultMonotonicNowMs = () => performance.now();
1155
+ var elapsedMilliseconds = (startedAt, monotonicNowMs) => Math.max(0, Math.round(monotonicNowMs() - startedAt));
1151
1156
  function toolResultToContent(result) {
1152
1157
  if (result.type === "text") return result.text;
1153
1158
  if (result.type === "parts") return result.parts;
@@ -1298,6 +1303,7 @@ var Agent = class {
1298
1303
  services;
1299
1304
  modelRegistry;
1300
1305
  canExecuteTool;
1306
+ monotonicNowMs;
1301
1307
  //private readonly dependencyOverrides?: DependencyOverrides;
1302
1308
  history;
1303
1309
  usageService;
@@ -1311,6 +1317,7 @@ var Agent = class {
1311
1317
  this.toolChoice = options.toolChoice ?? void 0;
1312
1318
  this.requireDoneTool = options.requireDoneTool ?? false;
1313
1319
  this.services = options.services ?? {};
1320
+ this.monotonicNowMs = this.services.monotonicNowMs ?? defaultMonotonicNowMs;
1314
1321
  this.modelRegistry = options.modelRegistry ?? DEFAULT_MODEL_REGISTRY;
1315
1322
  this.compactionService = options.compaction === null ? null : new CompactionService(options.compaction ?? {}, {
1316
1323
  modelRegistry: this.modelRegistry
@@ -1635,7 +1642,7 @@ var Agent = class {
1635
1642
  tool_call_id: toolCall.id
1636
1643
  };
1637
1644
  yield toolCallEvent;
1638
- const startTime = Date.now();
1645
+ const monotonicStartedAt = this.monotonicNowMs();
1639
1646
  try {
1640
1647
  throwIfAborted(signal);
1641
1648
  const execution = await this.executeToolCall(
@@ -1672,7 +1679,10 @@ var Agent = class {
1672
1679
  is_error: processedMessage.is_error
1673
1680
  };
1674
1681
  yield toolResultEvent;
1675
- const durationMs = Date.now() - startTime;
1682
+ const durationMs = elapsedMilliseconds(
1683
+ monotonicStartedAt,
1684
+ this.monotonicNowMs
1685
+ );
1676
1686
  const stepCompleteEvent = {
1677
1687
  type: "step_complete",
1678
1688
  step_id: toolCall.id,
@@ -1727,7 +1737,10 @@ var Agent = class {
1727
1737
  is_error: true
1728
1738
  };
1729
1739
  yield toolResultEvent;
1730
- const durationMs = Date.now() - startTime;
1740
+ const durationMs = elapsedMilliseconds(
1741
+ monotonicStartedAt,
1742
+ this.monotonicNowMs
1743
+ );
1731
1744
  const stepCompleteEvent = {
1732
1745
  type: "step_complete",
1733
1746
  step_id: toolCall.id,
@@ -2505,7 +2518,10 @@ var ChatAnthropic = class {
2505
2518
  const response = this.fastMode ? await this.client.beta.messages.create(
2506
2519
  request,
2507
2520
  requestOptions
2508
- ) : await this.client.messages.create(request, requestOptions);
2521
+ ) : await this.client.messages.create(
2522
+ request,
2523
+ requestOptions
2524
+ );
2509
2525
  await this.debugResponseIfEnabled(response, debugSeq);
2510
2526
  return toChatInvokeCompletion(response, {
2511
2527
  reasoning_requested: this.reasoningLevelMeta.requested,
@@ -3188,6 +3204,9 @@ var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent)
3188
3204
  return stream.finalResponse();
3189
3205
  };
3190
3206
 
3207
+ // src/llm/openai/responses-reasoning.ts
3208
+ var toSdkReasoningEffort = (effort) => effort;
3209
+
3191
3210
  // src/llm/openai/serializer.ts
3192
3211
  var toOpenAiOtherPart = (kind, payload) => ({
3193
3212
  type: "other",
@@ -4414,7 +4433,10 @@ var ChatOpenAI = class {
4414
4433
  }
4415
4434
  request.include = Array.from(includeSet);
4416
4435
  const effort = reasoningEffort ?? this.defaultReasoningEffort;
4417
- request.reasoning = { effort, summary: DEFAULT_REASONING_SUMMARY };
4436
+ request.reasoning = {
4437
+ effort: toSdkReasoningEffort(effort),
4438
+ summary: DEFAULT_REASONING_SUMMARY
4439
+ };
4418
4440
  const verbosity = textVerbosity ?? this.defaultTextVerbosity;
4419
4441
  if (verbosity) {
4420
4442
  request.text = {
@@ -5415,7 +5437,10 @@ var ChatOpenRouter = class {
5415
5437
  }
5416
5438
  request.include = Array.from(includeSet);
5417
5439
  const effort = reasoningEffort ?? this.defaultReasoningEffort;
5418
- request.reasoning = { effort, summary: DEFAULT_REASONING_SUMMARY2 };
5440
+ request.reasoning = {
5441
+ effort: toSdkReasoningEffort(effort),
5442
+ summary: DEFAULT_REASONING_SUMMARY2
5443
+ };
5419
5444
  const verbosity = textVerbosity ?? this.defaultTextVerbosity;
5420
5445
  if (verbosity) {
5421
5446
  request.text = {
@@ -5588,10 +5613,6 @@ function toZaiTools(tools) {
5588
5613
  parameters: tool.parameters
5589
5614
  }
5590
5615
  });
5591
- continue;
5592
- }
5593
- if (isHostedSearchToolDefinition(tool)) {
5594
- continue;
5595
5616
  }
5596
5617
  }
5597
5618
  return mapped.length ? mapped : void 0;
@@ -6087,62 +6108,103 @@ var getDefaultSystemPromptPath = () => promptPath;
6087
6108
 
6088
6109
  // src/tools/define.ts
6089
6110
  import { toJSONSchema } from "zod";
6090
- var mapSchema = (schema, transform) => {
6091
- if (!schema || typeof schema !== "object") return schema;
6092
- const next = transform({ ...schema });
6093
- if (next.properties) {
6094
- const updated = {};
6095
- for (const [key, value] of Object.entries(next.properties)) {
6096
- updated[key] = mapSchema(value, transform);
6111
+ var schemaAllowsNull = (schema) => {
6112
+ if (schema.type === "null") return true;
6113
+ if (Array.isArray(schema.type) && schema.type.includes("null")) return true;
6114
+ return [...schema.anyOf ?? [], ...schema.oneOf ?? []].some(
6115
+ (variant) => variant !== true && variant !== false && schemaAllowsNull(variant)
6116
+ );
6117
+ };
6118
+ var withOptionalNullHint = (description) => {
6119
+ const hint = "Pass null to omit this optional value and use its default behavior.";
6120
+ if (!description) return hint;
6121
+ return description.includes(hint) ? description : `${description} ${hint}`;
6122
+ };
6123
+ var nullableOptionalProperty = (schema) => {
6124
+ if (schemaAllowsNull(schema)) {
6125
+ return { ...schema, description: withOptionalNullHint(schema.description) };
6126
+ }
6127
+ const { description, ...inner } = schema;
6128
+ return {
6129
+ description: withOptionalNullHint(description),
6130
+ anyOf: [inner, { type: "null" }]
6131
+ };
6132
+ };
6133
+ var toStrictToolSchema = (schema) => {
6134
+ const originalRequired = new Set(schema.required ?? []);
6135
+ const next = { ...schema };
6136
+ if (next.type === "object") {
6137
+ next.additionalProperties ??= false;
6138
+ if (next.properties) {
6139
+ const properties = {};
6140
+ for (const [key, property] of Object.entries(next.properties)) {
6141
+ const normalized = toStrictToolSchema(property);
6142
+ properties[key] = originalRequired.has(key) ? normalized : nullableOptionalProperty(normalized);
6143
+ }
6144
+ next.properties = properties;
6145
+ const propertyKeys = Object.keys(properties);
6146
+ if (propertyKeys.length > 0) next.required = propertyKeys;
6097
6147
  }
6098
- next.properties = updated;
6099
6148
  }
6100
6149
  if (next.items) {
6101
- if (Array.isArray(next.items)) {
6102
- next.items = next.items.map(
6103
- (item) => mapSchema(item, transform)
6104
- );
6105
- } else {
6106
- next.items = mapSchema(next.items, transform);
6107
- }
6150
+ next.items = Array.isArray(next.items) ? next.items.map((item) => toStrictToolSchema(item)) : toStrictToolSchema(next.items);
6108
6151
  }
6109
6152
  if (next.anyOf) {
6110
6153
  next.anyOf = next.anyOf.map(
6111
- (item) => mapSchema(item, transform)
6154
+ (item) => item === true || item === false ? item : toStrictToolSchema(item)
6112
6155
  );
6113
6156
  }
6114
6157
  if (next.oneOf) {
6115
6158
  next.oneOf = next.oneOf.map(
6116
- (item) => mapSchema(item, transform)
6159
+ (item) => item === true || item === false ? item : toStrictToolSchema(item)
6117
6160
  );
6118
6161
  }
6119
6162
  if (next.allOf) {
6120
6163
  next.allOf = next.allOf.map(
6121
- (item) => mapSchema(item, transform)
6164
+ (item) => item === true || item === false ? item : toStrictToolSchema(item)
6122
6165
  );
6123
6166
  }
6124
6167
  if (next.not) {
6125
- next.not = mapSchema(next.not, transform);
6168
+ next.not = toStrictToolSchema(next.not);
6169
+ }
6170
+ if (next.additionalProperties && next.additionalProperties !== true) {
6171
+ next.additionalProperties = toStrictToolSchema(
6172
+ next.additionalProperties
6173
+ );
6126
6174
  }
6127
6175
  return next;
6128
6176
  };
6129
- var withNoAdditionalProperties = (schema) => mapSchema(schema, (next) => {
6130
- if (next.type === "object" && next.additionalProperties === void 0) {
6131
- next.additionalProperties = false;
6177
+ var normalizeOptionalNulls = (value, schema) => {
6178
+ if (Array.isArray(value) && schema.items && !Array.isArray(schema.items)) {
6179
+ return value.map(
6180
+ (item) => normalizeOptionalNulls(item, schema.items)
6181
+ );
6132
6182
  }
6133
- return next;
6134
- });
6135
- var withRequiredProperties = (schema) => mapSchema(schema, (next) => {
6136
- if (next.type === "object" && next.properties) {
6137
- const propertyKeys = Object.keys(next.properties);
6138
- if (propertyKeys.length > 0) {
6139
- next.required = Array.from(
6140
- /* @__PURE__ */ new Set([...next.required ?? [], ...propertyKeys])
6183
+ if (!value || typeof value !== "object" || Array.isArray(value)) return value;
6184
+ const normalized = { ...value };
6185
+ if (schema.type === "object" && schema.properties) {
6186
+ const required = new Set(schema.required ?? []);
6187
+ for (const [key, property] of Object.entries(schema.properties)) {
6188
+ if (!(key in normalized)) continue;
6189
+ if (normalized[key] === null && !required.has(key)) {
6190
+ delete normalized[key];
6191
+ continue;
6192
+ }
6193
+ normalized[key] = normalizeOptionalNulls(
6194
+ normalized[key],
6195
+ property
6141
6196
  );
6142
6197
  }
6143
6198
  }
6144
- return next;
6145
- });
6199
+ for (const variant of [...schema.anyOf ?? [], ...schema.oneOf ?? []]) {
6200
+ if (variant === true || variant === false) continue;
6201
+ Object.assign(
6202
+ normalized,
6203
+ normalizeOptionalNulls(normalized, variant)
6204
+ );
6205
+ }
6206
+ return normalized;
6207
+ };
6146
6208
  var withTopLevelObjectTypeForObjectUnions = (schema) => {
6147
6209
  if (schema.type !== void 0) return schema;
6148
6210
  const variants = (Array.isArray(schema.anyOf) && schema.anyOf.length > 0 ? schema.anyOf : Array.isArray(schema.oneOf) && schema.oneOf.length > 0 ? schema.oneOf : null) ?? null;
@@ -6168,7 +6230,7 @@ function defineTool(toolOptions) {
6168
6230
  io: "input"
6169
6231
  });
6170
6232
  const strictParameters = withTopLevelObjectTypeForObjectUnions(
6171
- withRequiredProperties(withNoAdditionalProperties(parameters))
6233
+ toStrictToolSchema(parameters)
6172
6234
  );
6173
6235
  return {
6174
6236
  name: toolOptions.name,
@@ -6188,7 +6250,9 @@ function defineTool(toolOptions) {
6188
6250
  `Invalid tool arguments JSON for ${toolOptions.name}: ${String(error)}`
6189
6251
  );
6190
6252
  }
6191
- const parsed = toolOptions.input.safeParse(rawArgs);
6253
+ const parsed = toolOptions.input.safeParse(
6254
+ normalizeOptionalNulls(rawArgs, parameters)
6255
+ );
6192
6256
  if (!parsed.success) {
6193
6257
  throw new Error(
6194
6258
  `Tool input validation failed for ${toolOptions.name}: ${parsed.error.message}`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelia/core",
3
- "version": "0.1.72",
3
+ "version": "0.1.74",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",
@@ -25,8 +25,8 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "@anthropic-ai/sdk": "^0.110.0",
28
- "@codelia/config": "0.1.72",
29
- "@codelia/shared-types": "0.1.72",
28
+ "@codelia/config": "0.1.74",
29
+ "@codelia/shared-types": "0.1.74",
30
30
  "@google-cloud/vertexai": "^1.10.0",
31
31
  "@google/genai": "^1.43.0",
32
32
  "json-schema": "^0.4.0",
package/prompts/system.md CHANGED
@@ -44,7 +44,7 @@ You can use a small set of tools (names vary by UI, but conceptually):
44
44
  - `webfetch` to fetch and normalize a specific HTTP(S) URL.
45
45
  - Shell / execution:
46
46
  - `shell` to start shell commands (optionally with detached wait).
47
- - `shell_list` / `shell_status` / `shell_logs` / `shell_wait` / `shell_result` / `shell_cancel` to inspect and control retained shell tasks.
47
+ - `shell_list` / `shell_status` / `shell_logs` / `shell_wait` / `shell_result` / `shell_cancel` to inspect and control retained shell tasks, and `shell_stdin_write` for bounded writes to explicitly piped detached tasks.
48
48
  - Planning:
49
49
  - `todo_read` / `todo_new` / `todo_append` / `todo_patch` / `todo_clear` to manage task checklists when helpful.
50
50
 
@@ -81,6 +81,7 @@ Shell / execution:
81
81
  - Use timeouts, one-shot commands, or controlled detached-wait execution when appropriate.
82
82
  - `shell` starts runtime-managed child processes; use `detached_wait=true` when you want to skip the attached wait and keep working, but do not treat it as persistence across runtime exit.
83
83
  - Use `shell_list` / `shell_status` / `shell_logs` / `shell_wait` / `shell_result` / `shell_cancel` to monitor and control retained shell work instead of treating it as fire-and-forget.
84
+ - Use `stdin_mode=pipe` only with `detached_wait=true`; send bounded UTF-8 input with `shell_stdin_write`, inspect responses with `shell_logs`, and close stdin when no more input is needed.
84
85
  - Treat detached-wait shell tasks as managed child jobs, not as fire-and-forget services: check status when progress matters, wait for the final result before relying on it, and cancel tasks that are no longer useful.
85
86
  - When work depends on background processes, ports, pidfiles, or other shared machine resources, check for conflicts with leftover state from earlier attempts and avoid relying on ambiguous ownership.
86
87
  - If work must survive runtime exit or behave like a service, start it explicitly out of process using shell-native detach/daemonization for that environment (for example `nohup`, `setsid`, `disown`, a service manager, or `docker compose up -d`) and verify readiness/liveness separately.