@codelia/runtime 0.1.66 → 0.1.68

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 +605 -456
  2. package/dist/index.js +605 -456
  3. package/package.json +9 -9
package/dist/index.js CHANGED
@@ -2,6 +2,26 @@
2
2
  import path20 from "path";
3
3
  import { SessionStateStoreImpl as SessionStateStoreImpl2 } from "@codelia/storage";
4
4
 
5
+ // src/agent-factory.ts
6
+ import { promises as fs15 } from "fs";
7
+ import {
8
+ Agent,
9
+ ANTHROPIC_DEFAULT_MODEL,
10
+ ChatAnthropic,
11
+ ChatOpenAI,
12
+ ChatOpenRouter,
13
+ DEFAULT_MODEL_REGISTRY as DEFAULT_MODEL_REGISTRY3,
14
+ OPENAI_DEFAULT_MODEL,
15
+ resolveModel as resolveModel2,
16
+ resolveProviderModelId as resolveProviderModelId2
17
+ } from "@codelia/core";
18
+ import { ModelMetadataServiceImpl as ModelMetadataServiceImpl2 } from "@codelia/model-metadata";
19
+ import { parseApprovalMode as parseApprovalMode2 } from "@codelia/shared-types";
20
+ import {
21
+ StoragePathServiceImpl as StoragePathServiceImpl3,
22
+ ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl2
23
+ } from "@codelia/storage";
24
+
5
25
  // src/agents/context.ts
6
26
  var createAgentsResolverKey = (resolver) => ({
7
27
  id: "agents-resolver",
@@ -363,26 +383,6 @@ var appendInitialAgentsContext = (systemPrompt, agentsContext) => {
363
383
  ${agentsContext}`;
364
384
  };
365
385
 
366
- // src/agent-factory.ts
367
- import { promises as fs15 } from "fs";
368
- import {
369
- Agent,
370
- ANTHROPIC_DEFAULT_MODEL,
371
- ChatAnthropic,
372
- ChatOpenAI,
373
- ChatOpenRouter,
374
- DEFAULT_MODEL_REGISTRY as DEFAULT_MODEL_REGISTRY3,
375
- OPENAI_DEFAULT_MODEL,
376
- resolveModel as resolveModel2,
377
- resolveProviderModelId as resolveProviderModelId2
378
- } from "@codelia/core";
379
- import { ModelMetadataServiceImpl as ModelMetadataServiceImpl2 } from "@codelia/model-metadata";
380
- import { parseApprovalMode as parseApprovalMode2 } from "@codelia/shared-types";
381
- import {
382
- StoragePathServiceImpl as StoragePathServiceImpl3,
383
- ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl2
384
- } from "@codelia/storage";
385
-
386
386
  // src/auth/oauth-utils.ts
387
387
  import { createServer } from "http";
388
388
  import * as oauth from "oauth4webapi";
@@ -2359,6 +2359,24 @@ var createMcpOAuthSession = async (params, options = {}) => {
2359
2359
  };
2360
2360
  };
2361
2361
 
2362
+ // src/model-fast.ts
2363
+ import { DEFAULT_MODEL_REGISTRY, supportsFastMode } from "@codelia/core";
2364
+ var resolveFastMode = (params) => {
2365
+ if (params.requested !== true) {
2366
+ return { enabled: false };
2367
+ }
2368
+ if (!supportsFastMode(DEFAULT_MODEL_REGISTRY, params.model, params.provider)) {
2369
+ return { enabled: false };
2370
+ }
2371
+ if (params.provider === "openai") {
2372
+ return { enabled: true, provider: "openai", serviceTier: "priority" };
2373
+ }
2374
+ if (params.provider === "anthropic") {
2375
+ return { enabled: true, provider: "anthropic", fastMode: true };
2376
+ }
2377
+ return { enabled: false };
2378
+ };
2379
+
2362
2380
  // src/model-reasoning.ts
2363
2381
  var REASONING_LEVEL_ORDER = [
2364
2382
  "low",
@@ -2579,24 +2597,6 @@ var resolveAnthropicMaxTokens = ({
2579
2597
  return normalizedBudget + ANTHROPIC_MAX_TOKENS_FALLBACK_HEADROOM;
2580
2598
  };
2581
2599
 
2582
- // src/model-fast.ts
2583
- import { DEFAULT_MODEL_REGISTRY, supportsFastMode } from "@codelia/core";
2584
- var resolveFastMode = (params) => {
2585
- if (params.requested !== true) {
2586
- return { enabled: false };
2587
- }
2588
- if (!supportsFastMode(DEFAULT_MODEL_REGISTRY, params.model, params.provider)) {
2589
- return { enabled: false };
2590
- }
2591
- if (params.provider === "openai") {
2592
- return { enabled: true, provider: "openai", serviceTier: "priority" };
2593
- }
2594
- if (params.provider === "anthropic") {
2595
- return { enabled: true, provider: "anthropic", fastMode: true };
2596
- }
2597
- return { enabled: false };
2598
- };
2599
-
2600
2600
  // src/model-registry.ts
2601
2601
  import {
2602
2602
  applyModelMetadata,
@@ -9353,6 +9353,12 @@ var createAgentFactory = (state, options = {}) => {
9353
9353
  },
9354
9354
  services: { toolOutputCacheStore },
9355
9355
  canExecuteTool: async (call, rawArgs, toolCtx) => {
9356
+ if (state.autoApprovedClientToolNames.has(call.function.name)) {
9357
+ debugLog(
9358
+ `permission.evaluate tool=${call.function.name} decision=allow reason=client-tool-auto-approved`
9359
+ );
9360
+ return { decision: "allow" };
9361
+ }
9356
9362
  const decision = permissionService.evaluate(
9357
9363
  call.function.name,
9358
9364
  rawArgs
@@ -11667,340 +11673,55 @@ var createModelHandlers = ({
11667
11673
  return { handleModelList, handleModelSet };
11668
11674
  };
11669
11675
 
11670
- // src/rpc/run.ts
11671
- import {
11672
- RPC_ERROR_CODE as RPC_ERROR_CODE4
11673
- } from "@codelia/protocol";
11674
-
11675
- // src/rpc/run-debug.ts
11676
- import { stringifyContent } from "@codelia/core";
11677
- var DEBUG_MAX_CONTENT_CHARS = 2e3;
11678
- var DEBUG_MAX_LOG_CHARS = 2e4;
11679
- var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
11680
- var DEBUG_MAX_EVENT_ARGS_CHARS = 2e3;
11681
- var DEBUG_ERROR_MESSAGE_MAX_CHARS = 2e3;
11682
- var DEBUG_ERROR_STACK_MAX_CHARS = 8e3;
11683
- var DEBUG_ERROR_CHAIN_MAX_CHARS = 4e3;
11684
- var DEBUG_ERROR_EXTRAS_MAX_CHARS = 4e3;
11685
- var DEBUG_PROVIDER_META_STRING_MAX_CHARS = 80;
11686
- var truncateText2 = (value, maxChars) => {
11687
- if (value.length <= maxChars) return value;
11688
- return `${value.slice(0, maxChars)}...[truncated]`;
11676
+ // src/rpc/resume-context.ts
11677
+ import { promises as fs17 } from "fs";
11678
+ import path16 from "path";
11679
+ var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
11680
+ var RESUME_CONTEXT_SCHEMA_VERSION = 1;
11681
+ var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
11682
+ var MAX_RESUME_DETAIL_LINES = 3;
11683
+ var normalizePath2 = (value) => {
11684
+ if (typeof value !== "string") return void 0;
11685
+ const trimmed = value.trim();
11686
+ if (!trimmed) return void 0;
11687
+ return path16.resolve(trimmed);
11689
11688
  };
11690
- var stringifyUnknown = (value) => {
11691
- try {
11692
- return JSON.stringify(value);
11693
- } catch {
11694
- return String(value);
11689
+ var normalizeMtime3 = (value) => {
11690
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
11691
+ return void 0;
11695
11692
  }
11693
+ return Math.trunc(value);
11696
11694
  };
11697
- var contentToDebugText = (content, maxChars) => {
11698
- const text = stringifyContent(content, {
11699
- mode: "log",
11700
- joiner: "\n",
11701
- includeOtherPayload: true
11702
- });
11703
- return truncateText2(text, maxChars);
11704
- };
11705
- var buildCompactionSnapshotLog = (messages) => {
11706
- const payload = messages.map((message, index) => {
11707
- if (message.role === "assistant") {
11708
- return {
11709
- index,
11710
- role: message.role,
11711
- content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS),
11712
- tool_calls: (message.tool_calls ?? []).map((call) => ({
11713
- id: call.id,
11714
- name: call.function.name
11715
- }))
11716
- };
11717
- }
11718
- if (message.role === "tool") {
11719
- return {
11720
- index,
11721
- role: message.role,
11722
- tool_name: message.tool_name,
11723
- tool_call_id: message.tool_call_id,
11724
- is_error: message.is_error ?? false,
11725
- content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS)
11726
- };
11727
- }
11728
- if (message.role === "reasoning") {
11729
- return {
11730
- index,
11731
- role: message.role,
11732
- content: truncateText2(message.content ?? "", DEBUG_MAX_CONTENT_CHARS)
11733
- };
11734
- }
11735
- return {
11736
- index,
11737
- role: message.role,
11738
- content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS)
11739
- };
11740
- });
11741
- return truncateText2(stringifyUnknown(payload), DEBUG_MAX_LOG_CHARS);
11742
- };
11743
- var logCompactionSnapshot = (log2, runId, runtimeAgent, compacted) => {
11744
- if (!isDebugEnabled()) return;
11745
- const messages = runtimeAgent.getHistoryMessages();
11746
- const snapshot = buildCompactionSnapshotLog(messages);
11747
- log2(
11748
- `compaction context snapshot run_id=${runId} compacted=${String(compacted)} messages=${messages.length} history=${snapshot}`
11749
- );
11695
+ var normalizeText = (value) => {
11696
+ if (typeof value !== "string") return void 0;
11697
+ const trimmed = value.trim();
11698
+ return trimmed.length > 0 ? trimmed : void 0;
11750
11699
  };
11751
- var isTrackedRunEvent = (eventType) => eventType === "tool_call" || eventType === "tool_result" || eventType === "step_start" || eventType === "step_complete" || eventType === "final";
11752
- var summarizeRunEvent = (event) => {
11753
- switch (event.type) {
11754
- case "tool_call": {
11755
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
11756
- const toolCallId = typeof event.tool_call_id === "string" ? event.tool_call_id : "unknown";
11757
- const rawArgs = typeof event.raw_args === "string" ? event.raw_args : stringifyUnknown(event.args);
11758
- const rawArgsSnippet = truncateText2(rawArgs, DEBUG_MAX_EVENT_ARGS_CHARS);
11759
- return `type=tool_call tool=${tool} tool_call_id=${toolCallId} raw_args=${stringifyUnknown(rawArgsSnippet)}`;
11760
- }
11761
- case "tool_result": {
11762
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
11763
- const toolCallId = typeof event.tool_call_id === "string" ? event.tool_call_id : "unknown";
11764
- const isError = event.is_error === true;
11765
- const result = typeof event.result === "string" ? truncateText2(event.result, DEBUG_MAX_EVENT_RESULT_CHARS) : truncateText2(
11766
- stringifyUnknown(event.result),
11767
- DEBUG_MAX_EVENT_RESULT_CHARS
11768
- );
11769
- return `type=tool_result tool=${tool} tool_call_id=${toolCallId} is_error=${String(isError)} result=${stringifyUnknown(result)}`;
11770
- }
11771
- case "step_start": {
11772
- const stepId = typeof event.step_id === "string" ? event.step_id : "unknown";
11773
- const title = typeof event.title === "string" ? event.title : "unknown";
11774
- return `type=step_start step_id=${stepId} title=${title}`;
11775
- }
11776
- case "step_complete": {
11777
- const stepId = typeof event.step_id === "string" ? event.step_id : "unknown";
11778
- const status = typeof event.status === "string" ? event.status : "unknown";
11779
- const durationMs = typeof event.duration_ms === "number" ? event.duration_ms : -1;
11780
- return `type=step_complete step_id=${stepId} status=${status} duration_ms=${durationMs}`;
11781
- }
11782
- case "final": {
11783
- const content = typeof event.content === "string" ? event.content : "";
11784
- return `type=final content_chars=${content.length}`;
11785
- }
11786
- default:
11787
- return `type=${event.type}`;
11700
+ var normalizeApprovalMode = (value) => {
11701
+ if (value === "minimal" || value === "trusted" || value === "full-access") {
11702
+ return value;
11788
11703
  }
11704
+ return void 0;
11789
11705
  };
11790
- var logRunDebug = (log2, runId, message) => {
11791
- if (!isDebugEnabled()) return;
11792
- log2(`run debug run_id=${runId} ${message}`);
11793
- };
11794
- var normalizeToolCallHistory = (messages) => {
11795
- const assistantCallIds = /* @__PURE__ */ new Set();
11796
- const toolOutputCallIds = /* @__PURE__ */ new Set();
11797
- for (const message of messages) {
11798
- if (message.role === "assistant") {
11799
- for (const call of message.tool_calls ?? []) {
11800
- assistantCallIds.add(call.id);
11801
- }
11802
- continue;
11803
- }
11804
- if (message.role === "tool") {
11805
- toolOutputCallIds.add(message.tool_call_id);
11806
- }
11706
+ var normalizeTrackedFiles = (value) => {
11707
+ if (!Array.isArray(value)) return [];
11708
+ const seen = /* @__PURE__ */ new Set();
11709
+ const files = [];
11710
+ for (const entry of value) {
11711
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11712
+ const record = entry;
11713
+ const filePath = normalizePath2(record.path);
11714
+ const mtime = normalizeMtime3(record.mtime_ms);
11715
+ if (!filePath || mtime === void 0 || seen.has(filePath)) continue;
11716
+ seen.add(filePath);
11717
+ files.push({ path: filePath, mtime_ms: mtime });
11807
11718
  }
11808
- if (assistantCallIds.size === 0 && toolOutputCallIds.size === 0) {
11809
- return messages;
11810
- }
11811
- const validCallIds = /* @__PURE__ */ new Set();
11812
- for (const callId of assistantCallIds) {
11813
- if (toolOutputCallIds.has(callId)) {
11814
- validCallIds.add(callId);
11815
- }
11816
- }
11817
- if (validCallIds.size === assistantCallIds.size && validCallIds.size === toolOutputCallIds.size) {
11818
- return messages;
11819
- }
11820
- let changed = false;
11821
- const normalized = [];
11822
- for (const message of messages) {
11823
- if (message.role === "assistant") {
11824
- const calls = message.tool_calls ?? [];
11825
- if (calls.length > 0) {
11826
- const filteredCalls = calls.filter((call) => validCallIds.has(call.id));
11827
- if (filteredCalls.length !== calls.length) {
11828
- changed = true;
11829
- if (filteredCalls.length === 0) {
11830
- const next = { ...message };
11831
- delete next.tool_calls;
11832
- normalized.push(next);
11833
- } else {
11834
- normalized.push({ ...message, tool_calls: filteredCalls });
11835
- }
11836
- continue;
11837
- }
11838
- }
11839
- normalized.push(message);
11840
- continue;
11841
- }
11842
- if (message.role === "tool" && !validCallIds.has(message.tool_call_id)) {
11843
- changed = true;
11844
- continue;
11845
- }
11846
- normalized.push(message);
11847
- }
11848
- return changed ? normalized : messages;
11849
- };
11850
- var formatErrorForDebugLog = (error) => {
11851
- const parts = [];
11852
- parts.push(`name=${error.name}`);
11853
- parts.push(
11854
- `message=${truncateText2(error.message, DEBUG_ERROR_MESSAGE_MAX_CHARS)}`
11855
- );
11856
- if (error.stack) {
11857
- parts.push(
11858
- `stack=${truncateText2(error.stack, DEBUG_ERROR_STACK_MAX_CHARS)}`
11859
- );
11860
- }
11861
- const causeChain = [];
11862
- let depth = 0;
11863
- let current = error.cause;
11864
- const seen = /* @__PURE__ */ new Set();
11865
- while (current !== void 0 && current !== null && depth < 4) {
11866
- if (seen.has(current)) {
11867
- causeChain.push("[circular]");
11868
- break;
11869
- }
11870
- seen.add(current);
11871
- if (current instanceof Error) {
11872
- causeChain.push(`${current.name}: ${current.message}`);
11873
- current = current.cause;
11874
- depth += 1;
11875
- continue;
11876
- }
11877
- causeChain.push(stringifyUnknown(current));
11878
- break;
11879
- }
11880
- if (causeChain.length > 0) {
11881
- parts.push(
11882
- `cause_chain=${truncateText2(causeChain.join(" <- "), DEBUG_ERROR_CHAIN_MAX_CHARS)}`
11883
- );
11884
- }
11885
- const extras = Object.entries(
11886
- error
11887
- ).filter(([key]) => key !== "name" && key !== "message" && key !== "stack");
11888
- if (extras.length > 0) {
11889
- parts.push(
11890
- `extras=${truncateText2(
11891
- stringifyUnknown(Object.fromEntries(extras)),
11892
- DEBUG_ERROR_EXTRAS_MAX_CHARS
11893
- )}`
11894
- );
11895
- }
11896
- return parts.join(" ");
11897
- };
11898
- var summarizeProviderMeta = (value) => {
11899
- if (value === null || value === void 0) {
11900
- return null;
11901
- }
11902
- if (typeof value === "string") {
11903
- return value.length > DEBUG_PROVIDER_META_STRING_MAX_CHARS ? `${value.slice(0, DEBUG_PROVIDER_META_STRING_MAX_CHARS - 3)}...` : value;
11904
- }
11905
- if (Array.isArray(value)) {
11906
- return `array(len=${value.length})`;
11907
- }
11908
- if (typeof value === "object") {
11909
- const obj = value;
11910
- const details = [];
11911
- if (typeof obj.transport === "string") {
11912
- details.push(`transport=${obj.transport}`);
11913
- }
11914
- if (typeof obj.websocket_mode === "string") {
11915
- details.push(`websocket_mode=${obj.websocket_mode}`);
11916
- }
11917
- if (typeof obj.response_id === "string") {
11918
- details.push(`response_id=${obj.response_id}`);
11919
- }
11920
- if (typeof obj.chain_reset === "boolean") {
11921
- details.push(`chain_reset=${obj.chain_reset ? "true" : "false"}`);
11922
- }
11923
- if (typeof obj.fallback_used === "boolean") {
11924
- details.push(`fallback_used=${obj.fallback_used ? "true" : "false"}`);
11925
- }
11926
- if (typeof obj.ws_input_mode === "string") {
11927
- details.push(`ws_input_mode=${obj.ws_input_mode}`);
11928
- }
11929
- if (typeof obj.reasoning_requested === "string") {
11930
- details.push(`reasoning_requested=${obj.reasoning_requested}`);
11931
- }
11932
- if (typeof obj.reasoning_applied === "string") {
11933
- details.push(`reasoning_applied=${obj.reasoning_applied}`);
11934
- }
11935
- if (typeof obj.reasoning_fallback === "boolean") {
11936
- details.push(
11937
- `reasoning_fallback=${obj.reasoning_fallback ? "true" : "false"}`
11938
- );
11939
- }
11940
- if (typeof obj.reasoning_budget_preset === "string") {
11941
- details.push(`reasoning_budget_preset=${obj.reasoning_budget_preset}`);
11942
- }
11943
- if (details.length > 0) {
11944
- return details.join(" ");
11945
- }
11946
- const keys = Object.keys(obj);
11947
- if (keys.length === 0) return "object";
11948
- const shown = keys.slice(0, 4).join(",");
11949
- return keys.length > 4 ? `object(keys=${shown},...)` : `object(keys=${shown})`;
11950
- }
11951
- return typeof value;
11952
- };
11953
- var isAbortLikeError = (error) => error.name === "AbortError" || error.name === "APIUserAbortError" || error.name === "AbortSignal" || /aborted|abort/i.test(error.message);
11954
-
11955
- // src/rpc/resume-context.ts
11956
- import { promises as fs17 } from "fs";
11957
- import path16 from "path";
11958
- var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
11959
- var RESUME_CONTEXT_SCHEMA_VERSION = 1;
11960
- var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
11961
- var MAX_RESUME_DETAIL_LINES = 3;
11962
- var normalizePath2 = (value) => {
11963
- if (typeof value !== "string") return void 0;
11964
- const trimmed = value.trim();
11965
- if (!trimmed) return void 0;
11966
- return path16.resolve(trimmed);
11967
- };
11968
- var normalizeMtime3 = (value) => {
11969
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
11970
- return void 0;
11971
- }
11972
- return Math.trunc(value);
11973
- };
11974
- var normalizeText = (value) => {
11975
- if (typeof value !== "string") return void 0;
11976
- const trimmed = value.trim();
11977
- return trimmed.length > 0 ? trimmed : void 0;
11978
- };
11979
- var normalizeApprovalMode = (value) => {
11980
- if (value === "minimal" || value === "trusted" || value === "full-access") {
11981
- return value;
11982
- }
11983
- return void 0;
11984
- };
11985
- var normalizeTrackedFiles = (value) => {
11986
- if (!Array.isArray(value)) return [];
11987
- const seen = /* @__PURE__ */ new Set();
11988
- const files = [];
11989
- for (const entry of value) {
11990
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
11991
- const record = entry;
11992
- const filePath = normalizePath2(record.path);
11993
- const mtime = normalizeMtime3(record.mtime_ms);
11994
- if (!filePath || mtime === void 0 || seen.has(filePath)) continue;
11995
- seen.add(filePath);
11996
- files.push({ path: filePath, mtime_ms: mtime });
11997
- }
11998
- files.sort((left, right) => left.path.localeCompare(right.path));
11999
- return files;
12000
- };
12001
- var trimDetails = (lines) => {
12002
- if (lines.length <= MAX_RESUME_DETAIL_LINES) {
12003
- return lines;
11719
+ files.sort((left, right) => left.path.localeCompare(right.path));
11720
+ return files;
11721
+ };
11722
+ var trimDetails = (lines) => {
11723
+ if (lines.length <= MAX_RESUME_DETAIL_LINES) {
11724
+ return lines;
12004
11725
  }
12005
11726
  const remaining = lines.length - MAX_RESUME_DETAIL_LINES;
12006
11727
  return [
@@ -12217,112 +11938,509 @@ var buildResumeDiff = async (meta, state, options = {}) => {
12217
11938
  if (currentWorkspaceRoot) {
12218
11939
  contextLines.push(`Current workspace root: ${currentWorkspaceRoot}`);
12219
11940
  }
12220
- if (currentWorkingDir) {
12221
- contextLines.push(`Current working directory: ${currentWorkingDir}`);
11941
+ if (currentWorkingDir) {
11942
+ contextLines.push(`Current working directory: ${currentWorkingDir}`);
11943
+ }
11944
+ if (currentSandboxRoot) {
11945
+ contextLines.push(`Current sandbox root: ${currentSandboxRoot}`);
11946
+ }
11947
+ if (currentApprovalMode) {
11948
+ contextLines.push(`Current approval mode: ${currentApprovalMode}`);
11949
+ }
11950
+ if (currentModelProvider || currentModelName) {
11951
+ contextLines.push(
11952
+ `Current model: ${currentModelProvider ?? "(unknown provider)"}/${currentModelName ?? "(unknown model)"}`
11953
+ );
11954
+ }
11955
+ const detailLines = [];
11956
+ let changed = false;
11957
+ if (!savedContext) {
11958
+ detailLines.push(
11959
+ "Saved session has no structured resume metadata. Treat the current runtime/workspace context as authoritative."
11960
+ );
11961
+ changed = true;
11962
+ } else {
11963
+ const comparePath = (label, savedValue, currentValue) => {
11964
+ if (bestEffortCurrentContext && currentValue === void 0) {
11965
+ return;
11966
+ }
11967
+ if (savedValue === currentValue) return;
11968
+ changed = true;
11969
+ detailLines.push(
11970
+ `${label}: ${savedValue ?? "(unknown)"} -> ${currentValue ?? "(unknown)"}`
11971
+ );
11972
+ };
11973
+ comparePath(
11974
+ "Workspace root changed",
11975
+ savedContext.workspace_root,
11976
+ currentWorkspaceRoot
11977
+ );
11978
+ comparePath(
11979
+ "Working directory changed",
11980
+ savedContext.working_dir,
11981
+ currentWorkingDir
11982
+ );
11983
+ comparePath(
11984
+ "Sandbox root changed",
11985
+ savedContext.sandbox_root,
11986
+ currentSandboxRoot
11987
+ );
11988
+ if (savedContext.approval_mode !== currentApprovalMode && (!bestEffortCurrentContext || currentApprovalMode !== void 0)) {
11989
+ changed = true;
11990
+ detailLines.push(
11991
+ `Approval mode changed: ${savedContext.approval_mode ?? "(unknown)"} -> ${currentApprovalMode ?? "(unknown)"}`
11992
+ );
11993
+ }
11994
+ if ((savedContext.model_provider !== currentModelProvider || savedContext.model_name !== currentModelName) && (!bestEffortCurrentContext || currentModelProvider !== void 0 || currentModelName !== void 0)) {
11995
+ changed = true;
11996
+ detailLines.push(
11997
+ `Model changed: ${savedContext.model_provider ?? "(unknown provider)"}/${savedContext.model_name ?? "(unknown model)"} -> ${currentModelProvider ?? "(unknown provider)"}/${currentModelName ?? "(unknown model)"}`
11998
+ );
11999
+ }
12000
+ if (!(bestEffortCurrentContext && !currentInitialAgentsKnown)) {
12001
+ const agentDiffs = summarizeTrackedFileDiff(
12002
+ "Initial AGENTS",
12003
+ savedContext.initial_agents ?? [],
12004
+ currentAgents
12005
+ );
12006
+ if (agentDiffs.length > 0) {
12007
+ changed = true;
12008
+ detailLines.push(...agentDiffs);
12009
+ }
12010
+ }
12011
+ const skillDiffs = await summarizeCurrentLoadedSkillDiff(
12012
+ savedContext.loaded_skills ?? [],
12013
+ currentLoadedSkills
12014
+ );
12015
+ if (skillDiffs.length > 0) {
12016
+ changed = true;
12017
+ detailLines.push(...skillDiffs);
12018
+ }
12019
+ if (!changed) {
12020
+ detailLines.push(
12021
+ "No material workspace/AGENTS/skill changes were detected from saved resume metadata."
12022
+ );
12023
+ }
12024
+ }
12025
+ if (contextLines.length === 0 && detailLines.length === 0) {
12026
+ return null;
12027
+ }
12028
+ const summaryLines = [
12029
+ "Resume context:",
12030
+ ...contextLines.map((line) => `- ${line}`),
12031
+ ...detailLines.map((line) => `- ${line}`)
12032
+ ];
12033
+ const systemLines = [
12034
+ '<system-reminder type="session.resume.diff">',
12035
+ "Session resumed in current runtime context:",
12036
+ ...contextLines.map((line) => `- ${line}`),
12037
+ ...detailLines.map((line) => `- ${line}`),
12038
+ "Use the current runtime/workspace context for subsequent actions.",
12039
+ "</system-reminder>"
12040
+ ];
12041
+ return {
12042
+ summary: summaryLines.join("\n"),
12043
+ systemReminder: systemLines.join("\n"),
12044
+ changed
12045
+ };
12046
+ };
12047
+
12048
+ // src/rpc/run.ts
12049
+ import {
12050
+ RPC_ERROR_CODE as RPC_ERROR_CODE4
12051
+ } from "@codelia/protocol";
12052
+
12053
+ // src/rpc/client-tool-requests.ts
12054
+ var requestClientToolCall = async (state, params, timeoutMs) => {
12055
+ const id = state.nextUiRequestId();
12056
+ const request = {
12057
+ jsonrpc: "2.0",
12058
+ id,
12059
+ method: "client.tool.call",
12060
+ params
12061
+ };
12062
+ send(request);
12063
+ return await state.waitForUiResponse(id, timeoutMs);
12064
+ };
12065
+
12066
+ // src/tools/client.ts
12067
+ var DEFAULT_TIMEOUT_MS4 = 6e4;
12068
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12069
+ var normalizeClientToolResult = (value) => {
12070
+ if (typeof value === "string") {
12071
+ return { type: "text", text: value };
12072
+ }
12073
+ if (isRecord7(value)) {
12074
+ if (value.type === "text" && typeof value.text === "string") {
12075
+ return { type: "text", text: value.text };
12076
+ }
12077
+ if (value.type === "parts" && Array.isArray(value.parts)) {
12078
+ return { type: "parts", parts: value.parts };
12079
+ }
12080
+ if (value.type === "json" && "value" in value) {
12081
+ return { type: "json", value: value.value };
12082
+ }
12083
+ }
12084
+ return { type: "json", value };
12085
+ };
12086
+ var validateClientToolDefinition = (tool, existingNames) => {
12087
+ if (tool.type !== void 0 && tool.type !== "function") {
12088
+ throw new Error(`unsupported client tool type: ${String(tool.type)}`);
12089
+ }
12090
+ if (!tool.name || !/^[a-zA-Z0-9_-]+$/.test(tool.name)) {
12091
+ throw new Error(`invalid client tool name: ${tool.name}`);
12092
+ }
12093
+ if (existingNames.has(tool.name)) {
12094
+ throw new Error(
12095
+ `client tool name conflicts with existing tool: ${tool.name}`
12096
+ );
12097
+ }
12098
+ if (!tool.description.trim()) {
12099
+ throw new Error(`client tool description is required: ${tool.name}`);
12100
+ }
12101
+ if (!isRecord7(tool.parameters)) {
12102
+ throw new Error(
12103
+ `client tool parameters must be a JSON schema: ${tool.name}`
12104
+ );
12105
+ }
12106
+ if (tool.timeout_ms !== void 0 && (!Number.isFinite(tool.timeout_ms) || tool.timeout_ms <= 0)) {
12107
+ throw new Error(`client tool timeout_ms must be positive: ${tool.name}`);
12108
+ }
12109
+ };
12110
+ var createClientToolAdapters = ({
12111
+ runId,
12112
+ tools,
12113
+ state,
12114
+ existingTools
12115
+ }) => {
12116
+ if (!tools?.length) return [];
12117
+ const existingNames = new Set(existingTools.map((tool) => tool.name));
12118
+ const clientNames = /* @__PURE__ */ new Set();
12119
+ return tools.map((clientTool) => {
12120
+ validateClientToolDefinition(clientTool, existingNames);
12121
+ if (clientNames.has(clientTool.name)) {
12122
+ throw new Error(`duplicate client tool name: ${clientTool.name}`);
12123
+ }
12124
+ clientNames.add(clientTool.name);
12125
+ const timeoutMs = clientTool.timeout_ms ?? DEFAULT_TIMEOUT_MS4;
12126
+ const description = `${clientTool.description.trim()} (origin: runtime client)`;
12127
+ return {
12128
+ name: clientTool.name,
12129
+ description,
12130
+ definition: {
12131
+ name: clientTool.name,
12132
+ description,
12133
+ parameters: clientTool.parameters,
12134
+ strict: clientTool.strict ?? false
12135
+ },
12136
+ executeRaw: async (rawArgsJson) => {
12137
+ let args;
12138
+ try {
12139
+ const parsed = JSON.parse(rawArgsJson);
12140
+ args = isRecord7(parsed) ? parsed : { value: parsed };
12141
+ } catch (error) {
12142
+ throw new Error(
12143
+ `Invalid tool arguments JSON for ${clientTool.name}: ${String(error)}`
12144
+ );
12145
+ }
12146
+ const response = await requestClientToolCall(
12147
+ state,
12148
+ {
12149
+ run_id: runId,
12150
+ name: clientTool.name,
12151
+ arguments: args,
12152
+ raw_arguments: rawArgsJson
12153
+ },
12154
+ timeoutMs
12155
+ );
12156
+ if (!response.ok) {
12157
+ throw new Error(response.error);
12158
+ }
12159
+ return normalizeClientToolResult(response.result);
12160
+ }
12161
+ };
12162
+ });
12163
+ };
12164
+
12165
+ // src/rpc/run-debug.ts
12166
+ import { stringifyContent } from "@codelia/core";
12167
+ var DEBUG_MAX_CONTENT_CHARS = 2e3;
12168
+ var DEBUG_MAX_LOG_CHARS = 2e4;
12169
+ var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
12170
+ var DEBUG_MAX_EVENT_ARGS_CHARS = 2e3;
12171
+ var DEBUG_ERROR_MESSAGE_MAX_CHARS = 2e3;
12172
+ var DEBUG_ERROR_STACK_MAX_CHARS = 8e3;
12173
+ var DEBUG_ERROR_CHAIN_MAX_CHARS = 4e3;
12174
+ var DEBUG_ERROR_EXTRAS_MAX_CHARS = 4e3;
12175
+ var DEBUG_PROVIDER_META_STRING_MAX_CHARS = 80;
12176
+ var truncateText2 = (value, maxChars) => {
12177
+ if (value.length <= maxChars) return value;
12178
+ return `${value.slice(0, maxChars)}...[truncated]`;
12179
+ };
12180
+ var stringifyUnknown = (value) => {
12181
+ try {
12182
+ return JSON.stringify(value);
12183
+ } catch {
12184
+ return String(value);
12185
+ }
12186
+ };
12187
+ var contentToDebugText = (content, maxChars) => {
12188
+ const text = stringifyContent(content, {
12189
+ mode: "log",
12190
+ joiner: "\n",
12191
+ includeOtherPayload: true
12192
+ });
12193
+ return truncateText2(text, maxChars);
12194
+ };
12195
+ var buildCompactionSnapshotLog = (messages) => {
12196
+ const payload = messages.map((message, index) => {
12197
+ if (message.role === "assistant") {
12198
+ return {
12199
+ index,
12200
+ role: message.role,
12201
+ content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS),
12202
+ tool_calls: (message.tool_calls ?? []).map((call) => ({
12203
+ id: call.id,
12204
+ name: call.function.name
12205
+ }))
12206
+ };
12207
+ }
12208
+ if (message.role === "tool") {
12209
+ return {
12210
+ index,
12211
+ role: message.role,
12212
+ tool_name: message.tool_name,
12213
+ tool_call_id: message.tool_call_id,
12214
+ is_error: message.is_error ?? false,
12215
+ content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS)
12216
+ };
12217
+ }
12218
+ if (message.role === "reasoning") {
12219
+ return {
12220
+ index,
12221
+ role: message.role,
12222
+ content: truncateText2(message.content ?? "", DEBUG_MAX_CONTENT_CHARS)
12223
+ };
12224
+ }
12225
+ return {
12226
+ index,
12227
+ role: message.role,
12228
+ content: contentToDebugText(message.content, DEBUG_MAX_CONTENT_CHARS)
12229
+ };
12230
+ });
12231
+ return truncateText2(stringifyUnknown(payload), DEBUG_MAX_LOG_CHARS);
12232
+ };
12233
+ var logCompactionSnapshot = (log2, runId, runtimeAgent, compacted) => {
12234
+ if (!isDebugEnabled()) return;
12235
+ const messages = runtimeAgent.getHistoryMessages();
12236
+ const snapshot = buildCompactionSnapshotLog(messages);
12237
+ log2(
12238
+ `compaction context snapshot run_id=${runId} compacted=${String(compacted)} messages=${messages.length} history=${snapshot}`
12239
+ );
12240
+ };
12241
+ var isTrackedRunEvent = (eventType) => eventType === "tool_call" || eventType === "tool_result" || eventType === "step_start" || eventType === "step_complete" || eventType === "final";
12242
+ var summarizeRunEvent = (event) => {
12243
+ switch (event.type) {
12244
+ case "tool_call": {
12245
+ const tool = typeof event.tool === "string" ? event.tool : "unknown";
12246
+ const toolCallId = typeof event.tool_call_id === "string" ? event.tool_call_id : "unknown";
12247
+ const rawArgs = typeof event.raw_args === "string" ? event.raw_args : stringifyUnknown(event.args);
12248
+ const rawArgsSnippet = truncateText2(rawArgs, DEBUG_MAX_EVENT_ARGS_CHARS);
12249
+ return `type=tool_call tool=${tool} tool_call_id=${toolCallId} raw_args=${stringifyUnknown(rawArgsSnippet)}`;
12250
+ }
12251
+ case "tool_result": {
12252
+ const tool = typeof event.tool === "string" ? event.tool : "unknown";
12253
+ const toolCallId = typeof event.tool_call_id === "string" ? event.tool_call_id : "unknown";
12254
+ const isError = event.is_error === true;
12255
+ const result = typeof event.result === "string" ? truncateText2(event.result, DEBUG_MAX_EVENT_RESULT_CHARS) : truncateText2(
12256
+ stringifyUnknown(event.result),
12257
+ DEBUG_MAX_EVENT_RESULT_CHARS
12258
+ );
12259
+ return `type=tool_result tool=${tool} tool_call_id=${toolCallId} is_error=${String(isError)} result=${stringifyUnknown(result)}`;
12260
+ }
12261
+ case "step_start": {
12262
+ const stepId = typeof event.step_id === "string" ? event.step_id : "unknown";
12263
+ const title = typeof event.title === "string" ? event.title : "unknown";
12264
+ return `type=step_start step_id=${stepId} title=${title}`;
12265
+ }
12266
+ case "step_complete": {
12267
+ const stepId = typeof event.step_id === "string" ? event.step_id : "unknown";
12268
+ const status = typeof event.status === "string" ? event.status : "unknown";
12269
+ const durationMs = typeof event.duration_ms === "number" ? event.duration_ms : -1;
12270
+ return `type=step_complete step_id=${stepId} status=${status} duration_ms=${durationMs}`;
12271
+ }
12272
+ case "final": {
12273
+ const content = typeof event.content === "string" ? event.content : "";
12274
+ return `type=final content_chars=${content.length}`;
12275
+ }
12276
+ default:
12277
+ return `type=${event.type}`;
12278
+ }
12279
+ };
12280
+ var logRunDebug = (log2, runId, message) => {
12281
+ if (!isDebugEnabled()) return;
12282
+ log2(`run debug run_id=${runId} ${message}`);
12283
+ };
12284
+ var normalizeToolCallHistory = (messages) => {
12285
+ const assistantCallIds = /* @__PURE__ */ new Set();
12286
+ const toolOutputCallIds = /* @__PURE__ */ new Set();
12287
+ for (const message of messages) {
12288
+ if (message.role === "assistant") {
12289
+ for (const call of message.tool_calls ?? []) {
12290
+ assistantCallIds.add(call.id);
12291
+ }
12292
+ continue;
12293
+ }
12294
+ if (message.role === "tool") {
12295
+ toolOutputCallIds.add(message.tool_call_id);
12296
+ }
12222
12297
  }
12223
- if (currentSandboxRoot) {
12224
- contextLines.push(`Current sandbox root: ${currentSandboxRoot}`);
12298
+ if (assistantCallIds.size === 0 && toolOutputCallIds.size === 0) {
12299
+ return messages;
12225
12300
  }
12226
- if (currentApprovalMode) {
12227
- contextLines.push(`Current approval mode: ${currentApprovalMode}`);
12301
+ const validCallIds = /* @__PURE__ */ new Set();
12302
+ for (const callId of assistantCallIds) {
12303
+ if (toolOutputCallIds.has(callId)) {
12304
+ validCallIds.add(callId);
12305
+ }
12228
12306
  }
12229
- if (currentModelProvider || currentModelName) {
12230
- contextLines.push(
12231
- `Current model: ${currentModelProvider ?? "(unknown provider)"}/${currentModelName ?? "(unknown model)"}`
12232
- );
12307
+ if (validCallIds.size === assistantCallIds.size && validCallIds.size === toolOutputCallIds.size) {
12308
+ return messages;
12233
12309
  }
12234
- const detailLines = [];
12235
12310
  let changed = false;
12236
- if (!savedContext) {
12237
- detailLines.push(
12238
- "Saved session has no structured resume metadata. Treat the current runtime/workspace context as authoritative."
12239
- );
12240
- changed = true;
12241
- } else {
12242
- const comparePath = (label, savedValue, currentValue) => {
12243
- if (bestEffortCurrentContext && currentValue === void 0) {
12244
- return;
12311
+ const normalized = [];
12312
+ for (const message of messages) {
12313
+ if (message.role === "assistant") {
12314
+ const calls = message.tool_calls ?? [];
12315
+ if (calls.length > 0) {
12316
+ const filteredCalls = calls.filter((call) => validCallIds.has(call.id));
12317
+ if (filteredCalls.length !== calls.length) {
12318
+ changed = true;
12319
+ if (filteredCalls.length === 0) {
12320
+ const next = { ...message };
12321
+ delete next.tool_calls;
12322
+ normalized.push(next);
12323
+ } else {
12324
+ normalized.push({ ...message, tool_calls: filteredCalls });
12325
+ }
12326
+ continue;
12327
+ }
12245
12328
  }
12246
- if (savedValue === currentValue) return;
12329
+ normalized.push(message);
12330
+ continue;
12331
+ }
12332
+ if (message.role === "tool" && !validCallIds.has(message.tool_call_id)) {
12247
12333
  changed = true;
12248
- detailLines.push(
12249
- `${label}: ${savedValue ?? "(unknown)"} -> ${currentValue ?? "(unknown)"}`
12250
- );
12251
- };
12252
- comparePath(
12253
- "Workspace root changed",
12254
- savedContext.workspace_root,
12255
- currentWorkspaceRoot
12334
+ continue;
12335
+ }
12336
+ normalized.push(message);
12337
+ }
12338
+ return changed ? normalized : messages;
12339
+ };
12340
+ var formatErrorForDebugLog = (error) => {
12341
+ const parts = [];
12342
+ parts.push(`name=${error.name}`);
12343
+ parts.push(
12344
+ `message=${truncateText2(error.message, DEBUG_ERROR_MESSAGE_MAX_CHARS)}`
12345
+ );
12346
+ if (error.stack) {
12347
+ parts.push(
12348
+ `stack=${truncateText2(error.stack, DEBUG_ERROR_STACK_MAX_CHARS)}`
12256
12349
  );
12257
- comparePath(
12258
- "Working directory changed",
12259
- savedContext.working_dir,
12260
- currentWorkingDir
12350
+ }
12351
+ const causeChain = [];
12352
+ let depth = 0;
12353
+ let current = error.cause;
12354
+ const seen = /* @__PURE__ */ new Set();
12355
+ while (current !== void 0 && current !== null && depth < 4) {
12356
+ if (seen.has(current)) {
12357
+ causeChain.push("[circular]");
12358
+ break;
12359
+ }
12360
+ seen.add(current);
12361
+ if (current instanceof Error) {
12362
+ causeChain.push(`${current.name}: ${current.message}`);
12363
+ current = current.cause;
12364
+ depth += 1;
12365
+ continue;
12366
+ }
12367
+ causeChain.push(stringifyUnknown(current));
12368
+ break;
12369
+ }
12370
+ if (causeChain.length > 0) {
12371
+ parts.push(
12372
+ `cause_chain=${truncateText2(causeChain.join(" <- "), DEBUG_ERROR_CHAIN_MAX_CHARS)}`
12261
12373
  );
12262
- comparePath(
12263
- "Sandbox root changed",
12264
- savedContext.sandbox_root,
12265
- currentSandboxRoot
12374
+ }
12375
+ const extras = Object.entries(
12376
+ error
12377
+ ).filter(([key]) => key !== "name" && key !== "message" && key !== "stack");
12378
+ if (extras.length > 0) {
12379
+ parts.push(
12380
+ `extras=${truncateText2(
12381
+ stringifyUnknown(Object.fromEntries(extras)),
12382
+ DEBUG_ERROR_EXTRAS_MAX_CHARS
12383
+ )}`
12266
12384
  );
12267
- if (savedContext.approval_mode !== currentApprovalMode && (!bestEffortCurrentContext || currentApprovalMode !== void 0)) {
12268
- changed = true;
12269
- detailLines.push(
12270
- `Approval mode changed: ${savedContext.approval_mode ?? "(unknown)"} -> ${currentApprovalMode ?? "(unknown)"}`
12271
- );
12385
+ }
12386
+ return parts.join(" ");
12387
+ };
12388
+ var summarizeProviderMeta = (value) => {
12389
+ if (value === null || value === void 0) {
12390
+ return null;
12391
+ }
12392
+ if (typeof value === "string") {
12393
+ return value.length > DEBUG_PROVIDER_META_STRING_MAX_CHARS ? `${value.slice(0, DEBUG_PROVIDER_META_STRING_MAX_CHARS - 3)}...` : value;
12394
+ }
12395
+ if (Array.isArray(value)) {
12396
+ return `array(len=${value.length})`;
12397
+ }
12398
+ if (typeof value === "object") {
12399
+ const obj = value;
12400
+ const details = [];
12401
+ if (typeof obj.transport === "string") {
12402
+ details.push(`transport=${obj.transport}`);
12272
12403
  }
12273
- if ((savedContext.model_provider !== currentModelProvider || savedContext.model_name !== currentModelName) && (!bestEffortCurrentContext || currentModelProvider !== void 0 || currentModelName !== void 0)) {
12274
- changed = true;
12275
- detailLines.push(
12276
- `Model changed: ${savedContext.model_provider ?? "(unknown provider)"}/${savedContext.model_name ?? "(unknown model)"} -> ${currentModelProvider ?? "(unknown provider)"}/${currentModelName ?? "(unknown model)"}`
12277
- );
12404
+ if (typeof obj.websocket_mode === "string") {
12405
+ details.push(`websocket_mode=${obj.websocket_mode}`);
12278
12406
  }
12279
- if (!(bestEffortCurrentContext && !currentInitialAgentsKnown)) {
12280
- const agentDiffs = summarizeTrackedFileDiff(
12281
- "Initial AGENTS",
12282
- savedContext.initial_agents ?? [],
12283
- currentAgents
12284
- );
12285
- if (agentDiffs.length > 0) {
12286
- changed = true;
12287
- detailLines.push(...agentDiffs);
12288
- }
12407
+ if (typeof obj.response_id === "string") {
12408
+ details.push(`response_id=${obj.response_id}`);
12289
12409
  }
12290
- const skillDiffs = await summarizeCurrentLoadedSkillDiff(
12291
- savedContext.loaded_skills ?? [],
12292
- currentLoadedSkills
12293
- );
12294
- if (skillDiffs.length > 0) {
12295
- changed = true;
12296
- detailLines.push(...skillDiffs);
12410
+ if (typeof obj.chain_reset === "boolean") {
12411
+ details.push(`chain_reset=${obj.chain_reset ? "true" : "false"}`);
12297
12412
  }
12298
- if (!changed) {
12299
- detailLines.push(
12300
- "No material workspace/AGENTS/skill changes were detected from saved resume metadata."
12413
+ if (typeof obj.fallback_used === "boolean") {
12414
+ details.push(`fallback_used=${obj.fallback_used ? "true" : "false"}`);
12415
+ }
12416
+ if (typeof obj.ws_input_mode === "string") {
12417
+ details.push(`ws_input_mode=${obj.ws_input_mode}`);
12418
+ }
12419
+ if (typeof obj.reasoning_requested === "string") {
12420
+ details.push(`reasoning_requested=${obj.reasoning_requested}`);
12421
+ }
12422
+ if (typeof obj.reasoning_applied === "string") {
12423
+ details.push(`reasoning_applied=${obj.reasoning_applied}`);
12424
+ }
12425
+ if (typeof obj.reasoning_fallback === "boolean") {
12426
+ details.push(
12427
+ `reasoning_fallback=${obj.reasoning_fallback ? "true" : "false"}`
12301
12428
  );
12302
12429
  }
12430
+ if (typeof obj.reasoning_budget_preset === "string") {
12431
+ details.push(`reasoning_budget_preset=${obj.reasoning_budget_preset}`);
12432
+ }
12433
+ if (details.length > 0) {
12434
+ return details.join(" ");
12435
+ }
12436
+ const keys = Object.keys(obj);
12437
+ if (keys.length === 0) return "object";
12438
+ const shown = keys.slice(0, 4).join(",");
12439
+ return keys.length > 4 ? `object(keys=${shown},...)` : `object(keys=${shown})`;
12303
12440
  }
12304
- if (contextLines.length === 0 && detailLines.length === 0) {
12305
- return null;
12306
- }
12307
- const summaryLines = [
12308
- "Resume context:",
12309
- ...contextLines.map((line) => `- ${line}`),
12310
- ...detailLines.map((line) => `- ${line}`)
12311
- ];
12312
- const systemLines = [
12313
- '<system-reminder type="session.resume.diff">',
12314
- "Session resumed in current runtime context:",
12315
- ...contextLines.map((line) => `- ${line}`),
12316
- ...detailLines.map((line) => `- ${line}`),
12317
- "Use the current runtime/workspace context for subsequent actions.",
12318
- "</system-reminder>"
12319
- ];
12320
- return {
12321
- summary: summaryLines.join("\n"),
12322
- systemReminder: systemLines.join("\n"),
12323
- changed
12324
- };
12441
+ return typeof value;
12325
12442
  };
12443
+ var isAbortLikeError = (error) => error.name === "AbortError" || error.name === "APIUserAbortError" || error.name === "AbortSignal" || /aborted|abort/i.test(error.message);
12326
12444
 
12327
12445
  // src/rpc/skill-mentions.ts
12328
12446
  var SKILL_MENTION_PATTERN = /\$([a-z0-9]+(?:-[a-z0-9]+)*)/g;
@@ -12663,6 +12781,24 @@ var createRunHandlers = ({
12663
12781
  };
12664
12782
  }
12665
12783
  const runId = state.nextRunId();
12784
+ let clientTools;
12785
+ try {
12786
+ clientTools = createClientToolAdapters({
12787
+ runId,
12788
+ tools: params.tools,
12789
+ state,
12790
+ existingTools: state.tools ?? []
12791
+ });
12792
+ state.autoApprovedClientToolNames = new Set(
12793
+ (params.tools ?? []).filter((tool) => tool.approval === "never").map((tool) => tool.name)
12794
+ );
12795
+ } catch (error) {
12796
+ sendError(id, {
12797
+ code: RPC_ERROR_CODE4.INVALID_PARAMS,
12798
+ message: String(error)
12799
+ });
12800
+ return;
12801
+ }
12666
12802
  const startedAt = nowIso5();
12667
12803
  state.beginRun(runId, params.ui_context ?? state.lastUiContext);
12668
12804
  const runAbortController = new AbortController();
@@ -12797,7 +12933,13 @@ var createRunHandlers = ({
12797
12933
  ...modelConfig.fast !== void 0 ? { fast: modelConfig.fast } : {}
12798
12934
  } : void 0,
12799
12935
  prompts: state.systemPrompt ? { system: state.systemPrompt } : void 0,
12800
- tools: state.toolDefinitions ? { definitions: state.toolDefinitions, source: "runtime" } : void 0,
12936
+ tools: state.toolDefinitions ? {
12937
+ definitions: [
12938
+ ...state.toolDefinitions,
12939
+ ...clientTools.map((tool) => tool.definition)
12940
+ ],
12941
+ source: clientTools.length ? "runtime+client" : "runtime"
12942
+ } : void 0,
12801
12943
  runtime: {
12802
12944
  cwd: state.lastUiContext?.cwd,
12803
12945
  os: process.platform,
@@ -12814,7 +12956,10 @@ var createRunHandlers = ({
12814
12956
  ui_context: params.ui_context,
12815
12957
  meta: params.meta
12816
12958
  });
12817
- const result = { run_id: runId };
12959
+ const result = {
12960
+ run_id: runId,
12961
+ ...sessionStore.filePath ? { session_log_path: sessionStore.filePath } : {}
12962
+ };
12818
12963
  sendResult(id, result);
12819
12964
  log2(`run.start ${runId}`);
12820
12965
  emitRunStatus(runId, "running");
@@ -12887,7 +13032,9 @@ var createRunHandlers = ({
12887
13032
  for await (const event of runtimeAgent.runStream(normalizedInput, {
12888
13033
  session,
12889
13034
  signal: runAbortController.signal,
12890
- forceCompaction: params.force_compaction
13035
+ forceCompaction: params.force_compaction,
13036
+ tools: clientTools,
13037
+ toolChoice: params.tool_choice
12891
13038
  })) {
12892
13039
  if (state.cancelRequested) {
12893
13040
  break;
@@ -14589,6 +14736,7 @@ var RuntimeState = class {
14589
14736
  executionEnvironmentDebugLogged = false;
14590
14737
  toolDefinitions = null;
14591
14738
  tools = null;
14739
+ autoApprovedClientToolNames = /* @__PURE__ */ new Set();
14592
14740
  sessionId = null;
14593
14741
  sessionMeta = null;
14594
14742
  sessionAppend = null;
@@ -14624,6 +14772,7 @@ var RuntimeState = class {
14624
14772
  }
14625
14773
  this.cancelRequested = false;
14626
14774
  this.lastContextLeftPercent = null;
14775
+ this.autoApprovedClientToolNames.clear();
14627
14776
  this.runSeq.delete(runId);
14628
14777
  if (this.activeRunId === null) {
14629
14778
  this.sessionAppend = null;