@codelia/runtime 0.1.66 → 0.1.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.cjs +601 -455
  2. package/dist/index.js +601 -455
  3. package/package.json +9 -9
package/dist/index.cjs CHANGED
@@ -26,6 +26,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  var import_node_path20 = __toESM(require("path"), 1);
27
27
  var import_storage14 = require("@codelia/storage");
28
28
 
29
+ // src/agent-factory.ts
30
+ var import_node_fs15 = require("fs");
31
+ var import_core21 = require("@codelia/core");
32
+ var import_model_metadata2 = require("@codelia/model-metadata");
33
+ var import_shared_types2 = require("@codelia/shared-types");
34
+ var import_storage8 = require("@codelia/storage");
35
+
29
36
  // src/agents/context.ts
30
37
  var createAgentsResolverKey = (resolver) => ({
31
38
  id: "agents-resolver",
@@ -387,13 +394,6 @@ var appendInitialAgentsContext = (systemPrompt, agentsContext) => {
387
394
  ${agentsContext}`;
388
395
  };
389
396
 
390
- // src/agent-factory.ts
391
- var import_node_fs15 = require("fs");
392
- var import_core21 = require("@codelia/core");
393
- var import_model_metadata2 = require("@codelia/model-metadata");
394
- var import_shared_types2 = require("@codelia/shared-types");
395
- var import_storage8 = require("@codelia/storage");
396
-
397
397
  // src/auth/oauth-utils.ts
398
398
  var import_node_http = require("http");
399
399
  var oauth = __toESM(require("oauth4webapi"), 1);
@@ -2362,6 +2362,24 @@ var createMcpOAuthSession = async (params, options = {}) => {
2362
2362
  };
2363
2363
  };
2364
2364
 
2365
+ // src/model-fast.ts
2366
+ var import_core2 = require("@codelia/core");
2367
+ var resolveFastMode = (params) => {
2368
+ if (params.requested !== true) {
2369
+ return { enabled: false };
2370
+ }
2371
+ if (!(0, import_core2.supportsFastMode)(import_core2.DEFAULT_MODEL_REGISTRY, params.model, params.provider)) {
2372
+ return { enabled: false };
2373
+ }
2374
+ if (params.provider === "openai") {
2375
+ return { enabled: true, provider: "openai", serviceTier: "priority" };
2376
+ }
2377
+ if (params.provider === "anthropic") {
2378
+ return { enabled: true, provider: "anthropic", fastMode: true };
2379
+ }
2380
+ return { enabled: false };
2381
+ };
2382
+
2365
2383
  // src/model-reasoning.ts
2366
2384
  var REASONING_LEVEL_ORDER = [
2367
2385
  "low",
@@ -2582,24 +2600,6 @@ var resolveAnthropicMaxTokens = ({
2582
2600
  return normalizedBudget + ANTHROPIC_MAX_TOKENS_FALLBACK_HEADROOM;
2583
2601
  };
2584
2602
 
2585
- // src/model-fast.ts
2586
- var import_core2 = require("@codelia/core");
2587
- var resolveFastMode = (params) => {
2588
- if (params.requested !== true) {
2589
- return { enabled: false };
2590
- }
2591
- if (!(0, import_core2.supportsFastMode)(import_core2.DEFAULT_MODEL_REGISTRY, params.model, params.provider)) {
2592
- return { enabled: false };
2593
- }
2594
- if (params.provider === "openai") {
2595
- return { enabled: true, provider: "openai", serviceTier: "priority" };
2596
- }
2597
- if (params.provider === "anthropic") {
2598
- return { enabled: true, provider: "anthropic", fastMode: true };
2599
- }
2600
- return { enabled: false };
2601
- };
2602
-
2603
2603
  // src/model-registry.ts
2604
2604
  var import_core3 = require("@codelia/core");
2605
2605
  var import_model_metadata = require("@codelia/model-metadata");
@@ -9347,6 +9347,12 @@ var createAgentFactory = (state, options = {}) => {
9347
9347
  },
9348
9348
  services: { toolOutputCacheStore },
9349
9349
  canExecuteTool: async (call, rawArgs, toolCtx) => {
9350
+ if (state.autoApprovedClientToolNames.has(call.function.name)) {
9351
+ (0, import_logger.debugLog)(
9352
+ `permission.evaluate tool=${call.function.name} decision=allow reason=client-tool-auto-approved`
9353
+ );
9354
+ return { decision: "allow" };
9355
+ }
9350
9356
  const decision = permissionService.evaluate(
9351
9357
  call.function.name,
9352
9358
  rawArgs
@@ -11634,356 +11640,73 @@ var createModelHandlers = ({
11634
11640
  return { handleModelList, handleModelSet };
11635
11641
  };
11636
11642
 
11637
- // src/rpc/run.ts
11638
- var import_protocol5 = require("@codelia/protocol");
11639
-
11640
- // src/rpc/run-debug.ts
11641
- var import_core23 = require("@codelia/core");
11642
- var DEBUG_MAX_CONTENT_CHARS = 2e3;
11643
- var DEBUG_MAX_LOG_CHARS = 2e4;
11644
- var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
11645
- var DEBUG_MAX_EVENT_ARGS_CHARS = 2e3;
11646
- var DEBUG_ERROR_MESSAGE_MAX_CHARS = 2e3;
11647
- var DEBUG_ERROR_STACK_MAX_CHARS = 8e3;
11648
- var DEBUG_ERROR_CHAIN_MAX_CHARS = 4e3;
11649
- var DEBUG_ERROR_EXTRAS_MAX_CHARS = 4e3;
11650
- var DEBUG_PROVIDER_META_STRING_MAX_CHARS = 80;
11651
- var truncateText2 = (value, maxChars) => {
11652
- if (value.length <= maxChars) return value;
11653
- return `${value.slice(0, maxChars)}...[truncated]`;
11643
+ // src/rpc/resume-context.ts
11644
+ var import_node_fs17 = require("fs");
11645
+ var import_node_path16 = __toESM(require("path"), 1);
11646
+ var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
11647
+ var RESUME_CONTEXT_SCHEMA_VERSION = 1;
11648
+ var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
11649
+ var MAX_RESUME_DETAIL_LINES = 3;
11650
+ var normalizePath2 = (value) => {
11651
+ if (typeof value !== "string") return void 0;
11652
+ const trimmed = value.trim();
11653
+ if (!trimmed) return void 0;
11654
+ return import_node_path16.default.resolve(trimmed);
11654
11655
  };
11655
- var stringifyUnknown = (value) => {
11656
- try {
11657
- return JSON.stringify(value);
11658
- } catch {
11659
- return String(value);
11656
+ var normalizeMtime3 = (value) => {
11657
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
11658
+ return void 0;
11660
11659
  }
11660
+ return Math.trunc(value);
11661
11661
  };
11662
- var contentToDebugText = (content, maxChars) => {
11663
- const text = (0, import_core23.stringifyContent)(content, {
11664
- mode: "log",
11665
- joiner: "\n",
11666
- includeOtherPayload: true
11667
- });
11668
- return truncateText2(text, maxChars);
11669
- };
11670
- var buildCompactionSnapshotLog = (messages) => {
11671
- const payload = messages.map((message, index) => {
11672
- if (message.role === "assistant") {
11673
- return {
11674
- index,
11675
- role: message.role,
11676
- content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS),
11677
- tool_calls: (message.tool_calls ?? []).map((call) => ({
11678
- id: call.id,
11679
- name: call.function.name
11680
- }))
11681
- };
11682
- }
11683
- if (message.role === "tool") {
11684
- return {
11685
- index,
11686
- role: message.role,
11687
- tool_name: message.tool_name,
11688
- tool_call_id: message.tool_call_id,
11689
- is_error: message.is_error ?? false,
11690
- content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS)
11691
- };
11692
- }
11693
- if (message.role === "reasoning") {
11694
- return {
11695
- index,
11696
- role: message.role,
11697
- content: truncateText2(message.content ?? "", DEBUG_MAX_CONTENT_CHARS)
11698
- };
11699
- }
11700
- return {
11701
- index,
11702
- role: message.role,
11703
- content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS)
11704
- };
11705
- });
11706
- return truncateText2(stringifyUnknown(payload), DEBUG_MAX_LOG_CHARS);
11662
+ var normalizeText = (value) => {
11663
+ if (typeof value !== "string") return void 0;
11664
+ const trimmed = value.trim();
11665
+ return trimmed.length > 0 ? trimmed : void 0;
11707
11666
  };
11708
- var logCompactionSnapshot = (log2, runId, runtimeAgent, compacted) => {
11709
- if (!(0, import_logger.isDebugEnabled)()) return;
11710
- const messages = runtimeAgent.getHistoryMessages();
11711
- const snapshot = buildCompactionSnapshotLog(messages);
11712
- log2(
11713
- `compaction context snapshot run_id=${runId} compacted=${String(compacted)} messages=${messages.length} history=${snapshot}`
11714
- );
11667
+ var normalizeApprovalMode = (value) => {
11668
+ if (value === "minimal" || value === "trusted" || value === "full-access") {
11669
+ return value;
11670
+ }
11671
+ return void 0;
11715
11672
  };
11716
- var isTrackedRunEvent = (eventType) => eventType === "tool_call" || eventType === "tool_result" || eventType === "step_start" || eventType === "step_complete" || eventType === "final";
11717
- var summarizeRunEvent = (event) => {
11718
- switch (event.type) {
11719
- case "tool_call": {
11720
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
11721
- const toolCallId = typeof event.tool_call_id === "string" ? event.tool_call_id : "unknown";
11722
- const rawArgs = typeof event.raw_args === "string" ? event.raw_args : stringifyUnknown(event.args);
11723
- const rawArgsSnippet = truncateText2(rawArgs, DEBUG_MAX_EVENT_ARGS_CHARS);
11724
- return `type=tool_call tool=${tool} tool_call_id=${toolCallId} raw_args=${stringifyUnknown(rawArgsSnippet)}`;
11725
- }
11726
- case "tool_result": {
11727
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
11728
- const toolCallId = typeof event.tool_call_id === "string" ? event.tool_call_id : "unknown";
11729
- const isError = event.is_error === true;
11730
- const result = typeof event.result === "string" ? truncateText2(event.result, DEBUG_MAX_EVENT_RESULT_CHARS) : truncateText2(
11731
- stringifyUnknown(event.result),
11732
- DEBUG_MAX_EVENT_RESULT_CHARS
11733
- );
11734
- return `type=tool_result tool=${tool} tool_call_id=${toolCallId} is_error=${String(isError)} result=${stringifyUnknown(result)}`;
11735
- }
11736
- case "step_start": {
11737
- const stepId = typeof event.step_id === "string" ? event.step_id : "unknown";
11738
- const title = typeof event.title === "string" ? event.title : "unknown";
11739
- return `type=step_start step_id=${stepId} title=${title}`;
11740
- }
11741
- case "step_complete": {
11742
- const stepId = typeof event.step_id === "string" ? event.step_id : "unknown";
11743
- const status = typeof event.status === "string" ? event.status : "unknown";
11744
- const durationMs = typeof event.duration_ms === "number" ? event.duration_ms : -1;
11745
- return `type=step_complete step_id=${stepId} status=${status} duration_ms=${durationMs}`;
11746
- }
11747
- case "final": {
11748
- const content = typeof event.content === "string" ? event.content : "";
11749
- return `type=final content_chars=${content.length}`;
11750
- }
11751
- default:
11752
- return `type=${event.type}`;
11673
+ var normalizeTrackedFiles = (value) => {
11674
+ if (!Array.isArray(value)) return [];
11675
+ const seen = /* @__PURE__ */ new Set();
11676
+ const files = [];
11677
+ for (const entry of value) {
11678
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11679
+ const record = entry;
11680
+ const filePath = normalizePath2(record.path);
11681
+ const mtime = normalizeMtime3(record.mtime_ms);
11682
+ if (!filePath || mtime === void 0 || seen.has(filePath)) continue;
11683
+ seen.add(filePath);
11684
+ files.push({ path: filePath, mtime_ms: mtime });
11753
11685
  }
11686
+ files.sort((left, right) => left.path.localeCompare(right.path));
11687
+ return files;
11754
11688
  };
11755
- var logRunDebug = (log2, runId, message) => {
11756
- if (!(0, import_logger.isDebugEnabled)()) return;
11757
- log2(`run debug run_id=${runId} ${message}`);
11689
+ var trimDetails = (lines) => {
11690
+ if (lines.length <= MAX_RESUME_DETAIL_LINES) {
11691
+ return lines;
11692
+ }
11693
+ const remaining = lines.length - MAX_RESUME_DETAIL_LINES;
11694
+ return [
11695
+ ...lines.slice(0, MAX_RESUME_DETAIL_LINES),
11696
+ `... and ${remaining} more change(s)`
11697
+ ];
11758
11698
  };
11759
- var normalizeToolCallHistory = (messages) => {
11760
- const assistantCallIds = /* @__PURE__ */ new Set();
11761
- const toolOutputCallIds = /* @__PURE__ */ new Set();
11762
- for (const message of messages) {
11763
- if (message.role === "assistant") {
11764
- for (const call of message.tool_calls ?? []) {
11765
- assistantCallIds.add(call.id);
11766
- }
11767
- continue;
11768
- }
11769
- if (message.role === "tool") {
11770
- toolOutputCallIds.add(message.tool_call_id);
11771
- }
11699
+ var contentToString = (content) => {
11700
+ if (typeof content === "string") {
11701
+ return content;
11772
11702
  }
11773
- if (assistantCallIds.size === 0 && toolOutputCallIds.size === 0) {
11774
- return messages;
11703
+ if (!Array.isArray(content)) {
11704
+ return "";
11775
11705
  }
11776
- const validCallIds = /* @__PURE__ */ new Set();
11777
- for (const callId of assistantCallIds) {
11778
- if (toolOutputCallIds.has(callId)) {
11779
- validCallIds.add(callId);
11780
- }
11781
- }
11782
- if (validCallIds.size === assistantCallIds.size && validCallIds.size === toolOutputCallIds.size) {
11783
- return messages;
11784
- }
11785
- let changed = false;
11786
- const normalized = [];
11787
- for (const message of messages) {
11788
- if (message.role === "assistant") {
11789
- const calls = message.tool_calls ?? [];
11790
- if (calls.length > 0) {
11791
- const filteredCalls = calls.filter((call) => validCallIds.has(call.id));
11792
- if (filteredCalls.length !== calls.length) {
11793
- changed = true;
11794
- if (filteredCalls.length === 0) {
11795
- const next = { ...message };
11796
- delete next.tool_calls;
11797
- normalized.push(next);
11798
- } else {
11799
- normalized.push({ ...message, tool_calls: filteredCalls });
11800
- }
11801
- continue;
11802
- }
11803
- }
11804
- normalized.push(message);
11805
- continue;
11806
- }
11807
- if (message.role === "tool" && !validCallIds.has(message.tool_call_id)) {
11808
- changed = true;
11809
- continue;
11810
- }
11811
- normalized.push(message);
11812
- }
11813
- return changed ? normalized : messages;
11814
- };
11815
- var formatErrorForDebugLog = (error) => {
11816
- const parts = [];
11817
- parts.push(`name=${error.name}`);
11818
- parts.push(
11819
- `message=${truncateText2(error.message, DEBUG_ERROR_MESSAGE_MAX_CHARS)}`
11820
- );
11821
- if (error.stack) {
11822
- parts.push(
11823
- `stack=${truncateText2(error.stack, DEBUG_ERROR_STACK_MAX_CHARS)}`
11824
- );
11825
- }
11826
- const causeChain = [];
11827
- let depth = 0;
11828
- let current = error.cause;
11829
- const seen = /* @__PURE__ */ new Set();
11830
- while (current !== void 0 && current !== null && depth < 4) {
11831
- if (seen.has(current)) {
11832
- causeChain.push("[circular]");
11833
- break;
11834
- }
11835
- seen.add(current);
11836
- if (current instanceof Error) {
11837
- causeChain.push(`${current.name}: ${current.message}`);
11838
- current = current.cause;
11839
- depth += 1;
11840
- continue;
11841
- }
11842
- causeChain.push(stringifyUnknown(current));
11843
- break;
11844
- }
11845
- if (causeChain.length > 0) {
11846
- parts.push(
11847
- `cause_chain=${truncateText2(causeChain.join(" <- "), DEBUG_ERROR_CHAIN_MAX_CHARS)}`
11848
- );
11849
- }
11850
- const extras = Object.entries(
11851
- error
11852
- ).filter(([key]) => key !== "name" && key !== "message" && key !== "stack");
11853
- if (extras.length > 0) {
11854
- parts.push(
11855
- `extras=${truncateText2(
11856
- stringifyUnknown(Object.fromEntries(extras)),
11857
- DEBUG_ERROR_EXTRAS_MAX_CHARS
11858
- )}`
11859
- );
11860
- }
11861
- return parts.join(" ");
11862
- };
11863
- var summarizeProviderMeta = (value) => {
11864
- if (value === null || value === void 0) {
11865
- return null;
11866
- }
11867
- if (typeof value === "string") {
11868
- return value.length > DEBUG_PROVIDER_META_STRING_MAX_CHARS ? `${value.slice(0, DEBUG_PROVIDER_META_STRING_MAX_CHARS - 3)}...` : value;
11869
- }
11870
- if (Array.isArray(value)) {
11871
- return `array(len=${value.length})`;
11872
- }
11873
- if (typeof value === "object") {
11874
- const obj = value;
11875
- const details = [];
11876
- if (typeof obj.transport === "string") {
11877
- details.push(`transport=${obj.transport}`);
11878
- }
11879
- if (typeof obj.websocket_mode === "string") {
11880
- details.push(`websocket_mode=${obj.websocket_mode}`);
11881
- }
11882
- if (typeof obj.response_id === "string") {
11883
- details.push(`response_id=${obj.response_id}`);
11884
- }
11885
- if (typeof obj.chain_reset === "boolean") {
11886
- details.push(`chain_reset=${obj.chain_reset ? "true" : "false"}`);
11887
- }
11888
- if (typeof obj.fallback_used === "boolean") {
11889
- details.push(`fallback_used=${obj.fallback_used ? "true" : "false"}`);
11890
- }
11891
- if (typeof obj.ws_input_mode === "string") {
11892
- details.push(`ws_input_mode=${obj.ws_input_mode}`);
11893
- }
11894
- if (typeof obj.reasoning_requested === "string") {
11895
- details.push(`reasoning_requested=${obj.reasoning_requested}`);
11896
- }
11897
- if (typeof obj.reasoning_applied === "string") {
11898
- details.push(`reasoning_applied=${obj.reasoning_applied}`);
11899
- }
11900
- if (typeof obj.reasoning_fallback === "boolean") {
11901
- details.push(
11902
- `reasoning_fallback=${obj.reasoning_fallback ? "true" : "false"}`
11903
- );
11904
- }
11905
- if (typeof obj.reasoning_budget_preset === "string") {
11906
- details.push(`reasoning_budget_preset=${obj.reasoning_budget_preset}`);
11907
- }
11908
- if (details.length > 0) {
11909
- return details.join(" ");
11910
- }
11911
- const keys = Object.keys(obj);
11912
- if (keys.length === 0) return "object";
11913
- const shown = keys.slice(0, 4).join(",");
11914
- return keys.length > 4 ? `object(keys=${shown},...)` : `object(keys=${shown})`;
11915
- }
11916
- return typeof value;
11917
- };
11918
- var isAbortLikeError = (error) => error.name === "AbortError" || error.name === "APIUserAbortError" || error.name === "AbortSignal" || /aborted|abort/i.test(error.message);
11919
-
11920
- // src/rpc/resume-context.ts
11921
- var import_node_fs17 = require("fs");
11922
- var import_node_path16 = __toESM(require("path"), 1);
11923
- var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
11924
- var RESUME_CONTEXT_SCHEMA_VERSION = 1;
11925
- var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
11926
- var MAX_RESUME_DETAIL_LINES = 3;
11927
- var normalizePath2 = (value) => {
11928
- if (typeof value !== "string") return void 0;
11929
- const trimmed = value.trim();
11930
- if (!trimmed) return void 0;
11931
- return import_node_path16.default.resolve(trimmed);
11932
- };
11933
- var normalizeMtime3 = (value) => {
11934
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
11935
- return void 0;
11936
- }
11937
- return Math.trunc(value);
11938
- };
11939
- var normalizeText = (value) => {
11940
- if (typeof value !== "string") return void 0;
11941
- const trimmed = value.trim();
11942
- return trimmed.length > 0 ? trimmed : void 0;
11943
- };
11944
- var normalizeApprovalMode = (value) => {
11945
- if (value === "minimal" || value === "trusted" || value === "full-access") {
11946
- return value;
11947
- }
11948
- return void 0;
11949
- };
11950
- var normalizeTrackedFiles = (value) => {
11951
- if (!Array.isArray(value)) return [];
11952
- const seen = /* @__PURE__ */ new Set();
11953
- const files = [];
11954
- for (const entry of value) {
11955
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11956
- const record = entry;
11957
- const filePath = normalizePath2(record.path);
11958
- const mtime = normalizeMtime3(record.mtime_ms);
11959
- if (!filePath || mtime === void 0 || seen.has(filePath)) continue;
11960
- seen.add(filePath);
11961
- files.push({ path: filePath, mtime_ms: mtime });
11962
- }
11963
- files.sort((left, right) => left.path.localeCompare(right.path));
11964
- return files;
11965
- };
11966
- var trimDetails = (lines) => {
11967
- if (lines.length <= MAX_RESUME_DETAIL_LINES) {
11968
- return lines;
11969
- }
11970
- const remaining = lines.length - MAX_RESUME_DETAIL_LINES;
11971
- return [
11972
- ...lines.slice(0, MAX_RESUME_DETAIL_LINES),
11973
- `... and ${remaining} more change(s)`
11974
- ];
11975
- };
11976
- var contentToString = (content) => {
11977
- if (typeof content === "string") {
11978
- return content;
11979
- }
11980
- if (!Array.isArray(content)) {
11981
- return "";
11982
- }
11983
- return content.map((part) => {
11984
- if (!part || typeof part !== "object") return "";
11985
- if ("type" in part && part.type === "text" && typeof part.text === "string") {
11986
- return part.text;
11706
+ return content.map((part) => {
11707
+ if (!part || typeof part !== "object") return "";
11708
+ if ("type" in part && part.type === "text" && typeof part.text === "string") {
11709
+ return part.text;
11987
11710
  }
11988
11711
  return "";
11989
11712
  }).join("");
@@ -12182,112 +11905,507 @@ var buildResumeDiff = async (meta, state, options = {}) => {
12182
11905
  if (currentWorkspaceRoot) {
12183
11906
  contextLines.push(`Current workspace root: ${currentWorkspaceRoot}`);
12184
11907
  }
12185
- if (currentWorkingDir) {
12186
- contextLines.push(`Current working directory: ${currentWorkingDir}`);
11908
+ if (currentWorkingDir) {
11909
+ contextLines.push(`Current working directory: ${currentWorkingDir}`);
11910
+ }
11911
+ if (currentSandboxRoot) {
11912
+ contextLines.push(`Current sandbox root: ${currentSandboxRoot}`);
11913
+ }
11914
+ if (currentApprovalMode) {
11915
+ contextLines.push(`Current approval mode: ${currentApprovalMode}`);
11916
+ }
11917
+ if (currentModelProvider || currentModelName) {
11918
+ contextLines.push(
11919
+ `Current model: ${currentModelProvider ?? "(unknown provider)"}/${currentModelName ?? "(unknown model)"}`
11920
+ );
11921
+ }
11922
+ const detailLines = [];
11923
+ let changed = false;
11924
+ if (!savedContext) {
11925
+ detailLines.push(
11926
+ "Saved session has no structured resume metadata. Treat the current runtime/workspace context as authoritative."
11927
+ );
11928
+ changed = true;
11929
+ } else {
11930
+ const comparePath = (label, savedValue, currentValue) => {
11931
+ if (bestEffortCurrentContext && currentValue === void 0) {
11932
+ return;
11933
+ }
11934
+ if (savedValue === currentValue) return;
11935
+ changed = true;
11936
+ detailLines.push(
11937
+ `${label}: ${savedValue ?? "(unknown)"} -> ${currentValue ?? "(unknown)"}`
11938
+ );
11939
+ };
11940
+ comparePath(
11941
+ "Workspace root changed",
11942
+ savedContext.workspace_root,
11943
+ currentWorkspaceRoot
11944
+ );
11945
+ comparePath(
11946
+ "Working directory changed",
11947
+ savedContext.working_dir,
11948
+ currentWorkingDir
11949
+ );
11950
+ comparePath(
11951
+ "Sandbox root changed",
11952
+ savedContext.sandbox_root,
11953
+ currentSandboxRoot
11954
+ );
11955
+ if (savedContext.approval_mode !== currentApprovalMode && (!bestEffortCurrentContext || currentApprovalMode !== void 0)) {
11956
+ changed = true;
11957
+ detailLines.push(
11958
+ `Approval mode changed: ${savedContext.approval_mode ?? "(unknown)"} -> ${currentApprovalMode ?? "(unknown)"}`
11959
+ );
11960
+ }
11961
+ if ((savedContext.model_provider !== currentModelProvider || savedContext.model_name !== currentModelName) && (!bestEffortCurrentContext || currentModelProvider !== void 0 || currentModelName !== void 0)) {
11962
+ changed = true;
11963
+ detailLines.push(
11964
+ `Model changed: ${savedContext.model_provider ?? "(unknown provider)"}/${savedContext.model_name ?? "(unknown model)"} -> ${currentModelProvider ?? "(unknown provider)"}/${currentModelName ?? "(unknown model)"}`
11965
+ );
11966
+ }
11967
+ if (!(bestEffortCurrentContext && !currentInitialAgentsKnown)) {
11968
+ const agentDiffs = summarizeTrackedFileDiff(
11969
+ "Initial AGENTS",
11970
+ savedContext.initial_agents ?? [],
11971
+ currentAgents
11972
+ );
11973
+ if (agentDiffs.length > 0) {
11974
+ changed = true;
11975
+ detailLines.push(...agentDiffs);
11976
+ }
11977
+ }
11978
+ const skillDiffs = await summarizeCurrentLoadedSkillDiff(
11979
+ savedContext.loaded_skills ?? [],
11980
+ currentLoadedSkills
11981
+ );
11982
+ if (skillDiffs.length > 0) {
11983
+ changed = true;
11984
+ detailLines.push(...skillDiffs);
11985
+ }
11986
+ if (!changed) {
11987
+ detailLines.push(
11988
+ "No material workspace/AGENTS/skill changes were detected from saved resume metadata."
11989
+ );
11990
+ }
11991
+ }
11992
+ if (contextLines.length === 0 && detailLines.length === 0) {
11993
+ return null;
11994
+ }
11995
+ const summaryLines = [
11996
+ "Resume context:",
11997
+ ...contextLines.map((line) => `- ${line}`),
11998
+ ...detailLines.map((line) => `- ${line}`)
11999
+ ];
12000
+ const systemLines = [
12001
+ '<system-reminder type="session.resume.diff">',
12002
+ "Session resumed in current runtime context:",
12003
+ ...contextLines.map((line) => `- ${line}`),
12004
+ ...detailLines.map((line) => `- ${line}`),
12005
+ "Use the current runtime/workspace context for subsequent actions.",
12006
+ "</system-reminder>"
12007
+ ];
12008
+ return {
12009
+ summary: summaryLines.join("\n"),
12010
+ systemReminder: systemLines.join("\n"),
12011
+ changed
12012
+ };
12013
+ };
12014
+
12015
+ // src/rpc/run.ts
12016
+ var import_protocol5 = require("@codelia/protocol");
12017
+
12018
+ // src/rpc/client-tool-requests.ts
12019
+ var requestClientToolCall = async (state, params, timeoutMs) => {
12020
+ const id = state.nextUiRequestId();
12021
+ const request = {
12022
+ jsonrpc: "2.0",
12023
+ id,
12024
+ method: "client.tool.call",
12025
+ params
12026
+ };
12027
+ send(request);
12028
+ return await state.waitForUiResponse(id, timeoutMs);
12029
+ };
12030
+
12031
+ // src/tools/client.ts
12032
+ var DEFAULT_TIMEOUT_MS4 = 6e4;
12033
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12034
+ var normalizeClientToolResult = (value) => {
12035
+ if (typeof value === "string") {
12036
+ return { type: "text", text: value };
12037
+ }
12038
+ if (isRecord7(value)) {
12039
+ if (value.type === "text" && typeof value.text === "string") {
12040
+ return { type: "text", text: value.text };
12041
+ }
12042
+ if (value.type === "parts" && Array.isArray(value.parts)) {
12043
+ return { type: "parts", parts: value.parts };
12044
+ }
12045
+ if (value.type === "json" && "value" in value) {
12046
+ return { type: "json", value: value.value };
12047
+ }
12048
+ }
12049
+ return { type: "json", value };
12050
+ };
12051
+ var validateClientToolDefinition = (tool, existingNames) => {
12052
+ if (tool.type !== void 0 && tool.type !== "function") {
12053
+ throw new Error(`unsupported client tool type: ${String(tool.type)}`);
12054
+ }
12055
+ if (!tool.name || !/^[a-zA-Z0-9_-]+$/.test(tool.name)) {
12056
+ throw new Error(`invalid client tool name: ${tool.name}`);
12057
+ }
12058
+ if (existingNames.has(tool.name)) {
12059
+ throw new Error(
12060
+ `client tool name conflicts with existing tool: ${tool.name}`
12061
+ );
12062
+ }
12063
+ if (!tool.description.trim()) {
12064
+ throw new Error(`client tool description is required: ${tool.name}`);
12065
+ }
12066
+ if (!isRecord7(tool.parameters)) {
12067
+ throw new Error(
12068
+ `client tool parameters must be a JSON schema: ${tool.name}`
12069
+ );
12070
+ }
12071
+ if (tool.timeout_ms !== void 0 && (!Number.isFinite(tool.timeout_ms) || tool.timeout_ms <= 0)) {
12072
+ throw new Error(`client tool timeout_ms must be positive: ${tool.name}`);
12073
+ }
12074
+ };
12075
+ var createClientToolAdapters = ({
12076
+ runId,
12077
+ tools,
12078
+ state,
12079
+ existingTools
12080
+ }) => {
12081
+ if (!tools?.length) return [];
12082
+ const existingNames = new Set(existingTools.map((tool) => tool.name));
12083
+ const clientNames = /* @__PURE__ */ new Set();
12084
+ return tools.map((clientTool) => {
12085
+ validateClientToolDefinition(clientTool, existingNames);
12086
+ if (clientNames.has(clientTool.name)) {
12087
+ throw new Error(`duplicate client tool name: ${clientTool.name}`);
12088
+ }
12089
+ clientNames.add(clientTool.name);
12090
+ const timeoutMs = clientTool.timeout_ms ?? DEFAULT_TIMEOUT_MS4;
12091
+ const description = `${clientTool.description.trim()} (origin: runtime client)`;
12092
+ return {
12093
+ name: clientTool.name,
12094
+ description,
12095
+ definition: {
12096
+ name: clientTool.name,
12097
+ description,
12098
+ parameters: clientTool.parameters,
12099
+ strict: clientTool.strict ?? false
12100
+ },
12101
+ executeRaw: async (rawArgsJson) => {
12102
+ let args;
12103
+ try {
12104
+ const parsed = JSON.parse(rawArgsJson);
12105
+ args = isRecord7(parsed) ? parsed : { value: parsed };
12106
+ } catch (error) {
12107
+ throw new Error(
12108
+ `Invalid tool arguments JSON for ${clientTool.name}: ${String(error)}`
12109
+ );
12110
+ }
12111
+ const response = await requestClientToolCall(
12112
+ state,
12113
+ {
12114
+ run_id: runId,
12115
+ name: clientTool.name,
12116
+ arguments: args,
12117
+ raw_arguments: rawArgsJson
12118
+ },
12119
+ timeoutMs
12120
+ );
12121
+ if (!response.ok) {
12122
+ throw new Error(response.error);
12123
+ }
12124
+ return normalizeClientToolResult(response.result);
12125
+ }
12126
+ };
12127
+ });
12128
+ };
12129
+
12130
+ // src/rpc/run-debug.ts
12131
+ var import_core23 = require("@codelia/core");
12132
+ var DEBUG_MAX_CONTENT_CHARS = 2e3;
12133
+ var DEBUG_MAX_LOG_CHARS = 2e4;
12134
+ var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
12135
+ var DEBUG_MAX_EVENT_ARGS_CHARS = 2e3;
12136
+ var DEBUG_ERROR_MESSAGE_MAX_CHARS = 2e3;
12137
+ var DEBUG_ERROR_STACK_MAX_CHARS = 8e3;
12138
+ var DEBUG_ERROR_CHAIN_MAX_CHARS = 4e3;
12139
+ var DEBUG_ERROR_EXTRAS_MAX_CHARS = 4e3;
12140
+ var DEBUG_PROVIDER_META_STRING_MAX_CHARS = 80;
12141
+ var truncateText2 = (value, maxChars) => {
12142
+ if (value.length <= maxChars) return value;
12143
+ return `${value.slice(0, maxChars)}...[truncated]`;
12144
+ };
12145
+ var stringifyUnknown = (value) => {
12146
+ try {
12147
+ return JSON.stringify(value);
12148
+ } catch {
12149
+ return String(value);
12150
+ }
12151
+ };
12152
+ var contentToDebugText = (content, maxChars) => {
12153
+ const text = (0, import_core23.stringifyContent)(content, {
12154
+ mode: "log",
12155
+ joiner: "\n",
12156
+ includeOtherPayload: true
12157
+ });
12158
+ return truncateText2(text, maxChars);
12159
+ };
12160
+ var buildCompactionSnapshotLog = (messages) => {
12161
+ const payload = messages.map((message, index) => {
12162
+ if (message.role === "assistant") {
12163
+ return {
12164
+ index,
12165
+ role: message.role,
12166
+ content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS),
12167
+ tool_calls: (message.tool_calls ?? []).map((call) => ({
12168
+ id: call.id,
12169
+ name: call.function.name
12170
+ }))
12171
+ };
12172
+ }
12173
+ if (message.role === "tool") {
12174
+ return {
12175
+ index,
12176
+ role: message.role,
12177
+ tool_name: message.tool_name,
12178
+ tool_call_id: message.tool_call_id,
12179
+ is_error: message.is_error ?? false,
12180
+ content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS)
12181
+ };
12182
+ }
12183
+ if (message.role === "reasoning") {
12184
+ return {
12185
+ index,
12186
+ role: message.role,
12187
+ content: truncateText2(message.content ?? "", DEBUG_MAX_CONTENT_CHARS)
12188
+ };
12189
+ }
12190
+ return {
12191
+ index,
12192
+ role: message.role,
12193
+ content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS)
12194
+ };
12195
+ });
12196
+ return truncateText2(stringifyUnknown(payload), DEBUG_MAX_LOG_CHARS);
12197
+ };
12198
+ var logCompactionSnapshot = (log2, runId, runtimeAgent, compacted) => {
12199
+ if (!(0, import_logger.isDebugEnabled)()) return;
12200
+ const messages = runtimeAgent.getHistoryMessages();
12201
+ const snapshot = buildCompactionSnapshotLog(messages);
12202
+ log2(
12203
+ `compaction context snapshot run_id=${runId} compacted=${String(compacted)} messages=${messages.length} history=${snapshot}`
12204
+ );
12205
+ };
12206
+ var isTrackedRunEvent = (eventType) => eventType === "tool_call" || eventType === "tool_result" || eventType === "step_start" || eventType === "step_complete" || eventType === "final";
12207
+ var summarizeRunEvent = (event) => {
12208
+ switch (event.type) {
12209
+ case "tool_call": {
12210
+ const tool = typeof event.tool === "string" ? event.tool : "unknown";
12211
+ const toolCallId = typeof event.tool_call_id === "string" ? event.tool_call_id : "unknown";
12212
+ const rawArgs = typeof event.raw_args === "string" ? event.raw_args : stringifyUnknown(event.args);
12213
+ const rawArgsSnippet = truncateText2(rawArgs, DEBUG_MAX_EVENT_ARGS_CHARS);
12214
+ return `type=tool_call tool=${tool} tool_call_id=${toolCallId} raw_args=${stringifyUnknown(rawArgsSnippet)}`;
12215
+ }
12216
+ case "tool_result": {
12217
+ const tool = typeof event.tool === "string" ? event.tool : "unknown";
12218
+ const toolCallId = typeof event.tool_call_id === "string" ? event.tool_call_id : "unknown";
12219
+ const isError = event.is_error === true;
12220
+ const result = typeof event.result === "string" ? truncateText2(event.result, DEBUG_MAX_EVENT_RESULT_CHARS) : truncateText2(
12221
+ stringifyUnknown(event.result),
12222
+ DEBUG_MAX_EVENT_RESULT_CHARS
12223
+ );
12224
+ return `type=tool_result tool=${tool} tool_call_id=${toolCallId} is_error=${String(isError)} result=${stringifyUnknown(result)}`;
12225
+ }
12226
+ case "step_start": {
12227
+ const stepId = typeof event.step_id === "string" ? event.step_id : "unknown";
12228
+ const title = typeof event.title === "string" ? event.title : "unknown";
12229
+ return `type=step_start step_id=${stepId} title=${title}`;
12230
+ }
12231
+ case "step_complete": {
12232
+ const stepId = typeof event.step_id === "string" ? event.step_id : "unknown";
12233
+ const status = typeof event.status === "string" ? event.status : "unknown";
12234
+ const durationMs = typeof event.duration_ms === "number" ? event.duration_ms : -1;
12235
+ return `type=step_complete step_id=${stepId} status=${status} duration_ms=${durationMs}`;
12236
+ }
12237
+ case "final": {
12238
+ const content = typeof event.content === "string" ? event.content : "";
12239
+ return `type=final content_chars=${content.length}`;
12240
+ }
12241
+ default:
12242
+ return `type=${event.type}`;
12243
+ }
12244
+ };
12245
+ var logRunDebug = (log2, runId, message) => {
12246
+ if (!(0, import_logger.isDebugEnabled)()) return;
12247
+ log2(`run debug run_id=${runId} ${message}`);
12248
+ };
12249
+ var normalizeToolCallHistory = (messages) => {
12250
+ const assistantCallIds = /* @__PURE__ */ new Set();
12251
+ const toolOutputCallIds = /* @__PURE__ */ new Set();
12252
+ for (const message of messages) {
12253
+ if (message.role === "assistant") {
12254
+ for (const call of message.tool_calls ?? []) {
12255
+ assistantCallIds.add(call.id);
12256
+ }
12257
+ continue;
12258
+ }
12259
+ if (message.role === "tool") {
12260
+ toolOutputCallIds.add(message.tool_call_id);
12261
+ }
12187
12262
  }
12188
- if (currentSandboxRoot) {
12189
- contextLines.push(`Current sandbox root: ${currentSandboxRoot}`);
12263
+ if (assistantCallIds.size === 0 && toolOutputCallIds.size === 0) {
12264
+ return messages;
12190
12265
  }
12191
- if (currentApprovalMode) {
12192
- contextLines.push(`Current approval mode: ${currentApprovalMode}`);
12266
+ const validCallIds = /* @__PURE__ */ new Set();
12267
+ for (const callId of assistantCallIds) {
12268
+ if (toolOutputCallIds.has(callId)) {
12269
+ validCallIds.add(callId);
12270
+ }
12193
12271
  }
12194
- if (currentModelProvider || currentModelName) {
12195
- contextLines.push(
12196
- `Current model: ${currentModelProvider ?? "(unknown provider)"}/${currentModelName ?? "(unknown model)"}`
12197
- );
12272
+ if (validCallIds.size === assistantCallIds.size && validCallIds.size === toolOutputCallIds.size) {
12273
+ return messages;
12198
12274
  }
12199
- const detailLines = [];
12200
12275
  let changed = false;
12201
- if (!savedContext) {
12202
- detailLines.push(
12203
- "Saved session has no structured resume metadata. Treat the current runtime/workspace context as authoritative."
12204
- );
12205
- changed = true;
12206
- } else {
12207
- const comparePath = (label, savedValue, currentValue) => {
12208
- if (bestEffortCurrentContext && currentValue === void 0) {
12209
- return;
12276
+ const normalized = [];
12277
+ for (const message of messages) {
12278
+ if (message.role === "assistant") {
12279
+ const calls = message.tool_calls ?? [];
12280
+ if (calls.length > 0) {
12281
+ const filteredCalls = calls.filter((call) => validCallIds.has(call.id));
12282
+ if (filteredCalls.length !== calls.length) {
12283
+ changed = true;
12284
+ if (filteredCalls.length === 0) {
12285
+ const next = { ...message };
12286
+ delete next.tool_calls;
12287
+ normalized.push(next);
12288
+ } else {
12289
+ normalized.push({ ...message, tool_calls: filteredCalls });
12290
+ }
12291
+ continue;
12292
+ }
12210
12293
  }
12211
- if (savedValue === currentValue) return;
12294
+ normalized.push(message);
12295
+ continue;
12296
+ }
12297
+ if (message.role === "tool" && !validCallIds.has(message.tool_call_id)) {
12212
12298
  changed = true;
12213
- detailLines.push(
12214
- `${label}: ${savedValue ?? "(unknown)"} -> ${currentValue ?? "(unknown)"}`
12215
- );
12216
- };
12217
- comparePath(
12218
- "Workspace root changed",
12219
- savedContext.workspace_root,
12220
- currentWorkspaceRoot
12299
+ continue;
12300
+ }
12301
+ normalized.push(message);
12302
+ }
12303
+ return changed ? normalized : messages;
12304
+ };
12305
+ var formatErrorForDebugLog = (error) => {
12306
+ const parts = [];
12307
+ parts.push(`name=${error.name}`);
12308
+ parts.push(
12309
+ `message=${truncateText2(error.message, DEBUG_ERROR_MESSAGE_MAX_CHARS)}`
12310
+ );
12311
+ if (error.stack) {
12312
+ parts.push(
12313
+ `stack=${truncateText2(error.stack, DEBUG_ERROR_STACK_MAX_CHARS)}`
12221
12314
  );
12222
- comparePath(
12223
- "Working directory changed",
12224
- savedContext.working_dir,
12225
- currentWorkingDir
12315
+ }
12316
+ const causeChain = [];
12317
+ let depth = 0;
12318
+ let current = error.cause;
12319
+ const seen = /* @__PURE__ */ new Set();
12320
+ while (current !== void 0 && current !== null && depth < 4) {
12321
+ if (seen.has(current)) {
12322
+ causeChain.push("[circular]");
12323
+ break;
12324
+ }
12325
+ seen.add(current);
12326
+ if (current instanceof Error) {
12327
+ causeChain.push(`${current.name}: ${current.message}`);
12328
+ current = current.cause;
12329
+ depth += 1;
12330
+ continue;
12331
+ }
12332
+ causeChain.push(stringifyUnknown(current));
12333
+ break;
12334
+ }
12335
+ if (causeChain.length > 0) {
12336
+ parts.push(
12337
+ `cause_chain=${truncateText2(causeChain.join(" <- "), DEBUG_ERROR_CHAIN_MAX_CHARS)}`
12226
12338
  );
12227
- comparePath(
12228
- "Sandbox root changed",
12229
- savedContext.sandbox_root,
12230
- currentSandboxRoot
12339
+ }
12340
+ const extras = Object.entries(
12341
+ error
12342
+ ).filter(([key]) => key !== "name" && key !== "message" && key !== "stack");
12343
+ if (extras.length > 0) {
12344
+ parts.push(
12345
+ `extras=${truncateText2(
12346
+ stringifyUnknown(Object.fromEntries(extras)),
12347
+ DEBUG_ERROR_EXTRAS_MAX_CHARS
12348
+ )}`
12231
12349
  );
12232
- if (savedContext.approval_mode !== currentApprovalMode && (!bestEffortCurrentContext || currentApprovalMode !== void 0)) {
12233
- changed = true;
12234
- detailLines.push(
12235
- `Approval mode changed: ${savedContext.approval_mode ?? "(unknown)"} -> ${currentApprovalMode ?? "(unknown)"}`
12236
- );
12350
+ }
12351
+ return parts.join(" ");
12352
+ };
12353
+ var summarizeProviderMeta = (value) => {
12354
+ if (value === null || value === void 0) {
12355
+ return null;
12356
+ }
12357
+ if (typeof value === "string") {
12358
+ return value.length > DEBUG_PROVIDER_META_STRING_MAX_CHARS ? `${value.slice(0, DEBUG_PROVIDER_META_STRING_MAX_CHARS - 3)}...` : value;
12359
+ }
12360
+ if (Array.isArray(value)) {
12361
+ return `array(len=${value.length})`;
12362
+ }
12363
+ if (typeof value === "object") {
12364
+ const obj = value;
12365
+ const details = [];
12366
+ if (typeof obj.transport === "string") {
12367
+ details.push(`transport=${obj.transport}`);
12237
12368
  }
12238
- if ((savedContext.model_provider !== currentModelProvider || savedContext.model_name !== currentModelName) && (!bestEffortCurrentContext || currentModelProvider !== void 0 || currentModelName !== void 0)) {
12239
- changed = true;
12240
- detailLines.push(
12241
- `Model changed: ${savedContext.model_provider ?? "(unknown provider)"}/${savedContext.model_name ?? "(unknown model)"} -> ${currentModelProvider ?? "(unknown provider)"}/${currentModelName ?? "(unknown model)"}`
12242
- );
12369
+ if (typeof obj.websocket_mode === "string") {
12370
+ details.push(`websocket_mode=${obj.websocket_mode}`);
12243
12371
  }
12244
- if (!(bestEffortCurrentContext && !currentInitialAgentsKnown)) {
12245
- const agentDiffs = summarizeTrackedFileDiff(
12246
- "Initial AGENTS",
12247
- savedContext.initial_agents ?? [],
12248
- currentAgents
12249
- );
12250
- if (agentDiffs.length > 0) {
12251
- changed = true;
12252
- detailLines.push(...agentDiffs);
12253
- }
12372
+ if (typeof obj.response_id === "string") {
12373
+ details.push(`response_id=${obj.response_id}`);
12254
12374
  }
12255
- const skillDiffs = await summarizeCurrentLoadedSkillDiff(
12256
- savedContext.loaded_skills ?? [],
12257
- currentLoadedSkills
12258
- );
12259
- if (skillDiffs.length > 0) {
12260
- changed = true;
12261
- detailLines.push(...skillDiffs);
12375
+ if (typeof obj.chain_reset === "boolean") {
12376
+ details.push(`chain_reset=${obj.chain_reset ? "true" : "false"}`);
12262
12377
  }
12263
- if (!changed) {
12264
- detailLines.push(
12265
- "No material workspace/AGENTS/skill changes were detected from saved resume metadata."
12378
+ if (typeof obj.fallback_used === "boolean") {
12379
+ details.push(`fallback_used=${obj.fallback_used ? "true" : "false"}`);
12380
+ }
12381
+ if (typeof obj.ws_input_mode === "string") {
12382
+ details.push(`ws_input_mode=${obj.ws_input_mode}`);
12383
+ }
12384
+ if (typeof obj.reasoning_requested === "string") {
12385
+ details.push(`reasoning_requested=${obj.reasoning_requested}`);
12386
+ }
12387
+ if (typeof obj.reasoning_applied === "string") {
12388
+ details.push(`reasoning_applied=${obj.reasoning_applied}`);
12389
+ }
12390
+ if (typeof obj.reasoning_fallback === "boolean") {
12391
+ details.push(
12392
+ `reasoning_fallback=${obj.reasoning_fallback ? "true" : "false"}`
12266
12393
  );
12267
12394
  }
12395
+ if (typeof obj.reasoning_budget_preset === "string") {
12396
+ details.push(`reasoning_budget_preset=${obj.reasoning_budget_preset}`);
12397
+ }
12398
+ if (details.length > 0) {
12399
+ return details.join(" ");
12400
+ }
12401
+ const keys = Object.keys(obj);
12402
+ if (keys.length === 0) return "object";
12403
+ const shown = keys.slice(0, 4).join(",");
12404
+ return keys.length > 4 ? `object(keys=${shown},...)` : `object(keys=${shown})`;
12268
12405
  }
12269
- if (contextLines.length === 0 && detailLines.length === 0) {
12270
- return null;
12271
- }
12272
- const summaryLines = [
12273
- "Resume context:",
12274
- ...contextLines.map((line) => `- ${line}`),
12275
- ...detailLines.map((line) => `- ${line}`)
12276
- ];
12277
- const systemLines = [
12278
- '<system-reminder type="session.resume.diff">',
12279
- "Session resumed in current runtime context:",
12280
- ...contextLines.map((line) => `- ${line}`),
12281
- ...detailLines.map((line) => `- ${line}`),
12282
- "Use the current runtime/workspace context for subsequent actions.",
12283
- "</system-reminder>"
12284
- ];
12285
- return {
12286
- summary: summaryLines.join("\n"),
12287
- systemReminder: systemLines.join("\n"),
12288
- changed
12289
- };
12406
+ return typeof value;
12290
12407
  };
12408
+ var isAbortLikeError = (error) => error.name === "AbortError" || error.name === "APIUserAbortError" || error.name === "AbortSignal" || /aborted|abort/i.test(error.message);
12291
12409
 
12292
12410
  // src/rpc/skill-mentions.ts
12293
12411
  var SKILL_MENTION_PATTERN = /\$([a-z0-9]+(?:-[a-z0-9]+)*)/g;
@@ -12628,6 +12746,24 @@ var createRunHandlers = ({
12628
12746
  };
12629
12747
  }
12630
12748
  const runId = state.nextRunId();
12749
+ let clientTools;
12750
+ try {
12751
+ clientTools = createClientToolAdapters({
12752
+ runId,
12753
+ tools: params.tools,
12754
+ state,
12755
+ existingTools: state.tools ?? []
12756
+ });
12757
+ state.autoApprovedClientToolNames = new Set(
12758
+ (params.tools ?? []).filter((tool) => tool.approval === "never").map((tool) => tool.name)
12759
+ );
12760
+ } catch (error) {
12761
+ sendError(id, {
12762
+ code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
12763
+ message: String(error)
12764
+ });
12765
+ return;
12766
+ }
12631
12767
  const startedAt = nowIso5();
12632
12768
  state.beginRun(runId, params.ui_context ?? state.lastUiContext);
12633
12769
  const runAbortController = new AbortController();
@@ -12762,7 +12898,13 @@ var createRunHandlers = ({
12762
12898
  ...modelConfig.fast !== void 0 ? { fast: modelConfig.fast } : {}
12763
12899
  } : void 0,
12764
12900
  prompts: state.systemPrompt ? { system: state.systemPrompt } : void 0,
12765
- tools: state.toolDefinitions ? { definitions: state.toolDefinitions, source: "runtime" } : void 0,
12901
+ tools: state.toolDefinitions ? {
12902
+ definitions: [
12903
+ ...state.toolDefinitions,
12904
+ ...clientTools.map((tool) => tool.definition)
12905
+ ],
12906
+ source: clientTools.length ? "runtime+client" : "runtime"
12907
+ } : void 0,
12766
12908
  runtime: {
12767
12909
  cwd: state.lastUiContext?.cwd,
12768
12910
  os: process.platform,
@@ -12852,7 +12994,9 @@ var createRunHandlers = ({
12852
12994
  for await (const event of runtimeAgent.runStream(normalizedInput, {
12853
12995
  session,
12854
12996
  signal: runAbortController.signal,
12855
- forceCompaction: params.force_compaction
12997
+ forceCompaction: params.force_compaction,
12998
+ tools: clientTools,
12999
+ toolChoice: params.tool_choice
12856
13000
  })) {
12857
13001
  if (state.cancelRequested) {
12858
13002
  break;
@@ -14544,6 +14688,7 @@ var RuntimeState = class {
14544
14688
  executionEnvironmentDebugLogged = false;
14545
14689
  toolDefinitions = null;
14546
14690
  tools = null;
14691
+ autoApprovedClientToolNames = /* @__PURE__ */ new Set();
14547
14692
  sessionId = null;
14548
14693
  sessionMeta = null;
14549
14694
  sessionAppend = null;
@@ -14579,6 +14724,7 @@ var RuntimeState = class {
14579
14724
  }
14580
14725
  this.cancelRequested = false;
14581
14726
  this.lastContextLeftPercent = null;
14727
+ this.autoApprovedClientToolNames.clear();
14582
14728
  this.runSeq.delete(runId);
14583
14729
  if (this.activeRunId === null) {
14584
14730
  this.sessionAppend = null;