@cydm/pie 2.7.20 → 2.8.1

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 (40) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/README.md +117 -0
  3. package/dist/builtin/extensions/ask-user/index.js +4 -3
  4. package/dist/builtin/extensions/cron/index.js +299 -39
  5. package/dist/builtin/extensions/im-forward/README.md +297 -0
  6. package/dist/builtin/extensions/im-forward/index.js +315 -27
  7. package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
  8. package/dist/builtin/extensions/memory/index.js +515 -0
  9. package/dist/builtin/extensions/memory/package.json +19 -0
  10. package/dist/builtin/extensions/pie-ipc/README.md +21 -0
  11. package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
  12. package/dist/builtin/extensions/plan-mode/index.js +150 -82
  13. package/dist/builtin/extensions/subagent/README.md +315 -0
  14. package/dist/builtin/extensions/subagent/index.js +8 -5
  15. package/dist/builtin/extensions/todo/index.js +4 -3
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  18. package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
  19. package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  22. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  23. package/dist/chunks/{chunk-X7UO6BA6.js → chunk-3BC5KGDQ.js} +451 -162
  24. package/dist/chunks/chunk-3NHP7HK5.js +298 -0
  25. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  26. package/dist/chunks/{chunk-TGCI5M6R.js → chunk-GDIYSMTS.js} +22 -142
  27. package/dist/chunks/{chunk-2H2DD22Z.js → chunk-GH4VW2OT.js} +1 -1
  28. package/dist/chunks/chunk-ILUHTKF3.js +149 -0
  29. package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-PK72LVWQ.js} +11841 -16501
  30. package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
  31. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  32. package/dist/chunks/config-74AUVDLT.js +46 -0
  33. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  34. package/dist/chunks/src-66XSMIAM.js +134 -0
  35. package/dist/chunks/src-BPSQMSSC.js +431 -0
  36. package/dist/chunks/src-OPPYTPWG.js +285 -0
  37. package/dist/chunks/{src-GX4UBAYF.js → src-YG5M2H44.js} +2 -2
  38. package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-JBWXKOQA.js} +1 -1
  39. package/dist/cli.js +986 -2292
  40. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -1,8 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
3
+ import {
4
+ ModelRegistry
5
+ } from "./chunks/chunk-YRR6C43W.js";
6
+ import {
7
+ distillWorkerLogPath,
8
+ readDistillWorkerLog,
9
+ runDistillAuto,
10
+ runDistillWorkerMain,
11
+ spawnDistillAutoWorker,
12
+ spawnDistillWorker
13
+ } from "./chunks/chunk-3NHP7HK5.js";
3
14
  import {
4
15
  CLI_RETRY_MAX_RETRIES,
5
- VERSION,
6
16
  classifyCliFailure,
7
17
  cleanupBashOutputArtifacts,
8
18
  createBashTool,
@@ -12,6 +22,18 @@ import {
12
22
  createTraceTransportSink,
13
23
  createTransportDiagnosticsStreamFn,
14
24
  formatSize,
25
+ isCliContextOverflowError,
26
+ isCliRetryableError,
27
+ logTransportLifecycle,
28
+ setYoloGrantListener,
29
+ truncateHeadTail
30
+ } from "./chunks/chunk-GDIYSMTS.js";
31
+ import {
32
+ AuthStorage,
33
+ FileAuthStorageBackend
34
+ } from "./chunks/chunk-6DNYGVZP.js";
35
+ import {
36
+ VERSION,
15
37
  getAgentDir,
16
38
  getBuiltinDir,
17
39
  getConfigDir,
@@ -23,50 +45,57 @@ import {
23
45
  getSessionsDir,
24
46
  getSettingsPath,
25
47
  getThemesDir,
26
- isCliContextOverflowError,
27
- isCliRetryableError,
28
- logTransportLifecycle,
29
- migrateConfigFromAgentDir,
30
- setYoloGrantListener,
31
- truncateHeadTail
32
- } from "./chunks/chunk-TGCI5M6R.js";
48
+ migrateConfigFromAgentDir
49
+ } from "./chunks/chunk-ILUHTKF3.js";
33
50
  import {
34
- AGENTS_CONTEXT_FILE_NAME,
35
- AgentSessionController,
36
- AttentionCoordinator,
37
51
  BUILTIN_TOOL_CAPABILITY_METADATA,
38
- DEFAULT_COMPACTION_CONFIG,
39
- ExtensionResourceScope,
40
- FileSessionStore,
41
- SessionTraceSnapshotWriter,
52
+ MemoryStore,
42
53
  abortExecutionState,
43
- attachAgentEventsToSessionTrace,
44
54
  buildExecutionReminder,
45
- buildProjectContextSection,
46
55
  buildToolsPromptSection,
47
- calculateTotalTokens,
56
+ consumptionSummary,
48
57
  continueExecutionState,
49
- createCompactionSummary,
50
58
  createEmptyExecutionState,
51
59
  createExecutionStateStore,
52
60
  createFileObservationState,
53
- createHostEnvelopeProjectorRegistry,
54
61
  createPolicyEnforcedTools,
55
62
  createReadFileUnderstandingHandler,
56
63
  createSearchContextTool,
57
- createSessionManager,
58
64
  createSharedFileSystemTools,
59
65
  createSharedWebSearchTool,
60
66
  createTodoWidgetView,
61
67
  createTwoFilesPatch,
62
- estimateContextTokens,
63
- estimateTokens,
64
68
  evaluateTodoClosureAfterCompletedTurn,
65
69
  evaluateTodoClosureAfterFailedTurn,
70
+ formatSkillSummariesForPrompt,
71
+ isToolAllowedInPlanMode,
72
+ maybeAdvanceTodoExecutionState,
73
+ modalityForReadFileUnderstandingKind,
74
+ pauseExecutionState,
75
+ restoreExecutionState,
76
+ shouldPreserveExecutionStateForUserText,
77
+ supersedeExecutionState,
78
+ todayKey
79
+ } from "./chunks/chunk-PK72LVWQ.js";
80
+ import {
81
+ AGENTS_CONTEXT_FILE_NAME,
82
+ AgentSessionController,
83
+ AttentionCoordinator,
84
+ DEFAULT_COMPACTION_CONFIG,
85
+ ExtensionResourceScope,
86
+ FileSessionStore,
87
+ SessionTraceSnapshotWriter,
88
+ attachAgentEventsToSessionTrace,
89
+ buildProjectContextSection,
90
+ calculateTotalTokens,
91
+ createCompactionSummary,
92
+ createHostEnvelopeProjectorRegistry,
93
+ createSessionManager,
94
+ estimateContextTokens,
95
+ estimateTokens,
66
96
  extensionFallbackName,
67
97
  extractExtensionSettings,
68
98
  findFirstKeptEntrySummaryId,
69
- formatSkillSummariesForPrompt,
70
99
  generateEntryId,
71
100
  getAutoCompactTokenLimit,
72
101
  getExtensionEnablementEntry,
@@ -76,30 +105,23 @@ import {
76
105
  isCompactSummaryMessage,
77
106
  isExtensionEnabled,
78
107
  isHostContextBlock,
79
- isToolAllowedInPlanMode,
80
- maybeAdvanceTodoExecutionState,
81
- modalityForReadFileUnderstandingKind,
82
- pauseExecutionState,
108
+ manifestDefaultLayer,
83
109
  prepareSessionCompaction,
84
110
  projectHostEnvelopes,
85
111
  registerInteractionHandler,
86
112
  requestInteraction,
87
113
  resolveExtensionIdentity,
88
- restoreExecutionState,
89
114
  setEnablementInMap,
90
115
  setExtensionEnabledInSettings,
91
- shouldPreserveExecutionStateForUserText,
92
- supersedeExecutionState,
93
116
  verifyPreparedCompactionCommit
94
- } from "./chunks/chunk-UDCGB3LZ.js";
95
- import "./chunks/chunk-2H2DD22Z.js";
117
+ } from "./chunks/chunk-RSL7E4R7.js";
118
+ import "./chunks/chunk-GH4VW2OT.js";
96
119
  import {
97
120
  Deref,
98
121
  Errors,
99
122
  ExtendsUndefinedCheck,
100
123
  HasTransform,
101
124
  Hash,
102
- MODEL_CLASS_FALLBACK_ORDER,
103
125
  TransformDecode,
104
126
  TransformDecodeCheckError,
105
127
  TransformEncode,
@@ -109,13 +131,10 @@ import {
109
131
  format_exports,
110
132
  getLogger,
111
133
  getModelCacheCapability,
112
- modelSupportsToolPurpose,
113
- requiredCapabilityForToolPurpose,
114
134
  setLogger,
115
- sortToolModelCandidatesByCapability,
116
135
  streamSimple,
117
136
  type_exports
118
- } from "./chunks/chunk-X7UO6BA6.js";
137
+ } from "./chunks/chunk-3BC5KGDQ.js";
119
138
  import {
120
139
  IsArray,
121
140
  IsBigInt,
@@ -1943,7 +1962,7 @@ var require_core = __commonJS({
1943
1962
  return match && match.index === 0;
1944
1963
  }
1945
1964
  var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
1946
- function join24(regexps, separator = "|") {
1965
+ function join23(regexps, separator = "|") {
1947
1966
  let numCaptures = 0;
1948
1967
  return regexps.map((regex) => {
1949
1968
  numCaptures += 1;
@@ -2247,7 +2266,7 @@ var require_core = __commonJS({
2247
2266
  this.exec = () => null;
2248
2267
  }
2249
2268
  const terminators = this.regexes.map((el) => el[1]);
2250
- this.matcherRe = langRe(join24(terminators), true);
2269
+ this.matcherRe = langRe(join23(terminators), true);
2251
2270
  this.lastIndex = 0;
2252
2271
  }
2253
2272
  /** @param {string} s */
@@ -34339,13 +34358,13 @@ var require_yaml = __commonJS({
34339
34358
  { begin: /[^\s,{}[\]]+/ }
34340
34359
  ]
34341
34360
  });
34342
- var DATE_RE = "[0-9]{4}(-[0-9][0-9]){0,2}";
34361
+ var DATE_RE2 = "[0-9]{4}(-[0-9][0-9]){0,2}";
34343
34362
  var TIME_RE = "([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?";
34344
34363
  var FRACTION_RE = "(\\.[0-9]*)?";
34345
34364
  var ZONE_RE = "([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?";
34346
34365
  var TIMESTAMP = {
34347
34366
  className: "number",
34348
- begin: "\\b" + DATE_RE + TIME_RE + FRACTION_RE + ZONE_RE + "\\b"
34367
+ begin: "\\b" + DATE_RE2 + TIME_RE + FRACTION_RE + ZONE_RE + "\\b"
34349
34368
  };
34350
34369
  var VALUE_CONTAINER = {
34351
34370
  end: ",",
@@ -47939,10 +47958,10 @@ var require_resolve_block_map = __commonJS({
47939
47958
  let offset = bm.offset;
47940
47959
  let commentEnd = null;
47941
47960
  for (const collItem of bm.items) {
47942
- const { start, key, sep: sep3, value } = collItem;
47961
+ const { start, key, sep: sep2, value } = collItem;
47943
47962
  const keyProps = resolveProps.resolveProps(start, {
47944
47963
  indicator: "explicit-key-ind",
47945
- next: key ?? sep3?.[0],
47964
+ next: key ?? sep2?.[0],
47946
47965
  offset,
47947
47966
  onError,
47948
47967
  parentIndent: bm.indent,
@@ -47956,7 +47975,7 @@ var require_resolve_block_map = __commonJS({
47956
47975
  else if ("indent" in key && key.indent !== bm.indent)
47957
47976
  onError(offset, "BAD_INDENT", startColMsg);
47958
47977
  }
47959
- if (!keyProps.anchor && !keyProps.tag && !sep3) {
47978
+ if (!keyProps.anchor && !keyProps.tag && !sep2) {
47960
47979
  commentEnd = keyProps.end;
47961
47980
  if (keyProps.comment) {
47962
47981
  if (map.comment)
@@ -47980,7 +47999,7 @@ var require_resolve_block_map = __commonJS({
47980
47999
  ctx.atKey = false;
47981
48000
  if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
47982
48001
  onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
47983
- const valueProps = resolveProps.resolveProps(sep3 ?? [], {
48002
+ const valueProps = resolveProps.resolveProps(sep2 ?? [], {
47984
48003
  indicator: "map-value-ind",
47985
48004
  next: value,
47986
48005
  offset: keyNode.range[2],
@@ -47996,7 +48015,7 @@ var require_resolve_block_map = __commonJS({
47996
48015
  if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
47997
48016
  onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
47998
48017
  }
47999
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep3, null, valueProps, onError);
48018
+ const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep2, null, valueProps, onError);
48000
48019
  if (ctx.schema.compat)
48001
48020
  utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
48002
48021
  offset = valueNode.range[2];
@@ -48087,7 +48106,7 @@ var require_resolve_end = __commonJS({
48087
48106
  let comment = "";
48088
48107
  if (end) {
48089
48108
  let hasSpace = false;
48090
- let sep3 = "";
48109
+ let sep2 = "";
48091
48110
  for (const token of end) {
48092
48111
  const { source, type } = token;
48093
48112
  switch (type) {
@@ -48101,13 +48120,13 @@ var require_resolve_end = __commonJS({
48101
48120
  if (!comment)
48102
48121
  comment = cb;
48103
48122
  else
48104
- comment += sep3 + cb;
48105
- sep3 = "";
48123
+ comment += sep2 + cb;
48124
+ sep2 = "";
48106
48125
  break;
48107
48126
  }
48108
48127
  case "newline":
48109
48128
  if (comment)
48110
- sep3 += source;
48129
+ sep2 += source;
48111
48130
  hasSpace = true;
48112
48131
  break;
48113
48132
  default:
@@ -48150,18 +48169,18 @@ var require_resolve_flow_collection = __commonJS({
48150
48169
  let offset = fc.offset + fc.start.source.length;
48151
48170
  for (let i = 0; i < fc.items.length; ++i) {
48152
48171
  const collItem = fc.items[i];
48153
- const { start, key, sep: sep3, value } = collItem;
48172
+ const { start, key, sep: sep2, value } = collItem;
48154
48173
  const props = resolveProps.resolveProps(start, {
48155
48174
  flow: fcName,
48156
48175
  indicator: "explicit-key-ind",
48157
- next: key ?? sep3?.[0],
48176
+ next: key ?? sep2?.[0],
48158
48177
  offset,
48159
48178
  onError,
48160
48179
  parentIndent: fc.indent,
48161
48180
  startOnNewline: false
48162
48181
  });
48163
48182
  if (!props.found) {
48164
- if (!props.anchor && !props.tag && !sep3 && !value) {
48183
+ if (!props.anchor && !props.tag && !sep2 && !value) {
48165
48184
  if (i === 0 && props.comma)
48166
48185
  onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
48167
48186
  else if (i < fc.items.length - 1)
@@ -48215,8 +48234,8 @@ var require_resolve_flow_collection = __commonJS({
48215
48234
  }
48216
48235
  }
48217
48236
  }
48218
- if (!isMap && !sep3 && !props.found) {
48219
- const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep3, null, props, onError);
48237
+ if (!isMap && !sep2 && !props.found) {
48238
+ const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep2, null, props, onError);
48220
48239
  coll.items.push(valueNode);
48221
48240
  offset = valueNode.range[2];
48222
48241
  if (isBlock(value))
@@ -48228,7 +48247,7 @@ var require_resolve_flow_collection = __commonJS({
48228
48247
  if (isBlock(key))
48229
48248
  onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
48230
48249
  ctx.atKey = false;
48231
- const valueProps = resolveProps.resolveProps(sep3 ?? [], {
48250
+ const valueProps = resolveProps.resolveProps(sep2 ?? [], {
48232
48251
  flow: fcName,
48233
48252
  indicator: "map-value-ind",
48234
48253
  next: value,
@@ -48239,8 +48258,8 @@ var require_resolve_flow_collection = __commonJS({
48239
48258
  });
48240
48259
  if (valueProps.found) {
48241
48260
  if (!isMap && !props.found && ctx.options.strict) {
48242
- if (sep3)
48243
- for (const st of sep3) {
48261
+ if (sep2)
48262
+ for (const st of sep2) {
48244
48263
  if (st === valueProps.found)
48245
48264
  break;
48246
48265
  if (st.type === "newline") {
@@ -48257,7 +48276,7 @@ var require_resolve_flow_collection = __commonJS({
48257
48276
  else
48258
48277
  onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
48259
48278
  }
48260
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep3, null, valueProps, onError) : null;
48279
+ const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep2, null, valueProps, onError) : null;
48261
48280
  if (valueNode) {
48262
48281
  if (isBlock(value))
48263
48282
  onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
@@ -48437,7 +48456,7 @@ var require_resolve_block_scalar = __commonJS({
48437
48456
  chompStart = i + 1;
48438
48457
  }
48439
48458
  let value = "";
48440
- let sep3 = "";
48459
+ let sep2 = "";
48441
48460
  let prevMoreIndented = false;
48442
48461
  for (let i = 0; i < contentStart; ++i)
48443
48462
  value += lines[i][0].slice(trimIndent) + "\n";
@@ -48454,24 +48473,24 @@ var require_resolve_block_scalar = __commonJS({
48454
48473
  indent = "";
48455
48474
  }
48456
48475
  if (type === Scalar.Scalar.BLOCK_LITERAL) {
48457
- value += sep3 + indent.slice(trimIndent) + content;
48458
- sep3 = "\n";
48476
+ value += sep2 + indent.slice(trimIndent) + content;
48477
+ sep2 = "\n";
48459
48478
  } else if (indent.length > trimIndent || content[0] === " ") {
48460
- if (sep3 === " ")
48461
- sep3 = "\n";
48462
- else if (!prevMoreIndented && sep3 === "\n")
48463
- sep3 = "\n\n";
48464
- value += sep3 + indent.slice(trimIndent) + content;
48465
- sep3 = "\n";
48479
+ if (sep2 === " ")
48480
+ sep2 = "\n";
48481
+ else if (!prevMoreIndented && sep2 === "\n")
48482
+ sep2 = "\n\n";
48483
+ value += sep2 + indent.slice(trimIndent) + content;
48484
+ sep2 = "\n";
48466
48485
  prevMoreIndented = true;
48467
48486
  } else if (content === "") {
48468
- if (sep3 === "\n")
48487
+ if (sep2 === "\n")
48469
48488
  value += "\n";
48470
48489
  else
48471
- sep3 = "\n";
48490
+ sep2 = "\n";
48472
48491
  } else {
48473
- value += sep3 + content;
48474
- sep3 = " ";
48492
+ value += sep2 + content;
48493
+ sep2 = " ";
48475
48494
  prevMoreIndented = false;
48476
48495
  }
48477
48496
  }
@@ -48653,25 +48672,25 @@ var require_resolve_flow_scalar = __commonJS({
48653
48672
  if (!match)
48654
48673
  return source;
48655
48674
  let res = match[1];
48656
- let sep3 = " ";
48675
+ let sep2 = " ";
48657
48676
  let pos = first.lastIndex;
48658
48677
  line.lastIndex = pos;
48659
48678
  while (match = line.exec(source)) {
48660
48679
  if (match[1] === "") {
48661
- if (sep3 === "\n")
48662
- res += sep3;
48680
+ if (sep2 === "\n")
48681
+ res += sep2;
48663
48682
  else
48664
- sep3 = "\n";
48683
+ sep2 = "\n";
48665
48684
  } else {
48666
- res += sep3 + match[1];
48667
- sep3 = " ";
48685
+ res += sep2 + match[1];
48686
+ sep2 = " ";
48668
48687
  }
48669
48688
  pos = line.lastIndex;
48670
48689
  }
48671
48690
  const last = /[ \t]*(.*)/sy;
48672
48691
  last.lastIndex = pos;
48673
48692
  match = last.exec(source);
48674
- return res + sep3 + (match?.[1] ?? "");
48693
+ return res + sep2 + (match?.[1] ?? "");
48675
48694
  }
48676
48695
  function doubleQuotedValue(source, onError) {
48677
48696
  let res = "";
@@ -49478,14 +49497,14 @@ var require_cst_stringify = __commonJS({
49478
49497
  }
49479
49498
  }
49480
49499
  }
49481
- function stringifyItem({ start, key, sep: sep3, value }) {
49500
+ function stringifyItem({ start, key, sep: sep2, value }) {
49482
49501
  let res = "";
49483
49502
  for (const st of start)
49484
49503
  res += st.source;
49485
49504
  if (key)
49486
49505
  res += stringifyToken(key);
49487
- if (sep3)
49488
- for (const st of sep3)
49506
+ if (sep2)
49507
+ for (const st of sep2)
49489
49508
  res += st.source;
49490
49509
  if (value)
49491
49510
  res += stringifyToken(value);
@@ -50635,18 +50654,18 @@ var require_parser2 = __commonJS({
50635
50654
  if (this.type === "map-value-ind") {
50636
50655
  const prev = getPrevProps(this.peek(2));
50637
50656
  const start = getFirstKeyStartProps(prev);
50638
- let sep3;
50657
+ let sep2;
50639
50658
  if (scalar.end) {
50640
- sep3 = scalar.end;
50641
- sep3.push(this.sourceToken);
50659
+ sep2 = scalar.end;
50660
+ sep2.push(this.sourceToken);
50642
50661
  delete scalar.end;
50643
50662
  } else
50644
- sep3 = [this.sourceToken];
50663
+ sep2 = [this.sourceToken];
50645
50664
  const map = {
50646
50665
  type: "block-map",
50647
50666
  offset: scalar.offset,
50648
50667
  indent: scalar.indent,
50649
- items: [{ start, key: scalar, sep: sep3 }]
50668
+ items: [{ start, key: scalar, sep: sep2 }]
50650
50669
  };
50651
50670
  this.onKeyLine = true;
50652
50671
  this.stack[this.stack.length - 1] = map;
@@ -50799,15 +50818,15 @@ var require_parser2 = __commonJS({
50799
50818
  } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
50800
50819
  const start2 = getFirstKeyStartProps(it.start);
50801
50820
  const key = it.key;
50802
- const sep3 = it.sep;
50803
- sep3.push(this.sourceToken);
50821
+ const sep2 = it.sep;
50822
+ sep2.push(this.sourceToken);
50804
50823
  delete it.key;
50805
50824
  delete it.sep;
50806
50825
  this.stack.push({
50807
50826
  type: "block-map",
50808
50827
  offset: this.offset,
50809
50828
  indent: this.indent,
50810
- items: [{ start: start2, key, sep: sep3 }]
50829
+ items: [{ start: start2, key, sep: sep2 }]
50811
50830
  });
50812
50831
  } else if (start.length > 0) {
50813
50832
  it.sep = it.sep.concat(start, this.sourceToken);
@@ -51001,13 +51020,13 @@ var require_parser2 = __commonJS({
51001
51020
  const prev = getPrevProps(parent);
51002
51021
  const start = getFirstKeyStartProps(prev);
51003
51022
  fixFlowSeqItems(fc);
51004
- const sep3 = fc.end.splice(1, fc.end.length);
51005
- sep3.push(this.sourceToken);
51023
+ const sep2 = fc.end.splice(1, fc.end.length);
51024
+ sep2.push(this.sourceToken);
51006
51025
  const map = {
51007
51026
  type: "block-map",
51008
51027
  offset: fc.offset,
51009
51028
  indent: fc.indent,
51010
- items: [{ start, key: fc, sep: sep3 }]
51029
+ items: [{ start, key: fc, sep: sep2 }]
51011
51030
  };
51012
51031
  this.onKeyLine = true;
51013
51032
  this.stack[this.stack.length - 1] = map;
@@ -51298,6 +51317,7 @@ function parseCliInvocation(args) {
51298
51317
  let command;
51299
51318
  let showHelp2 = false;
51300
51319
  let testCommand;
51320
+ let sessionId;
51301
51321
  const positionals = [];
51302
51322
  for (let i = 0; i < args.length; i += 1) {
51303
51323
  const arg = args[i];
@@ -51317,6 +51337,18 @@ function parseCliInvocation(args) {
51317
51337
  }
51318
51338
  continue;
51319
51339
  }
51340
+ if (arg === "--session-id") {
51341
+ const next = args[i + 1];
51342
+ if (next && !next.startsWith("-")) {
51343
+ sessionId = next;
51344
+ i += 1;
51345
+ }
51346
+ continue;
51347
+ }
51348
+ if (arg.startsWith("--session-id=")) {
51349
+ sessionId = arg.slice("--session-id=".length);
51350
+ continue;
51351
+ }
51320
51352
  if (FLAGS_WITH_VALUES.has(arg)) {
51321
51353
  i += 1;
51322
51354
  continue;
@@ -51336,11 +51368,15 @@ function parseCliInvocation(args) {
51336
51368
  return { showHelp: true };
51337
51369
  }
51338
51370
  if (testCommand) {
51339
- return { showHelp: false, testCommand };
51371
+ return sessionId !== void 0 ? { showHelp: false, testCommand, sessionId } : { showHelp: false, testCommand };
51372
+ }
51373
+ const initialPrompt = positionals.join(" ").trim() || void 0;
51374
+ if (sessionId !== void 0) {
51375
+ return { showHelp: false, initialPrompt, sessionId };
51340
51376
  }
51341
51377
  return {
51342
51378
  showHelp: false,
51343
- initialPrompt: positionals.join(" ").trim() || void 0
51379
+ initialPrompt
51344
51380
  };
51345
51381
  }
51346
51382
  function parseRepeatedFlag(args, flag) {
@@ -51702,1968 +51738,14 @@ function installInteractiveConsoleInterception(runtimeLogger) {
51702
51738
  // src/doctor.ts
51703
51739
  import { spawnSync } from "node:child_process";
51704
51740
  import { createRequire } from "node:module";
51705
- import * as fs5 from "node:fs";
51741
+ import * as fs3 from "node:fs";
51706
51742
  import * as os from "node:os";
51707
- import * as path5 from "node:path";
51743
+ import * as path3 from "node:path";
51708
51744
  import { delimiter } from "node:path";
51709
51745
 
51710
- // src/core/auth-storage.ts
51746
+ // src/core/settings-manager.ts
51711
51747
  import * as fs2 from "fs";
51712
51748
  import * as path2 from "path";
51713
- var AUTH_LOCK_WRITE_GRACE_MS = 1e3;
51714
- var DEFAULT_AUTH_LOCK_WAIT_MS = 2e3;
51715
- var OAUTH_EXPIRY_SKEW_MS = 3e4;
51716
- function syncSleepMs(ms) {
51717
- if (ms <= 0) return;
51718
- const cell = new Int32Array(new SharedArrayBuffer(4));
51719
- Atomics.wait(cell, 0, 0, ms);
51720
- }
51721
- function processIsAlive(pid) {
51722
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
51723
- try {
51724
- process.kill(pid, 0);
51725
- return true;
51726
- } catch (error) {
51727
- return error.code === "EPERM";
51728
- }
51729
- }
51730
- var InMemoryAuthStorageBackend = class {
51731
- snapshot = { oauth: {} };
51732
- read() {
51733
- return { oauth: { ...this.snapshot.oauth } };
51734
- }
51735
- write(snapshot) {
51736
- this.snapshot = { oauth: { ...snapshot.oauth } };
51737
- }
51738
- };
51739
- var AUTH_FILE_VERSION = 1;
51740
- var FileAuthStorageBackend = class {
51741
- constructor(authPath = path2.join(getConfigDir(), "auth.json"), lockWaitMs = DEFAULT_AUTH_LOCK_WAIT_MS) {
51742
- this.authPath = authPath;
51743
- this.lockWaitMs = lockWaitMs;
51744
- }
51745
- authPath;
51746
- lockWaitMs;
51747
- errors = [];
51748
- read() {
51749
- try {
51750
- if (!fs2.existsSync(this.authPath)) return { oauth: {} };
51751
- const raw = JSON.parse(fs2.readFileSync(this.authPath, "utf8"));
51752
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { oauth: {} };
51753
- const oauth = raw.oauth;
51754
- if (!oauth || typeof oauth !== "object" || Array.isArray(oauth)) return { oauth: {} };
51755
- return { oauth: { ...oauth } };
51756
- } catch (error) {
51757
- this.errors.push(error instanceof Error ? error : new Error(String(error)));
51758
- return { oauth: {} };
51759
- }
51760
- }
51761
- /** A lock whose owner is gone (or that never got populated) may be reclaimed. */
51762
- lockIsStale(lockPath) {
51763
- const stat2 = fs2.lstatSync(lockPath);
51764
- if (stat2.isSymbolicLink() || !stat2.isFile()) return true;
51765
- let owner;
51766
- try {
51767
- owner = JSON.parse(fs2.readFileSync(lockPath, "utf8"));
51768
- } catch {
51769
- }
51770
- const age = Date.now() - stat2.mtimeMs;
51771
- const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
51772
- if (validOwner && processIsAlive(Number(owner.pid))) return false;
51773
- return validOwner || age > AUTH_LOCK_WRITE_GRACE_MS;
51774
- }
51775
- /** Atomically claim a stale lock via hard-link identity comparison before removing it. */
51776
- reclaimStaleLock(lockPath) {
51777
- if (!this.lockIsStale(lockPath)) return false;
51778
- const claimPath = `${lockPath}.reclaim-${process.pid}-${Math.random().toString(36).slice(2)}`;
51779
- try {
51780
- fs2.linkSync(lockPath, claimPath);
51781
- const claimed = fs2.lstatSync(claimPath);
51782
- const current = fs2.lstatSync(lockPath);
51783
- if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile()) return false;
51784
- if (claimed.dev !== current.dev || claimed.ino !== current.ino) return false;
51785
- fs2.unlinkSync(lockPath);
51786
- return true;
51787
- } catch (error) {
51788
- const code = error.code;
51789
- if (code === "ENOENT" || code === "EEXIST") return false;
51790
- throw error;
51791
- } finally {
51792
- try {
51793
- fs2.unlinkSync(claimPath);
51794
- } catch {
51795
- }
51796
- }
51797
- }
51798
- /** Acquire the fixed-path cross-process lock; the release fn is token-checked. */
51799
- acquireLock(directory, lockPath) {
51800
- fs2.mkdirSync(directory, { recursive: true, mode: 448 });
51801
- const deadline = Date.now() + this.lockWaitMs;
51802
- while (true) {
51803
- const token = `${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
51804
- try {
51805
- const fd = fs2.openSync(lockPath, "wx", 384);
51806
- try {
51807
- fs2.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
51808
- `);
51809
- } finally {
51810
- fs2.closeSync(fd);
51811
- }
51812
- return () => {
51813
- try {
51814
- const owner = JSON.parse(fs2.readFileSync(lockPath, "utf8"));
51815
- if (owner?.token === token) fs2.unlinkSync(lockPath);
51816
- } catch {
51817
- }
51818
- };
51819
- } catch (error) {
51820
- if (error.code !== "EEXIST") throw error;
51821
- try {
51822
- if (this.reclaimStaleLock(lockPath)) continue;
51823
- } catch (reclaimError) {
51824
- if (reclaimError.code === "ENOENT") continue;
51825
- throw reclaimError;
51826
- }
51827
- if (Date.now() >= deadline) throw new Error(`timed out waiting for auth storage lock: ${lockPath}`);
51828
- syncSleepMs(25);
51829
- }
51830
- }
51831
- }
51832
- /**
51833
- * Merge-on-write under a fixed-path cross-process lock: re-read the file,
51834
- * apply explicit removals (logout), merge our snapshot's oauth entries
51835
- * over whatever is on disk (preserving unrelated edits), then write back
51836
- * atomically with 0600 permissions.
51837
- */
51838
- write(snapshot) {
51839
- const directory = path2.dirname(this.authPath);
51840
- const lockPath = `${this.authPath}.lock`;
51841
- let release;
51842
- try {
51843
- release = this.acquireLock(directory, lockPath);
51844
- try {
51845
- const onDisk = this.read();
51846
- const mergedOauth = { ...onDisk.oauth };
51847
- for (const removed of snapshot.removedOauth ?? []) {
51848
- delete mergedOauth[removed];
51849
- }
51850
- Object.assign(mergedOauth, snapshot.oauth);
51851
- const merged = {
51852
- version: AUTH_FILE_VERSION,
51853
- oauth: mergedOauth
51854
- };
51855
- const temporary = `${this.authPath}.${process.pid}.tmp`;
51856
- try {
51857
- fs2.writeFileSync(temporary, `${JSON.stringify(merged, null, 2)}
51858
- `, { flag: "wx", mode: 384 });
51859
- fs2.renameSync(temporary, this.authPath);
51860
- } finally {
51861
- if (fs2.existsSync(temporary)) fs2.unlinkSync(temporary);
51862
- }
51863
- } finally {
51864
- release();
51865
- }
51866
- } catch (error) {
51867
- this.errors.push(error instanceof Error ? error : new Error(String(error)));
51868
- }
51869
- }
51870
- drainErrors() {
51871
- return this.errors.splice(0);
51872
- }
51873
- };
51874
- var AuthStorage = class _AuthStorage {
51875
- providerApiKeys = /* @__PURE__ */ new Map();
51876
- runtimeApiKeys = /* @__PURE__ */ new Map();
51877
- providerEnvVars = /* @__PURE__ */ new Map();
51878
- legacyApiKey;
51879
- oauthCredentials = /* @__PURE__ */ new Map();
51880
- removedOauthProviders = /* @__PURE__ */ new Set();
51881
- backend;
51882
- constructor(backend) {
51883
- this.backend = backend;
51884
- if (backend) {
51885
- for (const [provider, credentials] of Object.entries(backend.read().oauth)) {
51886
- this.oauthCredentials.set(provider, credentials);
51887
- }
51888
- }
51889
- }
51890
- /** Runtime-only storage (no persistence). */
51891
- static create() {
51892
- return new _AuthStorage();
51893
- }
51894
- /** Storage bound to a persistence backend (OAuth credentials survive restarts). */
51895
- static fromStorage(backend) {
51896
- return new _AuthStorage(backend);
51897
- }
51898
- /** In-memory backend, for tests and embedders that manage their own persistence. */
51899
- static inMemory() {
51900
- return new _AuthStorage(new InMemoryAuthStorageBackend());
51901
- }
51902
- /** Drain buffered backend I/O errors (file backend only). */
51903
- drainErrors() {
51904
- const backend = this.backend;
51905
- if (backend && typeof backend.drainErrors === "function") {
51906
- return backend.drainErrors();
51907
- }
51908
- return [];
51909
- }
51910
- setLegacyApiKey(apiKey) {
51911
- this.legacyApiKey = apiKey;
51912
- }
51913
- setProviderApiKey(provider, apiKey) {
51914
- if (!apiKey) {
51915
- this.providerApiKeys.delete(provider);
51916
- return;
51917
- }
51918
- this.providerApiKeys.set(provider, apiKey);
51919
- }
51920
- setRuntimeApiKey(provider, apiKey) {
51921
- if (!apiKey) {
51922
- this.runtimeApiKeys.delete(provider);
51923
- return;
51924
- }
51925
- this.runtimeApiKeys.set(provider, apiKey);
51926
- }
51927
- setProviderEnvVar(provider, envVar) {
51928
- if (!envVar) {
51929
- this.providerEnvVars.delete(provider);
51930
- return;
51931
- }
51932
- this.providerEnvVars.set(provider, envVar);
51933
- }
51934
- getProviderEnvVar(provider) {
51935
- return this.providerEnvVars.get(provider);
51936
- }
51937
- setOAuthCredentials(provider, credentials) {
51938
- if (!credentials) {
51939
- this.oauthCredentials.delete(provider);
51940
- this.removedOauthProviders.add(provider);
51941
- this.runtimeApiKeys.delete(provider);
51942
- } else {
51943
- this.oauthCredentials.set(provider, credentials);
51944
- this.removedOauthProviders.delete(provider);
51945
- }
51946
- this.persistOAuth();
51947
- }
51948
- getOAuthCredentials(provider) {
51949
- return this.oauthCredentials.get(provider);
51950
- }
51951
- /** Providers with persisted OAuth credentials (for restore/refresh passes). */
51952
- getOAuthProviderNames() {
51953
- return [...this.oauthCredentials.keys()];
51954
- }
51955
- persistOAuth() {
51956
- if (!this.backend) return;
51957
- this.backend.write({
51958
- oauth: Object.fromEntries(this.oauthCredentials),
51959
- removedOauth: [...this.removedOauthProviders]
51960
- });
51961
- }
51962
- getApiKey(provider, explicitEnvVar) {
51963
- const envVar = explicitEnvVar || this.getProviderEnvVar(provider);
51964
- const envApiKey = envVar && typeof process !== "undefined" ? process.env?.[envVar] : void 0;
51965
- return this.runtimeApiKeys.get(provider) || this.providerApiKeys.get(provider) || envApiKey || this.usableOAuthAccessToken(provider) || this.legacyApiKey;
51966
- }
51967
- /** Persisted OAuth access token, when it exists and has not expired. */
51968
- usableOAuthAccessToken(provider) {
51969
- const credentials = this.oauthCredentials.get(provider);
51970
- if (!credentials?.access) return void 0;
51971
- if (credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_EXPIRY_SKEW_MS) {
51972
- return void 0;
51973
- }
51974
- return credentials.access;
51975
- }
51976
- };
51977
-
51978
- // src/core/model-registry.ts
51979
- import * as fs3 from "fs";
51980
- import * as path3 from "path";
51981
- import { createHash, createHmac, randomBytes } from "node:crypto";
51982
- var MODEL_OVERRIDE_KEYS = [
51983
- "name",
51984
- "reasoning",
51985
- "input",
51986
- "cost",
51987
- "contextWindow",
51988
- "maxTokens",
51989
- "transport",
51990
- "headers",
51991
- "compat",
51992
- "cacheCapability",
51993
- "webSearch",
51994
- "fileCapabilities",
51995
- "displayName"
51996
- ];
51997
- function validateExtensionProviderConfig(provider, config) {
51998
- if (!provider || provider !== provider.trim() || /\s/.test(provider)) throw new Error(`registerProvider: invalid provider id "${provider}"`);
51999
- if (!config || typeof config !== "object") throw new Error("registerProvider: config must be an object");
52000
- if (typeof config.baseUrl !== "string" || !config.baseUrl) throw new Error(`registerProvider("${provider}"): baseUrl is required`);
52001
- try {
52002
- new URL(config.baseUrl);
52003
- } catch {
52004
- throw new Error(`registerProvider("${provider}"): baseUrl must be an absolute URL`);
52005
- }
52006
- assertHeadersShape(config.headers, `registerProvider("${provider}")`);
52007
- validateTransport(config.transport, `registerProvider("${provider}")`);
52008
- for (const model of config.models ?? []) {
52009
- if (!model || typeof model.id !== "string" || !model.id.trim() || /\s/.test(model.id)) throw new Error(`registerProvider("${provider}"): invalid model id`);
52010
- assertHeadersShape(model.headers, `registerProvider("${provider}") model "${model.id}"`);
52011
- validateTransport(model.transport, `Model "${model.id}"`);
52012
- validateCompat(model.compat, `registerProvider("${provider}") model "${model.id}" compat`);
52013
- validateCacheCapability(model.cacheCapability, `registerProvider("${provider}") model "${model.id}" cacheCapability`);
52014
- validateWebSearchCapability(model.webSearch, `registerProvider("${provider}") model "${model.id}" webSearch`);
52015
- validateFileCapabilities(model.fileCapabilities, `registerProvider("${provider}") model "${model.id}" fileCapabilities`);
52016
- }
52017
- }
52018
- var REMOTE_CATALOG_CACHE_VERSION = 4;
52019
- var SUPPORTED_REMOTE_APIS = /* @__PURE__ */ new Set(["openai-completions", "anthropic-messages", "openai-responses"]);
52020
- var MAX_REMOTE_CATALOG_BYTES = 2 * 1024 * 1024;
52021
- var OAUTH_RESTORE_LEEWAY_MS = 6e4;
52022
- var OAUTH_REFRESH_TIMEOUT_MS = 3e4;
52023
- function withTimeout(promise, ms, timeoutMessage) {
52024
- return new Promise((resolve7, reject) => {
52025
- const timer = setTimeout(() => reject(new Error(timeoutMessage)), ms);
52026
- Promise.resolve(promise).then(
52027
- (value) => {
52028
- clearTimeout(timer);
52029
- resolve7(value);
52030
- },
52031
- (error) => {
52032
- clearTimeout(timer);
52033
- reject(error);
52034
- }
52035
- );
52036
- });
52037
- }
52038
- var REMOTE_REFRESH_LOCK_WAIT_MS = 6e4;
52039
- var REMOTE_REFRESH_LOCK_WRITE_GRACE_MS = 1e3;
52040
- var remoteRefreshTails = /* @__PURE__ */ new Map();
52041
- var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
52042
- "connection",
52043
- "keep-alive",
52044
- "proxy-authenticate",
52045
- "proxy-authorization",
52046
- "te",
52047
- "trailer",
52048
- "transfer-encoding",
52049
- "upgrade",
52050
- "host",
52051
- "content-length"
52052
- ]);
52053
- function canonicalRemote(remote) {
52054
- const url = new URL(remote.url);
52055
- return { id: remote.id, url: url.href, apiKeyEnv: remote.apiKeyEnv };
52056
- }
52057
- function remoteIdentityDigest(remote) {
52058
- return createHash("sha256").update(JSON.stringify({ version: REMOTE_CATALOG_CACHE_VERSION, ...canonicalRemote(remote) })).digest("hex");
52059
- }
52060
- function remoteCacheDirectory(modelsPath) {
52061
- return path3.join(path3.dirname(modelsPath), "cache", "remote-catalogs");
52062
- }
52063
- function safeRemoteCacheDirectory(modelsPath, create) {
52064
- const configDirectory = path3.dirname(modelsPath);
52065
- if (!fs3.existsSync(configDirectory)) {
52066
- if (!create) return void 0;
52067
- fs3.mkdirSync(configDirectory, { recursive: true, mode: 448 });
52068
- }
52069
- const configRoot = fs3.realpathSync(configDirectory);
52070
- const cacheRoot = path3.join(configDirectory, "cache");
52071
- const directory = remoteCacheDirectory(modelsPath);
52072
- for (const candidate of [cacheRoot, directory]) {
52073
- if (!fs3.existsSync(candidate)) {
52074
- if (!create) return void 0;
52075
- fs3.mkdirSync(candidate, { mode: 448 });
52076
- }
52077
- const stat2 = fs3.lstatSync(candidate);
52078
- if (stat2.isSymbolicLink() || !stat2.isDirectory()) throw new Error(`remote catalog cache path must be a real directory: ${candidate}`);
52079
- const canonical = fs3.realpathSync(candidate);
52080
- const relative3 = path3.relative(configRoot, canonical);
52081
- if (relative3 === ".." || relative3.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative3)) {
52082
- throw new Error(`remote catalog cache path escapes the config directory: ${candidate}`);
52083
- }
52084
- try {
52085
- fs3.chmodSync(candidate, 448);
52086
- } catch {
52087
- }
52088
- }
52089
- return directory;
52090
- }
52091
- function remoteRefreshLockPath(modelsPath) {
52092
- return path3.join(remoteCacheDirectory(modelsPath), ".refresh.lock");
52093
- }
52094
- function processIsAlive2(pid) {
52095
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
52096
- try {
52097
- process.kill(pid, 0);
52098
- return true;
52099
- } catch (error) {
52100
- return error.code === "EPERM";
52101
- }
52102
- }
52103
- function remoteRefreshLockIsStale(lockPath) {
52104
- const stat2 = fs3.lstatSync(lockPath);
52105
- if (stat2.isSymbolicLink() || !stat2.isFile()) throw new Error(`remote catalog refresh lock must be a regular file: ${lockPath}`);
52106
- let owner;
52107
- try {
52108
- owner = JSON.parse(fs3.readFileSync(lockPath, "utf8"));
52109
- } catch {
52110
- }
52111
- const age = Date.now() - stat2.mtimeMs;
52112
- const validOwner = owner?.version === 1 && Number.isSafeInteger(owner.pid) && typeof owner.token === "string" && typeof owner.createdAt === "number";
52113
- if (validOwner && processIsAlive2(Number(owner.pid))) return false;
52114
- return validOwner || age > REMOTE_REFRESH_LOCK_WRITE_GRACE_MS;
52115
- }
52116
- function sameFileIdentity(left, right, leftPath, rightPath) {
52117
- if (left.dev !== right.dev || left.ino !== right.ino) return false;
52118
- if (left.ino !== 0) return true;
52119
- return left.size === right.size && fs3.readFileSync(leftPath).equals(fs3.readFileSync(rightPath));
52120
- }
52121
- function reclaimStaleRemoteRefreshLock(lockPath) {
52122
- if (!remoteRefreshLockIsStale(lockPath)) return false;
52123
- const claimPath = `${lockPath}.reclaim-${process.pid}-${randomBytes(8).toString("hex")}`;
52124
- try {
52125
- fs3.linkSync(lockPath, claimPath);
52126
- const claimed = fs3.lstatSync(claimPath);
52127
- const current = fs3.lstatSync(lockPath);
52128
- if (claimed.isSymbolicLink() || !claimed.isFile() || current.isSymbolicLink() || !current.isFile() || !sameFileIdentity(claimed, current, claimPath, lockPath)) return false;
52129
- if (!remoteRefreshLockIsStale(claimPath)) return false;
52130
- fs3.unlinkSync(lockPath);
52131
- return true;
52132
- } catch (error) {
52133
- if (["ENOENT", "EEXIST"].includes(error.code ?? "")) return false;
52134
- throw error;
52135
- } finally {
52136
- try {
52137
- fs3.unlinkSync(claimPath);
52138
- } catch {
52139
- }
52140
- }
52141
- }
52142
- async function acquireRemoteRefreshLock(modelsPath) {
52143
- const directory = safeRemoteCacheDirectory(modelsPath, true);
52144
- const lockPath = remoteRefreshLockPath(modelsPath);
52145
- const deadline = Date.now() + REMOTE_REFRESH_LOCK_WAIT_MS;
52146
- while (true) {
52147
- const token = randomBytes(16).toString("hex");
52148
- try {
52149
- const fd = fs3.openSync(lockPath, "wx", 384);
52150
- try {
52151
- fs3.writeFileSync(fd, `${JSON.stringify({ version: 1, pid: process.pid, token, createdAt: Date.now() })}
52152
- `);
52153
- } finally {
52154
- fs3.closeSync(fd);
52155
- }
52156
- return () => {
52157
- try {
52158
- const stat2 = fs3.lstatSync(lockPath);
52159
- if (stat2.isSymbolicLink() || !stat2.isFile()) return;
52160
- const current = JSON.parse(fs3.readFileSync(lockPath, "utf8"));
52161
- if (current.token === token) fs3.unlinkSync(lockPath);
52162
- } catch {
52163
- }
52164
- };
52165
- } catch (error) {
52166
- if (error.code !== "EEXIST") throw error;
52167
- try {
52168
- if (reclaimStaleRemoteRefreshLock(lockPath)) continue;
52169
- } catch (lockError) {
52170
- if (lockError.code === "ENOENT") continue;
52171
- throw lockError;
52172
- }
52173
- if (Date.now() >= deadline) throw new Error(`timed out waiting for remote catalog refresh lock: ${lockPath}`);
52174
- await new Promise((resolve7) => setTimeout(resolve7, 25));
52175
- }
52176
- }
52177
- }
52178
- function readSafeRemoteCacheFile(directory, filepath) {
52179
- const stat2 = fs3.lstatSync(filepath);
52180
- if (stat2.isSymbolicLink() || !stat2.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${filepath}`);
52181
- const canonicalDirectory = fs3.realpathSync(directory);
52182
- const canonicalFile = fs3.realpathSync(filepath);
52183
- const relative3 = path3.relative(canonicalDirectory, canonicalFile);
52184
- if (!relative3 || relative3 === ".." || relative3.startsWith(`..${path3.sep}`) || path3.isAbsolute(relative3)) {
52185
- throw new Error(`remote catalog cache entry escapes its cache directory: ${filepath}`);
52186
- }
52187
- return fs3.readFileSync(filepath);
52188
- }
52189
- function credentialNamespaceKey(modelsPath, create) {
52190
- const directory = safeRemoteCacheDirectory(modelsPath, create);
52191
- if (!directory) return void 0;
52192
- const keyPath = path3.join(directory, ".credential-namespace-key");
52193
- if (!fs3.existsSync(keyPath) && !create) return void 0;
52194
- if (create && !fs3.existsSync(keyPath)) {
52195
- try {
52196
- fs3.writeFileSync(keyPath, randomBytes(32), { flag: "wx", mode: 384 });
52197
- } catch (error) {
52198
- if (!isPlainRecord(error) || error.code !== "EEXIST") throw error;
52199
- }
52200
- }
52201
- const key = readSafeRemoteCacheFile(directory, keyPath);
52202
- if (key.byteLength !== 32) throw new Error("remote catalog credential namespace key is invalid");
52203
- try {
52204
- fs3.chmodSync(keyPath, 384);
52205
- } catch {
52206
- }
52207
- return key;
52208
- }
52209
- function credentialFingerprint(modelsPath, remote, credential, create = false) {
52210
- const key = credentialNamespaceKey(modelsPath, create);
52211
- if (!key) return void 0;
52212
- return createHmac("sha256", key).update(remoteIdentityDigest(remote)).update("\0").update(credential).digest("hex");
52213
- }
52214
- function remoteCachePath(modelsPath, remote, fingerprint) {
52215
- return path3.join(remoteCacheDirectory(modelsPath), `${remoteIdentityDigest(remote)}-${fingerprint}.json`);
52216
- }
52217
- function pruneLegacyRemoteCatalogCaches(modelsPath) {
52218
- const directory = safeRemoteCacheDirectory(modelsPath, false);
52219
- if (!directory) return;
52220
- for (const name of fs3.readdirSync(directory)) {
52221
- if (!name.endsWith(".json")) continue;
52222
- const filepath = path3.join(directory, name);
52223
- try {
52224
- const value = JSON.parse(readSafeRemoteCacheFile(directory, filepath).toString("utf8"));
52225
- if (value.version === REMOTE_CATALOG_CACHE_VERSION) continue;
52226
- } catch {
52227
- let stat2;
52228
- try {
52229
- stat2 = fs3.lstatSync(filepath);
52230
- } catch {
52231
- continue;
52232
- }
52233
- if (stat2.isSymbolicLink() || !stat2.isFile()) continue;
52234
- }
52235
- try {
52236
- fs3.unlinkSync(filepath);
52237
- } catch {
52238
- }
52239
- }
52240
- }
52241
- function scrubActiveSecretsFromRemoteCaches(modelsPath, activeSecrets) {
52242
- if (activeSecrets.length === 0) return;
52243
- const directory = safeRemoteCacheDirectory(modelsPath, false);
52244
- if (!directory) return;
52245
- const handle = fs3.opendirSync(directory);
52246
- try {
52247
- let scanned = 0;
52248
- while (true) {
52249
- const entry = handle.readSync();
52250
- if (!entry) break;
52251
- if (++scanned > 1e4) throw new Error("remote catalog cache directory exceeds the hygiene scan limit");
52252
- const isCache = entry.name.endsWith(".json");
52253
- const isOrphanedTemporary = /^\..+\.json\.\d+\.[0-9a-f]+\.tmp$/.test(entry.name);
52254
- if (!entry.isFile() || !isCache && !isOrphanedTemporary) continue;
52255
- const filepath = path3.join(directory, entry.name);
52256
- try {
52257
- const raw = readSafeRemoteCacheFile(directory, filepath).toString("utf8");
52258
- assertNoSecretSubstrings(raw, activeSecrets, "remote catalog cache");
52259
- } catch {
52260
- try {
52261
- const stat2 = fs3.lstatSync(filepath);
52262
- if (!stat2.isSymbolicLink() && stat2.isFile()) fs3.unlinkSync(filepath);
52263
- } catch {
52264
- }
52265
- }
52266
- }
52267
- } finally {
52268
- handle.closeSync();
52269
- }
52270
- }
52271
- function payloadDigest(payload) {
52272
- return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
52273
- }
52274
- function assertNoSecretSubstrings(value, secrets, label) {
52275
- const active = [...new Set(secrets.filter((secret) => secret.length > 0))];
52276
- if (active.length === 0) return;
52277
- const seen = /* @__PURE__ */ new Set();
52278
- const visit = (candidate) => {
52279
- if (typeof candidate === "string") {
52280
- if (active.some((secret) => candidate.includes(secret))) throw new Error(`${label} reflects an active credential`);
52281
- return;
52282
- }
52283
- if (!candidate || typeof candidate !== "object" || seen.has(candidate)) return;
52284
- seen.add(candidate);
52285
- if (Array.isArray(candidate)) {
52286
- for (const item of candidate) visit(item);
52287
- return;
52288
- }
52289
- for (const [key, item] of Object.entries(candidate)) {
52290
- visit(key);
52291
- visit(item);
52292
- }
52293
- };
52294
- visit(value);
52295
- const serialized = JSON.stringify(value);
52296
- if (active.some((secret) => serialized.includes(secret))) throw new Error(`${label} reflects an active credential`);
52297
- }
52298
- function safeRemoteText(value, secrets) {
52299
- let message = String(value);
52300
- const active = [...new Set(secrets.filter(Boolean))];
52301
- const replacement = active.some((secret) => "[REDACTED]".includes(secret)) ? "" : "[REDACTED]";
52302
- for (const secret of active) message = message.split(secret).join(replacement);
52303
- message = message.slice(0, 1024);
52304
- if (!active.some((secret) => message.includes(secret))) return message;
52305
- return "";
52306
- }
52307
- function safeRemoteError(error, secrets) {
52308
- return safeRemoteText(error instanceof Error ? `${error.name}: ${error.message}` : String(error), secrets);
52309
- }
52310
- function warnRemoteCatalog(message, secrets) {
52311
- console.warn(safeRemoteText(message, secrets));
52312
- }
52313
- function configuredRemoteCredentialValues(config) {
52314
- let remotes;
52315
- try {
52316
- remotes = validatedRemoteCatalogs(config.remoteCatalogs);
52317
- } catch {
52318
- return [];
52319
- }
52320
- return [...new Set(remotes.map((remote) => process.env[remote.apiKeyEnv]).filter((secret) => typeof secret === "string" && secret.length > 0))];
52321
- }
52322
- function sameRemoteIdentity(left, right) {
52323
- if (!left || typeof left !== "object" || Array.isArray(left)) return false;
52324
- const value = left;
52325
- const expected = canonicalRemote(right);
52326
- return value.id === expected.id && value.url === expected.url && value.apiKeyEnv === expected.apiKeyEnv;
52327
- }
52328
- function readRemoteCache(modelsPath, remote, fingerprint, activeSecrets) {
52329
- try {
52330
- const directory = safeRemoteCacheDirectory(modelsPath, false);
52331
- if (!directory) return void 0;
52332
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
52333
- if (fs3.existsSync(tombstone)) return void 0;
52334
- const value = JSON.parse(readSafeRemoteCacheFile(directory, remoteCachePath(modelsPath, remote, fingerprint)).toString("utf8"));
52335
- if (value.version !== REMOTE_CATALOG_CACHE_VERSION || !sameRemoteIdentity(value.identity, remote) || value.credentialFingerprint !== fingerprint || typeof value.payloadSha256 !== "string" || value.payloadSha256 !== payloadDigest(value.payload)) return void 0;
52336
- assertNoSecretSubstrings({ etag: value.etag, payload: value.payload }, activeSecrets, "remote catalog cache");
52337
- const payload = sanitizeRemotePayload(value.payload, canonicalRemote(remote), new URL(remote.url), true);
52338
- if (payloadDigest(payload) !== value.payloadSha256) return void 0;
52339
- return { ...value, payload };
52340
- } catch {
52341
- removeRemoteCache(modelsPath, remote, fingerprint);
52342
- return void 0;
52343
- }
52344
- }
52345
- function remoteCacheTombstonePath(modelsPath, remote, fingerprint) {
52346
- return `${remoteCachePath(modelsPath, remote, fingerprint)}.revoked`;
52347
- }
52348
- function removeRemoteCache(modelsPath, remote, fingerprint) {
52349
- try {
52350
- const directory = safeRemoteCacheDirectory(modelsPath, false);
52351
- if (!directory) return;
52352
- const filepath = remoteCachePath(modelsPath, remote, fingerprint);
52353
- if (fs3.existsSync(filepath)) {
52354
- const stat2 = fs3.lstatSync(filepath);
52355
- if (stat2.isSymbolicLink() || !stat2.isFile()) throw new Error(`remote catalog cache entry is not a regular file: ${filepath}`);
52356
- fs3.unlinkSync(filepath);
52357
- }
52358
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
52359
- if (fs3.existsSync(tombstone)) fs3.unlinkSync(tombstone);
52360
- return;
52361
- } catch (error) {
52362
- const directory = safeRemoteCacheDirectory(modelsPath, true);
52363
- if (!directory) throw error;
52364
- const tombstone = remoteCacheTombstonePath(modelsPath, remote, fingerprint);
52365
- try {
52366
- fs3.writeFileSync(tombstone, `${JSON.stringify({ version: 1, revoked: true })}
52367
- `, { flag: "wx", mode: 384 });
52368
- } catch (tombstoneError) {
52369
- if (!fs3.existsSync(tombstone)) throw tombstoneError;
52370
- }
52371
- }
52372
- }
52373
- function validateRemoteEndpoint(baseUrl, catalogUrl, label) {
52374
- let endpoint;
52375
- try {
52376
- endpoint = new URL(baseUrl);
52377
- } catch {
52378
- throw new Error(`${label} baseUrl must be an absolute URL`);
52379
- }
52380
- if (endpoint.protocol !== "https:" && endpoint.hostname !== "127.0.0.1" && endpoint.hostname !== "localhost") {
52381
- throw new Error(`${label} baseUrl must use HTTPS`);
52382
- }
52383
- if (endpoint.username || endpoint.password) throw new Error(`${label} baseUrl must not contain credentials`);
52384
- if (endpoint.hash) throw new Error(`${label} baseUrl must not contain a fragment`);
52385
- if (endpoint.search) throw new Error(`${label} baseUrl must not contain query parameters`);
52386
- if (endpoint.origin !== catalogUrl.origin) throw new Error(`${label} baseUrl must use the authenticated catalog origin`);
52387
- }
52388
- function isPlainRecord(value) {
52389
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
52390
- const prototype = Object.getPrototypeOf(value);
52391
- return prototype === Object.prototype || prototype === null;
52392
- }
52393
- function assertOnlyKeys(value, allowed, label) {
52394
- const allowedSet = new Set(allowed);
52395
- const unexpected = Object.keys(value).find((key) => !allowedSet.has(key));
52396
- if (unexpected) throw new Error(`${label} contains unsupported field ${unexpected}`);
52397
- }
52398
- function validateRemoteCatalogConfig(value, label) {
52399
- if (!isPlainRecord(value)) throw new Error(`${label} must be an object`);
52400
- assertOnlyKeys(value, ["id", "url", "apiKeyEnv"], label);
52401
- if (typeof value.id !== "string" || !value.id.trim() || value.id !== value.id.trim() || /\s/.test(value.id)) throw new Error(`${label}.id must be a non-empty identifier without whitespace`);
52402
- if (typeof value.url !== "string" || !value.url) throw new Error(`${label}.url must be a URL`);
52403
- if (typeof value.apiKeyEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.apiKeyEnv)) throw new Error(`${label}.apiKeyEnv must be an environment variable name`);
52404
- let url;
52405
- try {
52406
- url = new URL(value.url);
52407
- } catch {
52408
- throw new Error(`${label}.url must be an absolute URL`);
52409
- }
52410
- const localTestHost = url.hostname === "127.0.0.1" || url.hostname === "localhost";
52411
- if (url.protocol !== "https:" && !localTestHost) throw new Error(`${label}.url must use HTTPS`);
52412
- if (url.username || url.password) throw new Error(`${label}.url must not contain credentials`);
52413
- if (url.hash) throw new Error(`${label}.url must not contain a fragment`);
52414
- if (url.search) throw new Error(`${label}.url must not contain query parameters`);
52415
- return canonicalRemote({ id: value.id, url: url.href, apiKeyEnv: value.apiKeyEnv });
52416
- }
52417
- function validatedRemoteCatalogs(value) {
52418
- if (value === void 0) return [];
52419
- if (!Array.isArray(value)) throw new Error("models.json remoteCatalogs must be an array");
52420
- if (value.length === 0) throw new Error("models.json remoteCatalogs must be a non-empty array");
52421
- const catalogs = value.map((item, index) => validateRemoteCatalogConfig(item, `models.json remoteCatalogs[${index}]`));
52422
- const ids = /* @__PURE__ */ new Set();
52423
- for (const catalog of catalogs) {
52424
- if (ids.has(catalog.id)) throw new Error(`models.json remoteCatalogs contains duplicate id ${catalog.id}`);
52425
- ids.add(catalog.id);
52426
- }
52427
- return catalogs;
52428
- }
52429
- function validateModelsDocumentShape(value) {
52430
- if (!isPlainRecord(value)) throw new Error("models.json must be an object");
52431
- assertOnlyKeys(value, ["$schema", "profiles", "remoteCatalogs", "defaults", "modelOverrides"], "models.json");
52432
- if (value.$schema !== void 0 && (typeof value.$schema !== "string" || !value.$schema)) throw new Error("models.json $schema must be a non-empty string");
52433
- const hasProfiles = Object.prototype.hasOwnProperty.call(value, "profiles");
52434
- const hasRemoteCatalogs = Object.prototype.hasOwnProperty.call(value, "remoteCatalogs");
52435
- if (!hasProfiles && !hasRemoteCatalogs) throw new Error("models.json must define profiles or remoteCatalogs");
52436
- validatedRemoteCatalogs(value.remoteCatalogs);
52437
- if (hasProfiles) {
52438
- if (!isPlainRecord(value.profiles) || Object.keys(value.profiles).length === 0) throw new Error("models.json profiles must be a non-empty object");
52439
- for (const [profileId, profile] of Object.entries(value.profiles)) {
52440
- if (!profileId || profileId !== profileId.trim() || /\s/.test(profileId)) throw new Error(`models.json profile id is invalid: ${profileId}`);
52441
- validateProfileConfig(profileId, profile);
52442
- }
52443
- }
52444
- validateModelOverrides(value.modelOverrides);
52445
- if (value.defaults !== void 0) {
52446
- if (!isPlainRecord(value.defaults)) throw new Error("models.json defaults must be an object");
52447
- assertOnlyKeys(value.defaults, ["provider", "modelId", "modelClasses", "toolModels"], "models.json defaults");
52448
- assertOptionalString(value.defaults.provider, "models.json defaults.provider");
52449
- assertOptionalString(value.defaults.modelId, "models.json defaults.modelId");
52450
- for (const [field, allowed] of [["modelClasses", ["light", "balanced", "strong"]], ["toolModels", ["web_search", "read_file.image", "read_file.video", "read_file.audio", "read_file.document"]]]) {
52451
- const routes = value.defaults[field];
52452
- if (routes === void 0) continue;
52453
- if (!isPlainRecord(routes)) throw new Error(`models.json defaults.${field} must be an object`);
52454
- assertOnlyKeys(routes, allowed, `models.json defaults.${field}`);
52455
- for (const [routeName, route] of Object.entries(routes)) {
52456
- if (!isPlainRecord(route)) throw new Error(`models.json defaults.${field}.${routeName} must be an object`);
52457
- assertOnlyKeys(route, ["provider", "modelId"], `models.json defaults.${field}.${routeName}`);
52458
- assertOptionalString(route.provider, `models.json defaults.${field}.${routeName}.provider`);
52459
- assertOptionalString(route.modelId, `models.json defaults.${field}.${routeName}.modelId`);
52460
- }
52461
- }
52462
- }
52463
- }
52464
- function assertOptionalString(value, label) {
52465
- if (value !== void 0 && (typeof value !== "string" || !value)) throw new Error(`${label} must be a non-empty string`);
52466
- }
52467
- function assertOptionalEnvName(value, label) {
52468
- if (value !== void 0 && (typeof value !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value))) {
52469
- throw new Error(`${label} must be an environment variable name`);
52470
- }
52471
- }
52472
- function assertOptionalBoolean(value, label) {
52473
- if (value !== void 0 && typeof value !== "boolean") throw new Error(`${label} must be a boolean`);
52474
- }
52475
- function validateCacheCapability(value, label) {
52476
- if (value === void 0) return;
52477
- if (!isPlainRecord(value) || !["none", "session_store", "prompt_cache", "usage_only"].includes(String(value.mode)) || typeof value.supported !== "boolean") throw new Error(`${label} is invalid`);
52478
- assertOnlyKeys(value, ["mode", "supported", "supportsUsageMetrics", "description"], label);
52479
- assertOptionalBoolean(value.supportsUsageMetrics, `${label}.supportsUsageMetrics`);
52480
- assertOptionalString(value.description, `${label}.description`);
52481
- }
52482
- function validateWebSearchCapability(value, label) {
52483
- if (value === void 0) return;
52484
- if (!isPlainRecord(value) || !["anthropic_server_tool", "chat_completions_web_search", "openai_responses"].includes(String(value.type))) {
52485
- throw new Error(`${label} is invalid`);
52486
- }
52487
- assertOnlyKeys(value, ["type", "forceToolChoice", "searchEngine", "count", "contentSize"], label);
52488
- assertOptionalBoolean(value.forceToolChoice, `${label}.forceToolChoice`);
52489
- assertOptionalString(value.searchEngine, `${label}.searchEngine`);
52490
- if (value.count !== void 0 && (!Number.isInteger(value.count) || Number(value.count) < 1)) throw new Error(`${label}.count is invalid`);
52491
- if (value.contentSize !== void 0 && !["low", "medium", "high"].includes(String(value.contentSize))) throw new Error(`${label}.contentSize is invalid`);
52492
- }
52493
- function validateFileCapabilities(value, label) {
52494
- if (value === void 0) return;
52495
- if (!isPlainRecord(value)) throw new Error(`${label} is invalid`);
52496
- for (const [kind, capability] of Object.entries(value)) {
52497
- if (!["image", "video", "audio", "document"].includes(kind)) throw new Error(`${label}.${kind} is unsupported`);
52498
- if (typeof capability === "boolean") continue;
52499
- if (!isPlainRecord(capability)) throw new Error(`${label}.${kind} is invalid`);
52500
- assertOnlyKeys(capability, ["supported", "formats", "maxFileSizeMb", "maxDurationSeconds", "nativeInline"], `${label}.${kind}`);
52501
- assertOptionalBoolean(capability.supported, `${label}.${kind}.supported`);
52502
- assertOptionalBoolean(capability.nativeInline, `${label}.${kind}.nativeInline`);
52503
- if (capability.formats !== void 0 && (!Array.isArray(capability.formats) || capability.formats.some((item) => typeof item !== "string" || !item))) {
52504
- throw new Error(`${label}.${kind}.formats is invalid`);
52505
- }
52506
- if (Array.isArray(capability.formats) && new Set(capability.formats).size !== capability.formats.length) {
52507
- throw new Error(`${label}.${kind}.formats contains duplicates`);
52508
- }
52509
- for (const field of ["maxFileSizeMb", "maxDurationSeconds"]) {
52510
- if (capability[field] !== void 0 && (typeof capability[field] !== "number" || !Number.isFinite(capability[field]) || capability[field] <= 0)) {
52511
- throw new Error(`${label}.${kind}.${field} is invalid`);
52512
- }
52513
- }
52514
- }
52515
- }
52516
- function validateTransport(value, label) {
52517
- if (value !== void 0 && value !== "sse" && value !== "websocket" && value !== "auto") throw new Error(`${label}.transport is invalid`);
52518
- }
52519
- function validateCompat(value, label) {
52520
- if (value === void 0) return;
52521
- if (!isPlainRecord(value)) throw new Error(`${label} is invalid`);
52522
- assertOnlyKeys(value, [
52523
- "forcedReasoningEffort",
52524
- "store",
52525
- "supportsEncryptedReasoning",
52526
- "responsesContinuation",
52527
- "supportsReasoningSummary",
52528
- "reasoningSummary",
52529
- "timeoutReplay",
52530
- "supportsStore",
52531
- "supportsDeveloperRole",
52532
- "supportsReasoningEffort",
52533
- "supportsUsageInStreaming",
52534
- "maxTokensField",
52535
- "requiresToolResultName",
52536
- "requiresAssistantAfterToolResult",
52537
- "requiresThinkingAsText",
52538
- "supportsStrictMode",
52539
- "streamRequiresDone",
52540
- "streamRequiresFinishReason",
52541
- "cacheCapability"
52542
- ], label);
52543
- if (value.forcedReasoningEffort !== void 0 && value.forcedReasoningEffort !== "none") {
52544
- throw new Error(`${label}.forcedReasoningEffort must be "none"`);
52545
- }
52546
- if (value.reasoningSummary !== void 0 && !["auto", "concise", "detailed", "none"].includes(String(value.reasoningSummary))) {
52547
- throw new Error(`${label}.reasoningSummary must be auto | concise | detailed | none`);
52548
- }
52549
- for (const field of [
52550
- "store",
52551
- "supportsEncryptedReasoning",
52552
- "responsesContinuation",
52553
- "supportsReasoningSummary",
52554
- "timeoutReplay",
52555
- "supportsStore",
52556
- "supportsDeveloperRole",
52557
- "supportsReasoningEffort",
52558
- "supportsUsageInStreaming",
52559
- "requiresToolResultName",
52560
- "requiresAssistantAfterToolResult",
52561
- "requiresThinkingAsText",
52562
- "supportsStrictMode",
52563
- "streamRequiresDone",
52564
- "streamRequiresFinishReason"
52565
- ]) assertOptionalBoolean(value[field], `${label}.${field}`);
52566
- if (value.maxTokensField !== void 0 && value.maxTokensField !== "max_completion_tokens" && value.maxTokensField !== "max_tokens") {
52567
- throw new Error(`${label}.maxTokensField is invalid`);
52568
- }
52569
- validateCacheCapability(value.cacheCapability, `${label}.cacheCapability`);
52570
- }
52571
- function validateRemoteModel(profileId, model) {
52572
- if (!isPlainRecord(model) || typeof model.id !== "string" || !model.id.trim() || model.id !== model.id.trim() || /\s/.test(model.id)) throw new Error(`Remote profile "${profileId}" contains an invalid model id`);
52573
- assertOnlyKeys(model, [
52574
- "id",
52575
- "api",
52576
- "name",
52577
- "reasoning",
52578
- "input",
52579
- "cost",
52580
- "contextWindow",
52581
- "maxTokens",
52582
- "transport",
52583
- "compat",
52584
- "cacheCapability",
52585
- "webSearch",
52586
- "fileCapabilities",
52587
- "headers",
52588
- "apiKeyEnv",
52589
- "displayName",
52590
- "filePlatform",
52591
- "attachmentPlatform"
52592
- ], `Remote profile "${profileId}" model "${model.id}"`);
52593
- for (const field of ["name", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
52594
- assertOptionalString(model[field], `Remote profile "${profileId}" model "${model.id}" ${field}`);
52595
- }
52596
- if (model.api !== void 0 && !SUPPORTED_REMOTE_APIS.has(model.api)) throw new Error(`Model "${model.id}" has unsupported api ${model.api}`);
52597
- assertOptionalBoolean(model.reasoning, `Remote profile "${profileId}" model "${model.id}" reasoning`);
52598
- if (!Array.isArray(model.input) || model.input.length === 0 || model.input.some((item) => !["text", "image", "audio", "video"].includes(item))) {
52599
- throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid input capabilities`);
52600
- }
52601
- if (!isPlainRecord(model.cost)) throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
52602
- assertOnlyKeys(model.cost, ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"], `Remote profile "${profileId}" model "${model.id}" cost`);
52603
- const invalidRate = (value) => typeof value !== "number" || !Number.isFinite(value) || value < 0;
52604
- if ([model.cost.input, model.cost.output, model.cost.cacheRead, model.cost.cacheWrite].some(invalidRate) || model.cost.cacheWriteLong !== void 0 && invalidRate(model.cost.cacheWriteLong)) {
52605
- throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid cost values`);
52606
- }
52607
- if (!Number.isSafeInteger(model.contextWindow) || Number(model.contextWindow) <= 0 || !Number.isSafeInteger(model.maxTokens) || Number(model.maxTokens) <= 0 || Number(model.maxTokens) > Number(model.contextWindow)) {
52608
- throw new Error(`Remote profile "${profileId}" model "${model.id}" has invalid token limits`);
52609
- }
52610
- if (new Set(model.input).size !== model.input.length) throw new Error(`Remote profile "${profileId}" model "${model.id}" has duplicate input capabilities`);
52611
- validateTransport(model.transport, `Model "${model.id}"`);
52612
- validateCompat(model.compat, `Remote profile "${profileId}" model "${model.id}" compat`);
52613
- validateCacheCapability(model.cacheCapability, `Remote profile "${profileId}" model "${model.id}" cacheCapability`);
52614
- validateWebSearchCapability(model.webSearch, `Remote profile "${profileId}" model "${model.id}" webSearch`);
52615
- validateFileCapabilities(model.fileCapabilities, `Remote profile "${profileId}" model "${model.id}" fileCapabilities`);
52616
- }
52617
- function assertHeadersShape(headers2, label) {
52618
- if (headers2 === void 0) return;
52619
- if (!isPlainRecord(headers2)) throw new Error(`${label} headers must be an object`);
52620
- for (const [name, value] of Object.entries(headers2)) {
52621
- if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name)) throw new Error(`${label} header name ${name || "(empty)"} is invalid`);
52622
- if (typeof value !== "string") throw new Error(`${label} header ${name} must be a string`);
52623
- if (/[\0-\x08\x0A-\x1F\x7F]/.test(value)) throw new Error(`${label} header ${name} contains an invalid control character`);
52624
- }
52625
- }
52626
- function assertRemoteHeadersSafe(headers2, label) {
52627
- assertHeadersShape(headers2, label);
52628
- for (const name of Object.keys(headers2 || {})) {
52629
- if (/(?:authorization|cookie|api[-_]?key|token|secret|credential)/i.test(name)) {
52630
- throw new Error(`${label} must not provide credential-bearing header ${name}`);
52631
- }
52632
- if (HOP_BY_HOP_HEADERS.has(name.toLowerCase())) throw new Error(`${label} must not provide transport header ${name}`);
52633
- }
52634
- }
52635
- function sanitizeRemotePayload(decoded, remote, catalogUrl, allowLocallyInjectedCredential = false) {
52636
- if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new Error("catalog response must be an object");
52637
- assertOnlyKeys(decoded, ["profiles"], "catalog response");
52638
- const sourceProfiles = decoded.profiles;
52639
- if (!sourceProfiles || typeof sourceProfiles !== "object" || Array.isArray(sourceProfiles)) {
52640
- throw new Error("catalog response profiles must be an object");
52641
- }
52642
- const profiles = /* @__PURE__ */ Object.create(null);
52643
- for (const [provider, source] of Object.entries(sourceProfiles)) {
52644
- if (!provider || provider !== provider.trim() || /\s/.test(provider) || !isPlainRecord(source)) throw new Error("catalog contains an invalid profile");
52645
- assertOnlyKeys(source, [
52646
- "baseUrl",
52647
- "endpoints",
52648
- "api",
52649
- "apiKey",
52650
- "apiKeyEnv",
52651
- "headers",
52652
- "displayName",
52653
- "filePlatform",
52654
- "attachmentPlatform",
52655
- "transport",
52656
- "compat",
52657
- "cacheCapability",
52658
- "webSearch",
52659
- "fileCapabilities",
52660
- "models"
52661
- ], `Remote profile "${provider}"`);
52662
- if (Object.prototype.hasOwnProperty.call(source, "apiKey") || Object.prototype.hasOwnProperty.call(source, "apiKeyEnv") && (!allowLocallyInjectedCredential || source.apiKeyEnv !== remote.apiKeyEnv)) {
52663
- throw new Error(`Remote profile "${provider}" must not declare credential fields`);
52664
- }
52665
- if (!source.api || !SUPPORTED_REMOTE_APIS.has(source.api)) throw new Error(`Remote profile "${provider}" has unsupported api`);
52666
- if (!source.baseUrl) throw new Error(`Remote profile "${provider}" has no baseUrl`);
52667
- for (const field of ["baseUrl", "api", "displayName", "filePlatform", "attachmentPlatform", "apiKeyEnv"]) {
52668
- assertOptionalString(source[field], `Remote profile "${provider}" ${field}`);
52669
- }
52670
- validateRemoteEndpoint(source.baseUrl, catalogUrl, `Remote profile "${provider}"`);
52671
- validateProfileEndpoints(source, `Remote profile "${provider}"`);
52672
- for (const [api, endpoint] of Object.entries(source.endpoints ?? {})) {
52673
- validateRemoteEndpoint(endpoint, catalogUrl, `Remote profile "${provider}" endpoints.${api}`);
52674
- }
52675
- if (!Array.isArray(source.models) || source.models.length === 0) throw new Error(`Remote profile "${provider}" has no models`);
52676
- assertRemoteHeadersSafe(source.headers, `Remote profile "${provider}"`);
52677
- validateTransport(source.transport, `Remote profile "${provider}"`);
52678
- validateCompat(source.compat, `Remote profile "${provider}" compat`);
52679
- validateCacheCapability(source.cacheCapability, `Remote profile "${provider}" cacheCapability`);
52680
- validateWebSearchCapability(source.webSearch, `Remote profile "${provider}" webSearch`);
52681
- validateFileCapabilities(source.fileCapabilities, `Remote profile "${provider}" fileCapabilities`);
52682
- const seen = /* @__PURE__ */ new Set();
52683
- for (const model of source.models) {
52684
- if (isPlainRecord(model) && Object.prototype.hasOwnProperty.call(model, "apiKeyEnv") && (!allowLocallyInjectedCredential || model.apiKeyEnv !== remote.apiKeyEnv)) {
52685
- throw new Error(`Remote profile "${provider}" model must not declare credential fields`);
52686
- }
52687
- validateRemoteModel(provider, model);
52688
- assertRemoteHeadersSafe(model.headers, `Remote profile "${provider}" model "${model.id}"`);
52689
- if (seen.has(model.id)) throw new Error(`Remote profile "${provider}" contains duplicate model "${model.id}"`);
52690
- seen.add(model.id);
52691
- }
52692
- const sanitized = {
52693
- baseUrl: source.baseUrl,
52694
- ...source.endpoints === void 0 ? {} : { endpoints: { ...source.endpoints } },
52695
- api: source.api,
52696
- transport: source.transport,
52697
- apiKeyEnv: remote.apiKeyEnv,
52698
- ...source.headers === void 0 ? {} : { headers: { ...source.headers } },
52699
- ...source.displayName === void 0 ? {} : { displayName: source.displayName },
52700
- ...source.filePlatform === void 0 ? {} : { filePlatform: source.filePlatform },
52701
- ...source.attachmentPlatform === void 0 ? {} : { attachmentPlatform: source.attachmentPlatform },
52702
- ...source.compat === void 0 ? {} : { compat: { ...source.compat } },
52703
- ...source.cacheCapability === void 0 ? {} : { cacheCapability: { ...source.cacheCapability } },
52704
- ...source.webSearch === void 0 ? {} : { webSearch: { ...source.webSearch } },
52705
- ...source.fileCapabilities === void 0 ? {} : { fileCapabilities: { ...source.fileCapabilities } },
52706
- models: source.models.map((model) => ({
52707
- id: model.id,
52708
- ...model.api === void 0 ? {} : { api: model.api },
52709
- ...model.name === void 0 ? {} : { name: model.name },
52710
- ...model.reasoning === void 0 ? {} : { reasoning: model.reasoning },
52711
- input: [...model.input],
52712
- cost: {
52713
- input: model.cost.input,
52714
- output: model.cost.output,
52715
- cacheRead: model.cost.cacheRead,
52716
- cacheWrite: model.cost.cacheWrite,
52717
- ...model.cost.cacheWriteLong === void 0 ? {} : { cacheWriteLong: model.cost.cacheWriteLong }
52718
- },
52719
- contextWindow: model.contextWindow,
52720
- maxTokens: model.maxTokens,
52721
- ...model.transport === void 0 ? {} : { transport: model.transport },
52722
- ...model.compat === void 0 ? {} : { compat: { ...model.compat } },
52723
- ...model.cacheCapability === void 0 ? {} : { cacheCapability: { ...model.cacheCapability } },
52724
- ...model.webSearch === void 0 ? {} : { webSearch: { ...model.webSearch } },
52725
- ...model.fileCapabilities === void 0 ? {} : { fileCapabilities: { ...model.fileCapabilities } },
52726
- ...model.headers === void 0 ? {} : { headers: { ...model.headers } },
52727
- apiKeyEnv: remote.apiKeyEnv,
52728
- ...model.displayName === void 0 ? {} : { displayName: model.displayName },
52729
- ...model.filePlatform === void 0 ? {} : { filePlatform: model.filePlatform },
52730
- ...model.attachmentPlatform === void 0 ? {} : { attachmentPlatform: model.attachmentPlatform }
52731
- }))
52732
- };
52733
- validateProfileConfig(provider, sanitized);
52734
- Object.defineProperty(profiles, provider, { value: sanitized, enumerable: true, configurable: true, writable: true });
52735
- }
52736
- return { profiles };
52737
- }
52738
- async function readResponseTextBounded(response, maxBytes) {
52739
- const reader = response.body?.getReader();
52740
- if (!reader) return "";
52741
- const chunks = [];
52742
- let total = 0;
52743
- try {
52744
- while (true) {
52745
- const { done, value } = await reader.read();
52746
- if (done) break;
52747
- if (!value) continue;
52748
- total += value.byteLength;
52749
- if (total > maxBytes) {
52750
- await reader.cancel("catalog response is too large");
52751
- throw new Error("catalog response is too large");
52752
- }
52753
- chunks.push(value);
52754
- }
52755
- return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString("utf8");
52756
- } finally {
52757
- reader.releaseLock();
52758
- }
52759
- }
52760
- function deepMergePlainRecords(base, patch) {
52761
- const result = isPlainRecord(base) ? { ...base } : {};
52762
- if (!isPlainRecord(patch)) return result;
52763
- for (const [key, value] of Object.entries(patch)) {
52764
- const current = result[key];
52765
- result[key] = isPlainRecord(current) && isPlainRecord(value) ? deepMergePlainRecords(current, value) : value;
52766
- }
52767
- return result;
52768
- }
52769
- function validateModelOverrides(value) {
52770
- if (value === void 0) return;
52771
- if (!isPlainRecord(value)) throw new Error("models.json modelOverrides must be an object");
52772
- for (const [key, override] of Object.entries(value)) {
52773
- if (!/^[^\s/]+\/[^\s/]+$/.test(key)) throw new Error(`models.json modelOverrides key must be "provider/modelId": ${key}`);
52774
- if (!isPlainRecord(override)) throw new Error(`models.json modelOverrides["${key}"] must be an object`);
52775
- assertOnlyKeys(override, [...MODEL_OVERRIDE_KEYS], `models.json modelOverrides["${key}"]`);
52776
- if (override.name !== void 0 && (typeof override.name !== "string" || !override.name.trim())) throw new Error(`models.json modelOverrides["${key}"].name must be a non-empty string`);
52777
- if (override.displayName !== void 0 && (typeof override.displayName !== "string" || !override.displayName.trim())) throw new Error(`models.json modelOverrides["${key}"].displayName must be a non-empty string`);
52778
- if (override.reasoning !== void 0 && typeof override.reasoning !== "boolean") throw new Error(`models.json modelOverrides["${key}"].reasoning must be a boolean`);
52779
- if (override.input !== void 0 && (!Array.isArray(override.input) || override.input.length === 0 || override.input.some((kind) => !["text", "image", "audio", "video"].includes(String(kind))))) throw new Error(`models.json modelOverrides["${key}"].input is invalid`);
52780
- if (override.contextWindow !== void 0 && (!Number.isInteger(override.contextWindow) || Number(override.contextWindow) < 1)) throw new Error(`models.json modelOverrides["${key}"].contextWindow is invalid`);
52781
- if (override.maxTokens !== void 0 && (!Number.isInteger(override.maxTokens) || Number(override.maxTokens) < 1)) throw new Error(`models.json modelOverrides["${key}"].maxTokens is invalid`);
52782
- if (override.cost !== void 0) {
52783
- if (!isPlainRecord(override.cost)) throw new Error(`models.json modelOverrides["${key}"].cost must be an object`);
52784
- for (const field of ["input", "output", "cacheRead", "cacheWrite", "cacheWriteLong"]) {
52785
- if (override.cost[field] !== void 0 && (typeof override.cost[field] !== "number" || !Number.isFinite(override.cost[field]) || override.cost[field] < 0)) throw new Error(`models.json modelOverrides["${key}"].cost.${field} must be a non-negative finite number`);
52786
- }
52787
- }
52788
- if (override.headers !== void 0) {
52789
- if (!isPlainRecord(override.headers)) throw new Error(`models.json modelOverrides["${key}"].headers must be an object`);
52790
- for (const [headerName, headerValue] of Object.entries(override.headers)) {
52791
- if (typeof headerValue !== "string") throw new Error(`models.json modelOverrides["${key}"].headers.${headerName} must be a string`);
52792
- }
52793
- }
52794
- validateTransport(override.transport, `Model override "${key}"`);
52795
- validateCompat(override.compat, `models.json modelOverrides["${key}"].compat`);
52796
- validateCacheCapability(override.cacheCapability, `models.json modelOverrides["${key}"].cacheCapability`);
52797
- validateWebSearchCapability(override.webSearch, `models.json modelOverrides["${key}"].webSearch`);
52798
- validateFileCapabilities(override.fileCapabilities, `models.json modelOverrides["${key}"].fileCapabilities`);
52799
- }
52800
- }
52801
- function validateProfileEndpoints(profile, label) {
52802
- if (profile.endpoints === void 0) return;
52803
- if (!isPlainRecord(profile.endpoints)) throw new Error(`${label} endpoints must be an object`);
52804
- for (const [api, value] of Object.entries(profile.endpoints)) {
52805
- if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`${label} endpoints has unsupported api ${api}`);
52806
- try {
52807
- if (typeof value !== "string") throw new Error("invalid URL");
52808
- const endpoint = new URL(value);
52809
- if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
52810
- } catch {
52811
- throw new Error(`${label} endpoints.${api} must be an absolute HTTP(S) URL`);
52812
- }
52813
- }
52814
- }
52815
- function resolveProfileRoute(profile, model) {
52816
- const api = model.api ?? profile.api;
52817
- if (!SUPPORTED_REMOTE_APIS.has(api)) throw new Error(`Model "${model.id}" has unsupported api ${api}`);
52818
- const endpoint = profile.endpoints?.[api];
52819
- if (model.api !== void 0 && endpoint === void 0 && api !== profile.api) {
52820
- throw new Error(`Model "${model.id}" api ${api} requires profile endpoints.${api} (otherwise api must equal profile api)`);
52821
- }
52822
- return { api, baseUrl: endpoint ?? profile.baseUrl };
52823
- }
52824
- function validateProfileConfig(profileId, profileConfig) {
52825
- if (!isPlainRecord(profileConfig)) throw new Error(`Profile "${profileId}" must be an object.`);
52826
- assertOnlyKeys(profileConfig, [
52827
- "baseUrl",
52828
- "endpoints",
52829
- "api",
52830
- "apiKey",
52831
- "apiKeyEnv",
52832
- "headers",
52833
- "displayName",
52834
- "filePlatform",
52835
- "attachmentPlatform",
52836
- "transport",
52837
- "compat",
52838
- "cacheCapability",
52839
- "webSearch",
52840
- "fileCapabilities",
52841
- "models"
52842
- ], `Profile "${profileId}"`);
52843
- const missing = [];
52844
- if (!profileConfig.api) missing.push("api");
52845
- if (!profileConfig.baseUrl) missing.push("baseUrl");
52846
- if (!Array.isArray(profileConfig.models) || profileConfig.models.length === 0) missing.push("models");
52847
- const hasProfileKeySource = Boolean(profileConfig.apiKey || profileConfig.apiKeyEnv);
52848
- const hasModelKeySource = Boolean(
52849
- (profileConfig.models || []).some((model) => Boolean(model.apiKeyEnv))
52850
- );
52851
- if (!hasProfileKeySource && !hasModelKeySource) missing.push("apiKey or apiKeyEnv");
52852
- if (missing.length > 0) {
52853
- throw new Error(
52854
- `Profile "${profileId}" is missing required field${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}.`
52855
- );
52856
- }
52857
- for (const field of ["baseUrl", "api", "apiKey", "displayName", "filePlatform", "attachmentPlatform"]) {
52858
- assertOptionalString(profileConfig[field], `Profile "${profileId}" ${field}`);
52859
- }
52860
- assertOptionalEnvName(profileConfig.apiKeyEnv, `Profile "${profileId}" apiKeyEnv`);
52861
- if (!SUPPORTED_REMOTE_APIS.has(profileConfig.api)) throw new Error(`Profile "${profileId}" has unsupported api ${profileConfig.api}`);
52862
- try {
52863
- const endpoint = new URL(profileConfig.baseUrl);
52864
- if (endpoint.protocol !== "http:" && endpoint.protocol !== "https:") throw new Error("unsupported protocol");
52865
- } catch {
52866
- throw new Error(`Profile "${profileId}" baseUrl must be an absolute HTTP(S) URL`);
52867
- }
52868
- validateProfileEndpoints(profileConfig, `Profile "${profileId}"`);
52869
- assertHeadersShape(profileConfig.headers, `Profile "${profileId}"`);
52870
- validateTransport(profileConfig.transport, `Profile "${profileId}"`);
52871
- validateCompat(profileConfig.compat, `Profile "${profileId}" compat`);
52872
- validateCacheCapability(profileConfig.cacheCapability, `Profile "${profileId}" cacheCapability`);
52873
- validateWebSearchCapability(profileConfig.webSearch, `Profile "${profileId}" webSearch`);
52874
- validateFileCapabilities(profileConfig.fileCapabilities, `Profile "${profileId}" fileCapabilities`);
52875
- const seenModelIds = /* @__PURE__ */ new Set();
52876
- for (const [index, modelConfig] of (profileConfig.models || []).entries()) {
52877
- if (!isPlainRecord(modelConfig)) throw new Error(`Profile "${profileId}" model #${index} must be an object.`);
52878
- assertOnlyKeys(modelConfig, [
52879
- "id",
52880
- "api",
52881
- "name",
52882
- "reasoning",
52883
- "input",
52884
- "cost",
52885
- "contextWindow",
52886
- "maxTokens",
52887
- "transport",
52888
- "compat",
52889
- "cacheCapability",
52890
- "webSearch",
52891
- "fileCapabilities",
52892
- "headers",
52893
- "apiKeyEnv",
52894
- "displayName",
52895
- "filePlatform",
52896
- "attachmentPlatform"
52897
- ], `Profile "${profileId}" model #${index}`);
52898
- const modelMissing = [];
52899
- if (!modelConfig.id) modelMissing.push("id");
52900
- if (!Array.isArray(modelConfig.input) || modelConfig.input.length === 0) modelMissing.push("input");
52901
- if (!modelConfig.cost) modelMissing.push("cost");
52902
- if (!modelConfig.contextWindow) modelMissing.push("contextWindow");
52903
- if (!modelConfig.maxTokens) modelMissing.push("maxTokens");
52904
- if (modelMissing.length > 0) {
52905
- const label = modelConfig.id || `#${index}`;
52906
- throw new Error(
52907
- `Profile "${profileId}" model "${label}" is missing required field${modelMissing.length > 1 ? "s" : ""}: ${modelMissing.join(", ")}.`
52908
- );
52909
- }
52910
- validateRemoteModel(profileId, modelConfig);
52911
- resolveProfileRoute(profileConfig, modelConfig);
52912
- assertHeadersShape(modelConfig.headers, `Profile "${profileId}" model "${modelConfig.id}"`);
52913
- assertOptionalEnvName(modelConfig.apiKeyEnv, `Profile "${profileId}" model "${modelConfig.id}" apiKeyEnv`);
52914
- if (seenModelIds.has(modelConfig.id)) throw new Error(`Profile "${profileId}" contains duplicate model "${modelConfig.id}".`);
52915
- seenModelIds.add(modelConfig.id);
52916
- }
52917
- }
52918
- var ModelRegistry = class {
52919
- models = /* @__PURE__ */ new Map();
52920
- loadError;
52921
- authStorage;
52922
- modelsPath;
52923
- configDefaults;
52924
- modelOrder = [];
52925
- modelOverrides = {};
52926
- extensionOAuthProviders = /* @__PURE__ */ new Map();
52927
- usingExternalProviders = false;
52928
- localProfileIds = /* @__PURE__ */ new Set();
52929
- remoteCredentialEnvByProvider = /* @__PURE__ */ new Map();
52930
- remoteCatalogByProvider = /* @__PURE__ */ new Map();
52931
- remoteCredentialFingerprintByCatalog = /* @__PURE__ */ new Map();
52932
- constructor(authStorage, modelsPath = path3.join(getConfigDir(), "models.json")) {
52933
- this.authStorage = authStorage;
52934
- this.modelsPath = modelsPath;
52935
- this.load();
52936
- }
52937
- upsert(model) {
52938
- let providerModels = this.models.get(model.provider);
52939
- if (!providerModels) {
52940
- providerModels = /* @__PURE__ */ new Map();
52941
- this.models.set(model.provider, providerModels);
52942
- }
52943
- const key = `${model.provider}/${model.id}`;
52944
- if (!providerModels.has(model.id) && !this.modelOrder.includes(key)) {
52945
- this.modelOrder.push(key);
52946
- }
52947
- providerModels.set(model.id, model);
52948
- }
52949
- load() {
52950
- this.loadError = void 0;
52951
- this.models.clear();
52952
- this.modelOrder = [];
52953
- this.modelOverrides = {};
52954
- this.configDefaults = void 0;
52955
- this.usingExternalProviders = false;
52956
- this.localProfileIds.clear();
52957
- this.remoteCredentialEnvByProvider.clear();
52958
- this.remoteCatalogByProvider.clear();
52959
- this.remoteCredentialFingerprintByCatalog.clear();
52960
- try {
52961
- pruneLegacyRemoteCatalogCaches(this.modelsPath);
52962
- } catch (error) {
52963
- this.loadError = error instanceof Error ? error.message : String(error);
52964
- return;
52965
- }
52966
- if (!fs3.existsSync(this.modelsPath)) {
52967
- return;
52968
- }
52969
- try {
52970
- const raw = JSON.parse(fs3.readFileSync(this.modelsPath, "utf-8"));
52971
- if (raw && typeof raw === "object" && "providers" in raw) {
52972
- throw new Error('Legacy models.json format is no longer supported. Use top-level "profiles".');
52973
- }
52974
- validateModelsDocumentShape(raw);
52975
- const remotes = validatedRemoteCatalogs(raw.remoteCatalogs);
52976
- this.modelOverrides = raw.modelOverrides ?? {};
52977
- const activeRemoteSecrets = configuredRemoteCredentialValues(raw);
52978
- scrubActiveSecretsFromRemoteCaches(this.modelsPath, activeRemoteSecrets);
52979
- const configuredProviders = Object.entries(raw.profiles || {});
52980
- this.localProfileIds = new Set(configuredProviders.map(([provider]) => provider));
52981
- const hasConfiguredProviders = configuredProviders.length > 0;
52982
- this.configDefaults = raw.defaults ? {
52983
- provider: raw.defaults.provider,
52984
- modelId: raw.defaults.modelId,
52985
- modelClasses: raw.defaults.modelClasses,
52986
- toolModels: raw.defaults.toolModels
52987
- } : void 0;
52988
- this.usingExternalProviders = hasConfiguredProviders;
52989
- for (const [configuredProvider, providerConfig] of configuredProviders) {
52990
- const provider = configuredProvider;
52991
- validateProfileConfig(provider, providerConfig);
52992
- if (providerConfig.apiKey) {
52993
- this.authStorage.setProviderApiKey(provider, providerConfig.apiKey);
52994
- }
52995
- if (providerConfig.apiKeyEnv) {
52996
- this.authStorage.setProviderEnvVar(
52997
- provider,
52998
- providerConfig.apiKeyEnv
52999
- );
53000
- }
53001
- const existing = this.models.get(provider);
53002
- if (existing && (providerConfig.baseUrl || providerConfig.api || providerConfig.headers || providerConfig.transport)) {
53003
- for (const model of existing.values()) {
53004
- this.upsert({
53005
- ...model,
53006
- baseUrl: providerConfig.baseUrl || model.baseUrl,
53007
- api: providerConfig.api || model.api,
53008
- transport: providerConfig.transport ?? model.transport,
53009
- apiKeyEnv: providerConfig.apiKeyEnv || model.apiKeyEnv,
53010
- displayName: providerConfig.displayName || model.displayName || provider,
53011
- filePlatform: providerConfig.filePlatform || model.filePlatform,
53012
- attachmentPlatform: providerConfig.attachmentPlatform || model.attachmentPlatform,
53013
- cacheCapability: providerConfig.cacheCapability || model.cacheCapability,
53014
- webSearch: providerConfig.webSearch || model.webSearch,
53015
- fileCapabilities: providerConfig.fileCapabilities || model.fileCapabilities,
53016
- headers: providerConfig.headers ? { ...model.headers, ...providerConfig.headers } : model.headers
53017
- });
53018
- }
53019
- }
53020
- for (const customModel of providerConfig.models || []) {
53021
- const baseModel = existing?.get(customModel.id);
53022
- this.upsert({
53023
- id: customModel.id,
53024
- name: customModel.name || baseModel?.name || customModel.id,
53025
- ...resolveProfileRoute(providerConfig, customModel),
53026
- provider,
53027
- reasoning: customModel.reasoning ?? baseModel?.reasoning ?? false,
53028
- input: customModel.input || baseModel?.input || ["text"],
53029
- cost: customModel.cost || baseModel?.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
53030
- contextWindow: customModel.contextWindow || baseModel?.contextWindow || 128e3,
53031
- maxTokens: customModel.maxTokens || baseModel?.maxTokens || 8192,
53032
- apiKeyEnv: customModel.apiKeyEnv || providerConfig.apiKeyEnv || baseModel?.apiKeyEnv,
53033
- displayName: customModel.displayName || providerConfig.displayName || baseModel?.displayName || provider,
53034
- filePlatform: customModel.filePlatform || providerConfig.filePlatform || baseModel?.filePlatform,
53035
- attachmentPlatform: customModel.attachmentPlatform || providerConfig.attachmentPlatform || baseModel?.attachmentPlatform,
53036
- headers: providerConfig.headers ? { ...baseModel?.headers, ...providerConfig.headers, ...customModel.headers } : customModel.headers || baseModel?.headers,
53037
- transport: customModel.transport ?? providerConfig.transport ?? baseModel?.transport,
53038
- compat: customModel.compat || providerConfig.compat || baseModel?.compat,
53039
- cacheCapability: customModel.cacheCapability || providerConfig.cacheCapability || baseModel?.cacheCapability,
53040
- webSearch: customModel.webSearch || providerConfig.webSearch || baseModel?.webSearch,
53041
- fileCapabilities: customModel.fileCapabilities || providerConfig.fileCapabilities || baseModel?.fileCapabilities
53042
- });
53043
- }
53044
- }
53045
- for (const identity of remotes) {
53046
- const credential = process.env[identity.apiKeyEnv];
53047
- if (!credential) continue;
53048
- const fingerprint = credentialFingerprint(this.modelsPath, identity, credential);
53049
- if (!fingerprint) continue;
53050
- const cached = readRemoteCache(this.modelsPath, identity, fingerprint, activeRemoteSecrets);
53051
- if (!cached) continue;
53052
- const owner = remoteIdentityDigest(identity);
53053
- this.remoteCredentialFingerprintByCatalog.set(owner, fingerprint);
53054
- const candidates = Object.entries(cached.payload.profiles || {}).filter(([provider]) => !this.localProfileIds.has(provider));
53055
- if (candidates.some(([provider]) => {
53056
- const existing = this.remoteCatalogByProvider.get(provider);
53057
- return existing !== void 0 && existing !== owner;
53058
- })) continue;
53059
- for (const [provider, profile] of candidates) {
53060
- this.registerRemoteProfile(provider, profile, identity.apiKeyEnv, owner);
53061
- }
53062
- }
53063
- this.applyModelOverrides();
53064
- } catch (error) {
53065
- this.loadError = error instanceof Error ? error.message : String(error);
53066
- }
53067
- }
53068
- /**
53069
- * Re-apply models.json modelOverrides after any (re)materialization pass
53070
- * (initial load, remote catalog refresh). Overrides patch descriptive
53071
- * fields only; nested plain objects deep-merge, arrays/scalars replace.
53072
- */
53073
- applyModelOverrides() {
53074
- for (const [key, override] of Object.entries(this.modelOverrides)) {
53075
- const slash = key.indexOf("/");
53076
- if (slash <= 0) continue;
53077
- const provider = key.slice(0, slash);
53078
- const modelId = key.slice(slash + 1);
53079
- const existing = this.models.get(provider)?.get(modelId);
53080
- if (!existing) continue;
53081
- const patched = { ...existing };
53082
- if (override.name !== void 0) patched.name = override.name;
53083
- if (override.displayName !== void 0) patched.displayName = override.displayName;
53084
- if (override.reasoning !== void 0) patched.reasoning = override.reasoning;
53085
- if (override.input !== void 0) patched.input = [...override.input];
53086
- if (override.contextWindow !== void 0) patched.contextWindow = override.contextWindow;
53087
- if (override.maxTokens !== void 0) patched.maxTokens = override.maxTokens;
53088
- if (override.cost !== void 0) patched.cost = { ...existing.cost, ...override.cost };
53089
- if (override.headers !== void 0) patched.headers = { ...existing.headers, ...override.headers };
53090
- if (override.transport !== void 0) patched.transport = override.transport;
53091
- if (override.compat !== void 0) patched.compat = deepMergePlainRecords(existing.compat, override.compat);
53092
- if (override.cacheCapability !== void 0) patched.cacheCapability = { ...existing.cacheCapability, ...override.cacheCapability };
53093
- if (override.webSearch !== void 0) patched.webSearch = { ...existing.webSearch, ...override.webSearch };
53094
- if (override.fileCapabilities !== void 0) patched.fileCapabilities = deepMergePlainRecords(existing.fileCapabilities, override.fileCapabilities);
53095
- this.upsert(patched);
53096
- }
53097
- }
53098
- registerRemoteProfile(provider, providerConfig, credentialEnv, catalogId) {
53099
- if (this.localProfileIds.has(provider)) return;
53100
- const existingCatalog = this.remoteCatalogByProvider.get(provider);
53101
- if (existingCatalog && existingCatalog !== catalogId) {
53102
- throw new Error(`remote profile "${provider}" is already owned by catalog "${existingCatalog}"`);
53103
- }
53104
- validateProfileConfig(provider, providerConfig);
53105
- this.remoteCatalogByProvider.set(provider, catalogId);
53106
- this.remoteCredentialEnvByProvider.set(provider, credentialEnv);
53107
- this.authStorage.setProviderEnvVar(provider, credentialEnv);
53108
- for (const customModel of providerConfig.models || []) {
53109
- this.upsert({
53110
- id: customModel.id,
53111
- name: customModel.name || customModel.id,
53112
- ...resolveProfileRoute(providerConfig, customModel),
53113
- provider,
53114
- reasoning: customModel.reasoning ?? false,
53115
- input: customModel.input || ["text"],
53116
- cost: customModel.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
53117
- contextWindow: customModel.contextWindow || 128e3,
53118
- maxTokens: customModel.maxTokens || 8192,
53119
- apiKeyEnv: credentialEnv,
53120
- displayName: customModel.displayName || providerConfig.displayName || provider,
53121
- filePlatform: customModel.filePlatform || providerConfig.filePlatform,
53122
- attachmentPlatform: customModel.attachmentPlatform || providerConfig.attachmentPlatform,
53123
- headers: { ...providerConfig.headers, ...customModel.headers },
53124
- transport: customModel.transport ?? providerConfig.transport,
53125
- compat: customModel.compat || providerConfig.compat,
53126
- cacheCapability: customModel.cacheCapability || providerConfig.cacheCapability,
53127
- webSearch: customModel.webSearch || providerConfig.webSearch,
53128
- fileCapabilities: customModel.fileCapabilities || providerConfig.fileCapabilities
53129
- });
53130
- }
53131
- this.usingExternalProviders = true;
53132
- }
53133
- removeRemoteProvider(provider, catalogId) {
53134
- if (this.remoteCatalogByProvider.get(provider) !== catalogId) return;
53135
- this.models.delete(provider);
53136
- this.modelOrder = this.modelOrder.filter((key) => !key.startsWith(`${provider}/`));
53137
- this.remoteCatalogByProvider.delete(provider);
53138
- this.remoteCredentialEnvByProvider.delete(provider);
53139
- }
53140
- removeRemoteCatalogProfiles(catalogId) {
53141
- for (const [provider, owner] of [...this.remoteCatalogByProvider]) {
53142
- if (owner === catalogId) this.removeRemoteProvider(provider, catalogId);
53143
- }
53144
- this.usingExternalProviders = this.localProfileIds.size > 0 || this.remoteCatalogByProvider.size > 0;
53145
- }
53146
- replaceRemoteCatalogProfiles(catalogId, payload, credentialEnv) {
53147
- const candidates = Object.entries(payload.profiles || {}).filter(([provider]) => !this.localProfileIds.has(provider));
53148
- for (const [provider, profile] of candidates) {
53149
- const owner = this.remoteCatalogByProvider.get(provider);
53150
- if (owner && owner !== catalogId) throw new Error(`remote profile "${provider}" is already owned by another catalog identity`);
53151
- validateProfileConfig(provider, profile);
53152
- }
53153
- this.removeRemoteCatalogProfiles(catalogId);
53154
- for (const [provider, profile] of candidates) {
53155
- this.registerRemoteProfile(provider, profile, credentialEnv, catalogId);
53156
- }
53157
- this.applyModelOverrides();
53158
- }
53159
- writeRemoteCache(remote, fingerprint, value) {
53160
- const directory = safeRemoteCacheDirectory(this.modelsPath, true);
53161
- const target = remoteCachePath(this.modelsPath, remote, fingerprint);
53162
- if (fs3.existsSync(target)) {
53163
- const stat2 = fs3.lstatSync(target);
53164
- if (stat2.isSymbolicLink() || !stat2.isFile()) throw new Error(`remote catalog cache entry must be a regular file: ${target}`);
53165
- }
53166
- const temporary = path3.join(directory, `.${path3.basename(target)}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
53167
- try {
53168
- fs3.writeFileSync(temporary, `${JSON.stringify(value)}
53169
- `, { flag: "wx", mode: 384 });
53170
- fs3.renameSync(temporary, target);
53171
- const tombstone = remoteCacheTombstonePath(this.modelsPath, remote, fingerprint);
53172
- if (fs3.existsSync(tombstone)) fs3.unlinkSync(tombstone);
53173
- } finally {
53174
- if (fs3.existsSync(temporary)) fs3.unlinkSync(temporary);
53175
- }
53176
- }
53177
- refreshRemoteCatalogs() {
53178
- const queueKey = path3.resolve(this.modelsPath);
53179
- const previous = remoteRefreshTails.get(queueKey) ?? Promise.resolve();
53180
- const refresh = previous.then(() => this.performRemoteCatalogRefresh());
53181
- const tail = refresh.catch(() => void 0);
53182
- remoteRefreshTails.set(queueKey, tail);
53183
- void tail.finally(() => {
53184
- if (remoteRefreshTails.get(queueKey) === tail) remoteRefreshTails.delete(queueKey);
53185
- });
53186
- return refresh;
53187
- }
53188
- async performRemoteCatalogRefresh() {
53189
- const releaseLock = await acquireRemoteRefreshLock(this.modelsPath);
53190
- try {
53191
- await this.performRemoteCatalogRefreshLocked();
53192
- } finally {
53193
- releaseLock();
53194
- }
53195
- }
53196
- async performRemoteCatalogRefreshLocked() {
53197
- try {
53198
- pruneLegacyRemoteCatalogCaches(this.modelsPath);
53199
- } catch (error) {
53200
- this.loadError = error instanceof Error ? error.message : String(error);
53201
- return;
53202
- }
53203
- if (!fs3.existsSync(this.modelsPath)) {
53204
- for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
53205
- this.remoteCredentialFingerprintByCatalog.clear();
53206
- return;
53207
- }
53208
- let config;
53209
- try {
53210
- const decoded = JSON.parse(fs3.readFileSync(this.modelsPath, "utf8"));
53211
- validateModelsDocumentShape(decoded);
53212
- config = decoded;
53213
- } catch {
53214
- for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
53215
- this.remoteCredentialFingerprintByCatalog.clear();
53216
- return;
53217
- }
53218
- this.modelOverrides = config.modelOverrides ?? {};
53219
- let remotes;
53220
- try {
53221
- remotes = validatedRemoteCatalogs(config.remoteCatalogs);
53222
- } catch (error) {
53223
- for (const owner of new Set(this.remoteCatalogByProvider.values())) this.removeRemoteCatalogProfiles(owner);
53224
- this.remoteCredentialFingerprintByCatalog.clear();
53225
- this.loadError = error instanceof Error ? error.message : String(error);
53226
- return;
53227
- }
53228
- const activeOwners = new Set(remotes.map(remoteIdentityDigest));
53229
- const activeRemoteSecrets = configuredRemoteCredentialValues(config);
53230
- scrubActiveSecretsFromRemoteCaches(this.modelsPath, activeRemoteSecrets);
53231
- for (const owner of new Set(this.remoteCatalogByProvider.values())) {
53232
- if (!activeOwners.has(owner)) this.removeRemoteCatalogProfiles(owner);
53233
- }
53234
- for (const owner of [...this.remoteCredentialFingerprintByCatalog.keys()]) {
53235
- if (!activeOwners.has(owner)) this.remoteCredentialFingerprintByCatalog.delete(owner);
53236
- }
53237
- for (const identity of remotes) {
53238
- const remote = identity;
53239
- const url = new URL(identity.url);
53240
- const catalogOwner = remoteIdentityDigest(identity);
53241
- const apiKey = process.env[remote.apiKeyEnv];
53242
- if (!apiKey) {
53243
- this.removeRemoteCatalogProfiles(catalogOwner);
53244
- this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
53245
- warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: environment variable ${remote.apiKeyEnv} is not set`, activeRemoteSecrets);
53246
- continue;
53247
- }
53248
- const fingerprint = credentialFingerprint(this.modelsPath, identity, apiKey, true);
53249
- const previousFingerprint = this.remoteCredentialFingerprintByCatalog.get(catalogOwner);
53250
- if (previousFingerprint && previousFingerprint !== fingerprint) {
53251
- this.removeRemoteCatalogProfiles(catalogOwner);
53252
- this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
53253
- }
53254
- const cached = readRemoteCache(this.modelsPath, identity, fingerprint, activeRemoteSecrets);
53255
- let payload = cached?.payload;
53256
- let response;
53257
- try {
53258
- const headers2 = { Authorization: `Bearer ${apiKey}` };
53259
- if (cached?.etag) headers2["If-None-Match"] = cached.etag;
53260
- response = await fetch(url, {
53261
- headers: headers2,
53262
- redirect: "manual",
53263
- signal: AbortSignal.timeout(3e3)
53264
- });
53265
- } catch (error) {
53266
- if (!payload) {
53267
- warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
53268
- continue;
53269
- }
53270
- warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" using cached data after a transient fetch failure: ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
53271
- }
53272
- if (response) {
53273
- if (response.status === 304 && payload && cached?.etag && (!response.headers.get("etag") || response.headers.get("etag") === cached.etag)) {
53274
- } else if (response.ok) {
53275
- try {
53276
- const contentLength = Number(response.headers.get("content-length") || 0);
53277
- if (contentLength > MAX_REMOTE_CATALOG_BYTES) throw new Error("catalog response is too large");
53278
- const text = await readResponseTextBounded(response, MAX_REMOTE_CATALOG_BYTES);
53279
- const decoded = JSON.parse(text);
53280
- const etag = response.headers.get("etag") || void 0;
53281
- assertNoSecretSubstrings({ etag, payload: decoded }, activeRemoteSecrets, "remote catalog response");
53282
- payload = sanitizeRemotePayload(decoded, identity, url);
53283
- const envelope = {
53284
- version: REMOTE_CATALOG_CACHE_VERSION,
53285
- identity,
53286
- credentialFingerprint: fingerprint,
53287
- etag,
53288
- payload,
53289
- payloadSha256: payloadDigest(payload)
53290
- };
53291
- this.writeRemoteCache(identity, fingerprint, envelope);
53292
- } catch (error) {
53293
- this.removeRemoteCatalogProfiles(catalogOwner);
53294
- this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
53295
- removeRemoteCache(this.modelsPath, identity, fingerprint);
53296
- warnRemoteCatalog(`[Config] Rejecting invalid remote catalog "${remote.id}": ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
53297
- continue;
53298
- }
53299
- } else if (response.status === 408 || response.status === 429 || response.status >= 500) {
53300
- if (!payload) {
53301
- warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" unavailable: HTTP ${response.status}`, activeRemoteSecrets);
53302
- continue;
53303
- }
53304
- warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" using cached data after transient HTTP ${response.status}`, activeRemoteSecrets);
53305
- } else {
53306
- this.removeRemoteCatalogProfiles(catalogOwner);
53307
- this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
53308
- removeRemoteCache(this.modelsPath, identity, fingerprint);
53309
- warnRemoteCatalog(`[Config] Remote catalog "${remote.id}" rejected: HTTP ${response.status}`, activeRemoteSecrets);
53310
- continue;
53311
- }
53312
- }
53313
- if (!payload) continue;
53314
- try {
53315
- this.replaceRemoteCatalogProfiles(catalogOwner, payload, identity.apiKeyEnv);
53316
- this.remoteCredentialFingerprintByCatalog.set(catalogOwner, fingerprint);
53317
- } catch (error) {
53318
- this.removeRemoteCatalogProfiles(catalogOwner);
53319
- this.remoteCredentialFingerprintByCatalog.delete(catalogOwner);
53320
- removeRemoteCache(this.modelsPath, identity, fingerprint);
53321
- warnRemoteCatalog(`[Config] Ignoring conflicting remote catalog "${remote.id}": ${safeRemoteError(error, activeRemoteSecrets)}`, activeRemoteSecrets);
53322
- }
53323
- }
53324
- }
53325
- getConfigDefaults() {
53326
- return this.configDefaults;
53327
- }
53328
- resolveConfiguredRoute(purpose, route) {
53329
- if (!route?.provider || !route?.modelId) return void 0;
53330
- const requiredCapability = requiredCapabilityForToolPurpose(purpose);
53331
- const model = this.find(route.provider, route.modelId);
53332
- if (!model) {
53333
- return {
53334
- purpose,
53335
- requiredCapability,
53336
- routeSource: "unavailable",
53337
- fallbackReason: `models.json defaults.toolModels.${purpose} points to missing model ${route.provider}/${route.modelId}`
53338
- };
53339
- }
53340
- if (!modelSupportsToolPurpose(model, purpose)) {
53341
- return {
53342
- purpose,
53343
- requiredCapability,
53344
- routeSource: "unavailable",
53345
- model,
53346
- fallbackReason: `models.json defaults.toolModels.${purpose} points to ${model.provider}/${model.id}, but it does not declare ${requiredCapability} capability`
53347
- };
53348
- }
53349
- const apiKey = this.getApiKey(model);
53350
- if (!apiKey) {
53351
- return {
53352
- purpose,
53353
- requiredCapability,
53354
- routeSource: "unavailable",
53355
- model,
53356
- fallbackReason: `no API key available for models.json defaults.toolModels.${purpose} (${model.provider}/${model.id})`
53357
- };
53358
- }
53359
- return { purpose, requiredCapability, routeSource: "explicit", model, apiKey };
53360
- }
53361
- resolveToolModel(purpose, currentModel) {
53362
- return this.resolveToolModelCandidates(purpose, currentModel)[0] ?? {
53363
- purpose,
53364
- requiredCapability: requiredCapabilityForToolPurpose(purpose),
53365
- routeSource: "unavailable",
53366
- fallbackReason: `No configured model declares ${requiredCapabilityForToolPurpose(purpose)} capability for ${purpose}.`
53367
- };
53368
- }
53369
- resolveToolModelCandidates(purpose, currentModel) {
53370
- const requiredCapability = requiredCapabilityForToolPurpose(purpose);
53371
- const candidates = [];
53372
- const seen = /* @__PURE__ */ new Set();
53373
- const add = (decision) => {
53374
- if (!decision) return;
53375
- if (!decision.model) {
53376
- if (decision.routeSource === "unavailable") candidates.push(decision);
53377
- return;
53378
- }
53379
- const key = `${decision.model.provider}/${decision.model.id}`;
53380
- if (seen.has(key)) return;
53381
- seen.add(key);
53382
- candidates.push(decision);
53383
- };
53384
- const explicit = this.resolveConfiguredRoute(purpose, this.configDefaults?.toolModels?.[purpose]);
53385
- add(explicit);
53386
- if (currentModel && modelSupportsToolPurpose(currentModel, purpose)) {
53387
- const apiKey = this.getApiKey(currentModel);
53388
- if (apiKey) {
53389
- add({ purpose, requiredCapability, routeSource: "current_model", model: currentModel, apiKey });
53390
- }
53391
- }
53392
- const modelClassCandidates = [];
53393
- for (const modelClass of MODEL_CLASS_FALLBACK_ORDER) {
53394
- const resolved = this.resolveModelClass(modelClass);
53395
- if (resolved.model && resolved.apiKey && modelSupportsToolPurpose(resolved.model, purpose)) {
53396
- modelClassCandidates.push({
53397
- purpose,
53398
- requiredCapability,
53399
- routeSource: "model_class",
53400
- model: resolved.model,
53401
- apiKey: resolved.apiKey
53402
- });
53403
- }
53404
- }
53405
- for (const decision of sortToolModelCandidatesByCapability(purpose, modelClassCandidates)) add(decision);
53406
- const configuredCandidates = [];
53407
- for (const model of this.getAllInConfigOrder()) {
53408
- if (!modelSupportsToolPurpose(model, purpose)) continue;
53409
- const apiKey = this.getApiKey(model);
53410
- if (!apiKey) continue;
53411
- configuredCandidates.push({ purpose, requiredCapability, routeSource: "configured_model", model, apiKey });
53412
- }
53413
- for (const decision of sortToolModelCandidatesByCapability(purpose, configuredCandidates)) add(decision);
53414
- if (candidates.some((candidate) => candidate.model)) {
53415
- return candidates.filter((candidate) => candidate.model);
53416
- }
53417
- return candidates.length > 0 ? candidates : [{
53418
- purpose,
53419
- requiredCapability,
53420
- routeSource: "unavailable",
53421
- fallbackReason: `No configured model declares ${requiredCapability} capability for ${purpose}.`
53422
- }];
53423
- }
53424
- validateExplicitToolModelRoutes() {
53425
- const routes = this.configDefaults?.toolModels || {};
53426
- const results = [];
53427
- for (const purpose of Object.keys(routes)) {
53428
- const decision = this.resolveConfiguredRoute(purpose, routes[purpose]);
53429
- if (decision) results.push(decision);
53430
- }
53431
- return results;
53432
- }
53433
- resolveModelClass(modelClass) {
53434
- const configured = this.configDefaults?.modelClasses?.[modelClass];
53435
- if (!configured?.provider || !configured?.modelId) {
53436
- return { fallbackReason: `models.json defaults.modelClasses.${modelClass} is not configured` };
53437
- }
53438
- const model = this.find(configured.provider, configured.modelId);
53439
- if (!model) {
53440
- return { fallbackReason: `models.json defaults.modelClasses.${modelClass} points to missing model ${configured.provider}/${configured.modelId}` };
53441
- }
53442
- const apiKey = this.getApiKey(model);
53443
- if (!apiKey) {
53444
- return { model, fallbackReason: `no API key available for model class ${modelClass} (${configured.provider}/${configured.modelId})` };
53445
- }
53446
- return { model, apiKey };
53447
- }
53448
- /** Resolve an explicit model reference for user-requested overrides.
53449
- * Accepts "provider/model-id" (exact lookup) or a bare model id (only
53450
- * when it matches exactly one configured model). Never guesses across
53451
- * providers; ambiguity and missing keys are reported as fallback reasons. */
53452
- resolveModelRef(ref) {
53453
- const trimmed = ref.trim();
53454
- if (!trimmed) {
53455
- return { fallbackReason: "empty model reference" };
53456
- }
53457
- const separator = trimmed.indexOf("/");
53458
- if (separator >= 0) {
53459
- if (separator === 0 || separator === trimmed.length - 1) {
53460
- return { fallbackReason: `invalid model reference "${trimmed}"; expected provider/model-id` };
53461
- }
53462
- const provider = trimmed.slice(0, separator);
53463
- const modelId = trimmed.slice(separator + 1);
53464
- const model2 = this.find(provider, modelId);
53465
- if (!model2) {
53466
- return { fallbackReason: `model "${trimmed}" is not configured` };
53467
- }
53468
- const apiKey2 = this.getApiKey(model2);
53469
- if (!apiKey2) {
53470
- return { model: model2, fallbackReason: `no API key available for model "${trimmed}"` };
53471
- }
53472
- return { model: model2, apiKey: apiKey2 };
53473
- }
53474
- const matches = this.getAll().filter((model2) => model2.id === trimmed);
53475
- if (matches.length === 0) {
53476
- return { fallbackReason: `model "${trimmed}" is not configured; use provider/model-id` };
53477
- }
53478
- if (matches.length > 1) {
53479
- return { fallbackReason: `model "${trimmed}" is ambiguous across providers (${matches.map((model2) => `${model2.provider}/${model2.id}`).join(", ")}); use provider/model-id` };
53480
- }
53481
- const model = matches[0];
53482
- const apiKey = this.getApiKey(model);
53483
- if (!apiKey) {
53484
- return { model, fallbackReason: `no API key available for model "${model.provider}/${model.id}"` };
53485
- }
53486
- return { model, apiKey };
53487
- }
53488
- hasExternalProviderConfig() {
53489
- return this.usingExternalProviders;
53490
- }
53491
- getLoadError() {
53492
- return this.loadError;
53493
- }
53494
- find(provider, modelId) {
53495
- return this.models.get(provider)?.get(modelId);
53496
- }
53497
- getAll() {
53498
- const all = [];
53499
- for (const providerModels of this.models.values()) {
53500
- all.push(...providerModels.values());
53501
- }
53502
- return all.sort((a, b2) => `${a.provider}/${a.id}`.localeCompare(`${b2.provider}/${b2.id}`));
53503
- }
53504
- getAllInConfigOrder() {
53505
- const ordered = [];
53506
- const seen = /* @__PURE__ */ new Set();
53507
- for (const key of this.modelOrder) {
53508
- const [provider, ...modelParts] = key.split("/");
53509
- const modelId = modelParts.join("/");
53510
- const model = this.find(provider, modelId);
53511
- if (!model) continue;
53512
- ordered.push(model);
53513
- seen.add(key);
53514
- }
53515
- for (const model of this.getAll()) {
53516
- const key = `${model.provider}/${model.id}`;
53517
- if (!seen.has(key)) ordered.push(model);
53518
- }
53519
- return ordered;
53520
- }
53521
- getAvailable() {
53522
- return this.getAll().filter((model) => !!this.getApiKey(model));
53523
- }
53524
- getByProvider(provider) {
53525
- return [...this.models.get(provider)?.values() || []].sort((a, b2) => a.id.localeCompare(b2.id));
53526
- }
53527
- listAvailableModels() {
53528
- return this.getAll().map((model) => `${model.provider}/${model.id}`);
53529
- }
53530
- getApiKey(model) {
53531
- const remoteEnv = this.remoteCredentialEnvByProvider.get(model.provider);
53532
- if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
53533
- return this.authStorage.getApiKey(model.provider, model.apiKeyEnv);
53534
- }
53535
- getApiKeyForProvider(provider) {
53536
- const remoteEnv = this.remoteCredentialEnvByProvider.get(provider);
53537
- if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
53538
- return this.authStorage.getApiKey(provider);
53539
- }
53540
- /**
53541
- * Register a provider at runtime (extension API). Not persisted to
53542
- * models.json: runtime registrations live for the process unless the
53543
- * extension registers them again. Returns an unregister handle that
53544
- * restores the provider's previous state (models, order, env binding).
53545
- *
53546
- * When the provider already exists (local profile or remote catalog),
53547
- * models are merged by id: registered models upsert over existing entries
53548
- * with the same id; existing entries not named in `config.models` survive.
53549
- * baseUrl/api/headers patch every model of that provider (existing and
53550
- * new) when provided.
53551
- */
53552
- registerProvider(provider, config) {
53553
- validateExtensionProviderConfig(provider, config);
53554
- const previousModels = this.models.get(provider) ? new Map(this.models.get(provider)) : void 0;
53555
- const previousOrder = [...this.modelOrder];
53556
- const previousEnvVar = this.authStorage.getProviderEnvVar(provider);
53557
- if (config.apiKey) {
53558
- this.authStorage.setRuntimeApiKey(provider, config.apiKey);
53559
- }
53560
- if (config.apiKeyEnv) {
53561
- this.authStorage.setProviderEnvVar(provider, config.apiKeyEnv);
53562
- }
53563
- const existing = this.models.get(provider);
53564
- if (existing && (config.baseUrl || config.api || config.headers || config.transport)) {
53565
- for (const model of existing.values()) {
53566
- this.upsert({
53567
- ...model,
53568
- baseUrl: config.baseUrl || model.baseUrl,
53569
- api: config.api || model.api,
53570
- transport: config.transport ?? model.transport,
53571
- headers: config.headers ? { ...model.headers, ...config.headers } : model.headers
53572
- });
53573
- }
53574
- }
53575
- for (const customModel of config.models ?? []) {
53576
- const baseModel = this.models.get(provider)?.get(customModel.id);
53577
- this.upsert({
53578
- id: customModel.id,
53579
- name: customModel.name || baseModel?.name || customModel.id,
53580
- api: config.api || baseModel?.api || "openai-completions",
53581
- provider,
53582
- baseUrl: config.baseUrl || baseModel?.baseUrl || "",
53583
- reasoning: customModel.reasoning ?? baseModel?.reasoning ?? false,
53584
- input: customModel.input || baseModel?.input || ["text"],
53585
- cost: customModel.cost || baseModel?.cost || { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
53586
- contextWindow: customModel.contextWindow || baseModel?.contextWindow || 128e3,
53587
- maxTokens: customModel.maxTokens || baseModel?.maxTokens || 8192,
53588
- apiKeyEnv: config.apiKeyEnv || baseModel?.apiKeyEnv,
53589
- displayName: customModel.displayName || baseModel?.displayName || provider,
53590
- headers: config.headers ? { ...baseModel?.headers, ...config.headers, ...customModel.headers } : customModel.headers || baseModel?.headers,
53591
- transport: customModel.transport ?? config.transport ?? baseModel?.transport,
53592
- compat: customModel.compat || baseModel?.compat,
53593
- cacheCapability: customModel.cacheCapability || baseModel?.cacheCapability,
53594
- webSearch: customModel.webSearch || baseModel?.webSearch,
53595
- fileCapabilities: customModel.fileCapabilities || baseModel?.fileCapabilities
53596
- });
53597
- }
53598
- this.applyModelOverrides();
53599
- this.usingExternalProviders = true;
53600
- const registeredOAuth = config.oauth;
53601
- if (registeredOAuth) this.extensionOAuthProviders.set(provider, registeredOAuth);
53602
- return () => {
53603
- if (previousModels) this.models.set(provider, previousModels);
53604
- else this.models.delete(provider);
53605
- this.modelOrder = previousOrder;
53606
- this.authStorage.setRuntimeApiKey(provider, void 0);
53607
- this.authStorage.setProviderEnvVar(provider, previousEnvVar);
53608
- if (registeredOAuth) this.extensionOAuthProviders.delete(provider);
53609
- this.applyModelOverrides();
53610
- };
53611
- }
53612
- /** OAuth flow declared by an extension-registered provider, if any. */
53613
- getExtensionOAuth(provider) {
53614
- return this.extensionOAuthProviders.get(provider);
53615
- }
53616
- /**
53617
- * Restore persisted OAuth credentials now that extensions have registered
53618
- * their providers: refresh expired tokens when the extension declares
53619
- * refreshToken, and drop the runtime binding when a token cannot be
53620
- * recovered (getApiKey then reports the provider as unauthenticated).
53621
- * Never throws; returns per-provider outcomes for the host to surface.
53622
- */
53623
- async restorePersistedOAuth() {
53624
- const authStorage = this.authStorage;
53625
- const results = [];
53626
- for (const provider of authStorage.getOAuthProviderNames()) {
53627
- const credentials = authStorage.getOAuthCredentials(provider);
53628
- if (!credentials?.access) continue;
53629
- const expired = credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_RESTORE_LEEWAY_MS;
53630
- if (!expired) continue;
53631
- const oauth = this.extensionOAuthProviders.get(provider);
53632
- if (!oauth?.refreshToken || !credentials.refresh) {
53633
- authStorage.setRuntimeApiKey(provider, void 0);
53634
- results.push({ provider, action: "not-refreshable", detail: "token expired and no refresh flow" });
53635
- continue;
53636
- }
53637
- try {
53638
- const next = await withTimeout(
53639
- oauth.refreshToken({
53640
- access: credentials.access,
53641
- refresh: credentials.refresh,
53642
- expires: credentials.expires
53643
- }),
53644
- OAUTH_REFRESH_TIMEOUT_MS,
53645
- `${provider} refreshToken timed out after ${OAUTH_REFRESH_TIMEOUT_MS}ms`
53646
- );
53647
- const merged = { ...credentials, ...next };
53648
- authStorage.setOAuthCredentials(provider, merged);
53649
- authStorage.setRuntimeApiKey(provider, merged.access);
53650
- results.push({ provider, action: "refreshed" });
53651
- } catch (error) {
53652
- authStorage.setRuntimeApiKey(provider, void 0);
53653
- results.push({ provider, action: "refresh-failed", detail: error instanceof Error ? error.message : String(error) });
53654
- }
53655
- }
53656
- return results;
53657
- }
53658
- /** Credential store backing this registry (for OAuth persistence). */
53659
- getAuthStorage() {
53660
- return this.authStorage;
53661
- }
53662
- };
53663
-
53664
- // src/core/settings-manager.ts
53665
- import * as fs4 from "fs";
53666
- import * as path4 from "path";
53667
51749
  function getDisabledToolNames(settingsManager) {
53668
51750
  const disabled = new Set(typeof settingsManager?.getDisabledTools === "function" ? settingsManager.getDisabledTools() : []);
53669
51751
  if (disabled.has("bash") || disabled.has("shell")) {
@@ -53679,8 +51761,31 @@ function filterEnabledTools(tools, settingsManager) {
53679
51761
  function isPlainObject(value) {
53680
51762
  return typeof value === "object" && value !== null && !Array.isArray(value);
53681
51763
  }
51764
+ var COUPLED_SETTINGS_KEY_GROUPS = [
51765
+ // settings.json (and models-defaults views) spell the pair
51766
+ // defaultProvider/defaultModel; the legacy config.json mirror spells it
51767
+ // provider/modelId. Both documents merge through this function, and each
51768
+ // group is a no-op for the document that lacks its keys, so listing both
51769
+ // spellings closes the splice in either file.
51770
+ ["defaultProvider", "defaultModel"],
51771
+ ["provider", "modelId"]
51772
+ ];
53682
51773
  function mergeSnapshotDelta(atLoad, current, onDisk) {
53683
- return mergeDeltaNode(atLoad, current, onDisk);
51774
+ const merged = mergeDeltaNode(atLoad, current, onDisk);
51775
+ if (!isPlainObject(merged) || !isPlainObject(current)) return merged;
51776
+ const load = isPlainObject(atLoad) ? atLoad : {};
51777
+ for (const group of COUPLED_SETTINGS_KEY_GROUPS) {
51778
+ const groupChanged = group.some(
51779
+ (key) => JSON.stringify(load[key]) !== JSON.stringify(current[key])
51780
+ );
51781
+ if (!groupChanged) continue;
51782
+ for (const key of group) {
51783
+ const after = Object.hasOwn(current, key) ? current[key] : void 0;
51784
+ if (after === void 0) delete merged[key];
51785
+ else setOwnDataProperty(merged, key, after);
51786
+ }
51787
+ }
51788
+ return merged;
53684
51789
  }
53685
51790
  function mergeDeltaNode(load, cur, disk) {
53686
51791
  if (!isPlainObject(disk)) {
@@ -53740,29 +51845,29 @@ function cloneJsonDocument(value) {
53740
51845
  return JSON.parse(JSON.stringify(value));
53741
51846
  }
53742
51847
  function writeJsonAtomic(filePath, value) {
53743
- fs4.mkdirSync(path4.dirname(filePath), { recursive: true });
51848
+ fs2.mkdirSync(path2.dirname(filePath), { recursive: true });
53744
51849
  const tempPath = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
53745
51850
  try {
53746
- const fd = fs4.openSync(tempPath, "w");
51851
+ const fd = fs2.openSync(tempPath, "w");
53747
51852
  try {
53748
- fs4.writeFileSync(fd, JSON.stringify(value, null, 2));
53749
- fs4.fsyncSync(fd);
51853
+ fs2.writeFileSync(fd, JSON.stringify(value, null, 2));
51854
+ fs2.fsyncSync(fd);
53750
51855
  } finally {
53751
- fs4.closeSync(fd);
51856
+ fs2.closeSync(fd);
53752
51857
  }
53753
- fs4.renameSync(tempPath, filePath);
51858
+ fs2.renameSync(tempPath, filePath);
53754
51859
  try {
53755
- const dirFd = fs4.openSync(path4.dirname(filePath), "r");
51860
+ const dirFd = fs2.openSync(path2.dirname(filePath), "r");
53756
51861
  try {
53757
- fs4.fsyncSync(dirFd);
51862
+ fs2.fsyncSync(dirFd);
53758
51863
  } finally {
53759
- fs4.closeSync(dirFd);
51864
+ fs2.closeSync(dirFd);
53760
51865
  }
53761
51866
  } catch {
53762
51867
  }
53763
51868
  } catch (error) {
53764
51869
  try {
53765
- fs4.unlinkSync(tempPath);
51870
+ fs2.unlinkSync(tempPath);
53766
51871
  } catch {
53767
51872
  }
53768
51873
  throw error;
@@ -53790,9 +51895,9 @@ var SettingsManager = class {
53790
51895
  this.legacyConfigLastWritten = cloneJsonDocument(this.legacyConfig);
53791
51896
  }
53792
51897
  readJson(filePath) {
53793
- if (!fs4.existsSync(filePath)) return null;
51898
+ if (!fs2.existsSync(filePath)) return null;
53794
51899
  try {
53795
- return JSON.parse(fs4.readFileSync(filePath, "utf-8"));
51900
+ return JSON.parse(fs2.readFileSync(filePath, "utf-8"));
53796
51901
  } catch {
53797
51902
  return null;
53798
51903
  }
@@ -53804,7 +51909,7 @@ var SettingsManager = class {
53804
51909
  return this.readJson(this.legacyConfigPath) || {};
53805
51910
  }
53806
51911
  ensureDir() {
53807
- fs4.mkdirSync(getConfigDir(), { recursive: true });
51912
+ fs2.mkdirSync(getConfigDir(), { recursive: true });
53808
51913
  }
53809
51914
  writeSettings() {
53810
51915
  this.ensureDir();
@@ -53830,9 +51935,9 @@ var SettingsManager = class {
53830
51935
  mergeOntoDisk(filePath, lastWritten, current) {
53831
51936
  let onDisk = null;
53832
51937
  let corrupt = false;
53833
- if (fs4.existsSync(filePath)) {
51938
+ if (fs2.existsSync(filePath)) {
53834
51939
  try {
53835
- onDisk = JSON.parse(fs4.readFileSync(filePath, "utf-8"));
51940
+ onDisk = JSON.parse(fs2.readFileSync(filePath, "utf-8"));
53836
51941
  } catch {
53837
51942
  corrupt = true;
53838
51943
  }
@@ -54053,19 +52158,19 @@ function checkShell() {
54053
52158
  }
54054
52159
  function canWriteDirectory(dir) {
54055
52160
  try {
54056
- fs5.mkdirSync(dir, { recursive: true });
54057
- const probe = path5.join(dir, `.pie-doctor-${process.pid}-${Date.now()}`);
54058
- fs5.writeFileSync(probe, "ok", "utf8");
54059
- fs5.rmSync(probe, { force: true });
52161
+ fs3.mkdirSync(dir, { recursive: true });
52162
+ const probe = path3.join(dir, `.pie-doctor-${process.pid}-${Date.now()}`);
52163
+ fs3.writeFileSync(probe, "ok", "utf8");
52164
+ fs3.rmSync(probe, { force: true });
54060
52165
  return { ok: true };
54061
52166
  } catch (error) {
54062
52167
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
54063
52168
  }
54064
52169
  }
54065
52170
  function isExecutable(candidate) {
54066
- if (!candidate || !fs5.existsSync(candidate)) return false;
52171
+ if (!candidate || !fs3.existsSync(candidate)) return false;
54067
52172
  try {
54068
- fs5.accessSync(candidate, fs5.constants.X_OK);
52173
+ fs3.accessSync(candidate, fs3.constants.X_OK);
54069
52174
  return true;
54070
52175
  } catch {
54071
52176
  return os.platform() === "win32";
@@ -54075,7 +52180,7 @@ function findOnPath(names) {
54075
52180
  for (const dir of (process.env.PATH || "").split(delimiter)) {
54076
52181
  if (!dir) continue;
54077
52182
  for (const name of names) {
54078
- const candidate = path5.join(dir, name);
52183
+ const candidate = path3.join(dir, name);
54079
52184
  if (isExecutable(candidate)) return candidate;
54080
52185
  }
54081
52186
  }
@@ -54091,10 +52196,10 @@ function findDoctorChromeExecutable() {
54091
52196
  "/Applications/Chromium.app/Contents/MacOS/Chromium",
54092
52197
  "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"
54093
52198
  ] : os.platform() === "win32" ? [
54094
- path5.join(process.env.PROGRAMFILES || "C:\\Program Files", "Google", "Chrome", "Application", "chrome.exe"),
54095
- path5.join(process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)", "Google", "Chrome", "Application", "chrome.exe"),
54096
- path5.join(process.env.LOCALAPPDATA || path5.join(home, "AppData", "Local"), "Google", "Chrome", "Application", "chrome.exe"),
54097
- path5.join(process.env.PROGRAMFILES || "C:\\Program Files", "Microsoft", "Edge", "Application", "msedge.exe")
52199
+ path3.join(process.env.PROGRAMFILES || "C:\\Program Files", "Google", "Chrome", "Application", "chrome.exe"),
52200
+ path3.join(process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)", "Google", "Chrome", "Application", "chrome.exe"),
52201
+ path3.join(process.env.LOCALAPPDATA || path3.join(home, "AppData", "Local"), "Google", "Chrome", "Application", "chrome.exe"),
52202
+ path3.join(process.env.PROGRAMFILES || "C:\\Program Files", "Microsoft", "Edge", "Application", "msedge.exe")
54098
52203
  ] : [
54099
52204
  "/usr/bin/google-chrome",
54100
52205
  "/usr/bin/google-chrome-stable",
@@ -54110,8 +52215,8 @@ function findDoctorChromeExecutable() {
54110
52215
  }
54111
52216
  function resolveDoctorChromeDevtoolsAxiCli() {
54112
52217
  try {
54113
- const runtime = path5.join(getBuiltinDir(), "skills", "chrome-devtools-axi", "chrome-devtools-axi-runtime.js");
54114
- return fs5.existsSync(runtime) ? runtime : void 0;
52218
+ const runtime = path3.join(getBuiltinDir(), "skills", "chrome-devtools-axi", "chrome-devtools-axi-runtime.js");
52219
+ return fs3.existsSync(runtime) ? runtime : void 0;
54115
52220
  } catch {
54116
52221
  return void 0;
54117
52222
  }
@@ -54139,10 +52244,10 @@ function checkChromeDevtoolsAxiCli() {
54139
52244
  function checkComputerUse() {
54140
52245
  if (process.platform === "darwin") {
54141
52246
  const envAppPath = process.env.PIE_COMPUTER_USE_HELPER_APP_PATH?.trim();
54142
- const systemAppPath = path5.join("/Applications", "pie-computer-use.app");
54143
- const systemAppUsable = fs5.existsSync(systemAppPath) && canWriteDirectory(path5.dirname(systemAppPath)).ok;
54144
- const appPath = envAppPath || (systemAppUsable ? systemAppPath : path5.join(getConfigDir(), "computer-use", "pie-computer-use.app"));
54145
- const executable = path5.join(appPath, "Contents", "MacOS", "pie-computer-use");
52247
+ const systemAppPath = path3.join("/Applications", "pie-computer-use.app");
52248
+ const systemAppUsable = fs3.existsSync(systemAppPath) && canWriteDirectory(path3.dirname(systemAppPath)).ok;
52249
+ const appPath = envAppPath || (systemAppUsable ? systemAppPath : path3.join(getConfigDir(), "computer-use", "pie-computer-use.app"));
52250
+ const executable = path3.join(appPath, "Contents", "MacOS", "pie-computer-use");
54146
52251
  if (isExecutable(executable)) {
54147
52252
  return {
54148
52253
  id: "computer_use_helper",
@@ -54161,7 +52266,7 @@ function checkComputerUse() {
54161
52266
  };
54162
52267
  }
54163
52268
  if (process.platform === "linux") {
54164
- const helperPath = process.env.PIE_COMPUTER_USE_LINUX_HELPER_PATH ?? path5.join(getConfigDir(), "helpers", "computer-use", "linux-bridge");
52269
+ const helperPath = process.env.PIE_COMPUTER_USE_LINUX_HELPER_PATH ?? path3.join(getConfigDir(), "helpers", "computer-use", "linux-bridge");
54165
52270
  const installed = isExecutable(helperPath);
54166
52271
  return {
54167
52272
  id: "computer_use_helper",
@@ -54172,8 +52277,8 @@ function checkComputerUse() {
54172
52277
  };
54173
52278
  }
54174
52279
  if (process.platform === "win32") {
54175
- const helperPath = process.env.PIE_COMPUTER_USE_WINDOWS_HELPER_PATH ?? path5.join(getConfigDir(), "helpers", "computer-use", "windows-bridge.exe");
54176
- const installed = fs5.existsSync(helperPath);
52280
+ const helperPath = process.env.PIE_COMPUTER_USE_WINDOWS_HELPER_PATH ?? path3.join(getConfigDir(), "helpers", "computer-use", "windows-bridge.exe");
52281
+ const installed = fs3.existsSync(helperPath);
54177
52282
  return {
54178
52283
  id: "computer_use_helper",
54179
52284
  label: "computer-use helper",
@@ -54211,8 +52316,8 @@ function isLiveUnityInstance(instance, nowUnix = Math.floor(Date.now() / 1e3)) {
54211
52316
  return isProcessAlive(Number(instance.pid || 0));
54212
52317
  }
54213
52318
  function checkUnityRegistry() {
54214
- const registryDir = path5.join(os.homedir(), ".pie-unity", "instances");
54215
- if (!fs5.existsSync(registryDir)) {
52319
+ const registryDir = path3.join(os.homedir(), ".pie-unity", "instances");
52320
+ if (!fs3.existsSync(registryDir)) {
54216
52321
  return {
54217
52322
  id: "unity_bridge",
54218
52323
  label: "Unity bridge",
@@ -54223,12 +52328,12 @@ function checkUnityRegistry() {
54223
52328
  }
54224
52329
  try {
54225
52330
  const nowUnix = Math.floor(Date.now() / 1e3);
54226
- const files = fs5.readdirSync(registryDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path5.join(registryDir, entry.name));
52331
+ const files = fs3.readdirSync(registryDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path3.join(registryDir, entry.name));
54227
52332
  let malformedFiles = 0;
54228
52333
  let invalidFiles = 0;
54229
52334
  const liveInstances = files.map((filePath) => {
54230
52335
  try {
54231
- const parsed = JSON.parse(fs5.readFileSync(filePath, "utf8").replace(/^\uFEFF/, ""));
52336
+ const parsed = JSON.parse(fs3.readFileSync(filePath, "utf8").replace(/^\uFEFF/, ""));
54232
52337
  if (!isRecord(parsed)) {
54233
52338
  invalidFiles += 1;
54234
52339
  return null;
@@ -54302,13 +52407,13 @@ async function runDoctor() {
54302
52407
  const packageDir = getPackageDir();
54303
52408
  let dir = packageDir;
54304
52409
  let lockPath;
54305
- while (dir !== path5.dirname(dir)) {
54306
- const candidate = path5.join(dir, "package-lock.json");
54307
- if (fs5.existsSync(candidate)) {
52410
+ while (dir !== path3.dirname(dir)) {
52411
+ const candidate = path3.join(dir, "package-lock.json");
52412
+ if (fs3.existsSync(candidate)) {
54308
52413
  lockPath = candidate;
54309
52414
  break;
54310
52415
  }
54311
- dir = path5.dirname(dir);
52416
+ dir = path3.dirname(dir);
54312
52417
  }
54313
52418
  checks.push({
54314
52419
  id: "package_lock",
@@ -54501,10 +52606,10 @@ Disable or narrow capabilities:
54501
52606
  }
54502
52607
 
54503
52608
  // src/commands/models-config.ts
54504
- import * as fs6 from "node:fs";
54505
- import * as path6 from "node:path";
52609
+ import * as fs4 from "node:fs";
52610
+ import * as path4 from "node:path";
54506
52611
  function getDefaultModelsPath() {
54507
- return path6.join(getConfigDir(), "models.json");
52612
+ return path4.join(getConfigDir(), "models.json");
54508
52613
  }
54509
52614
  function createModelsTemplate() {
54510
52615
  const template = {
@@ -54599,7 +52704,7 @@ function createModelsTemplate() {
54599
52704
  `;
54600
52705
  }
54601
52706
  function resolveModelsPath(input) {
54602
- return input ? path6.resolve(input) : getDefaultModelsPath();
52707
+ return input ? path4.resolve(input) : getDefaultModelsPath();
54603
52708
  }
54604
52709
  function initModelsConfig(options = {}) {
54605
52710
  const targetPath = resolveModelsPath(options.path);
@@ -54607,16 +52712,16 @@ function initModelsConfig(options = {}) {
54607
52712
  if (options.stdout) {
54608
52713
  return { path: targetPath, content, wrote: false };
54609
52714
  }
54610
- if (fs6.existsSync(targetPath) && !options.force) {
52715
+ if (fs4.existsSync(targetPath) && !options.force) {
54611
52716
  throw new Error(`models.json already exists: ${targetPath}. Use --force to overwrite, or --stdout to print the template.`);
54612
52717
  }
54613
- fs6.mkdirSync(path6.dirname(targetPath), { recursive: true });
54614
- fs6.writeFileSync(targetPath, content, "utf8");
52718
+ fs4.mkdirSync(path4.dirname(targetPath), { recursive: true });
52719
+ fs4.writeFileSync(targetPath, content, "utf8");
54615
52720
  return { path: targetPath, content, wrote: true };
54616
52721
  }
54617
52722
  function validateModelsConfig(options = {}) {
54618
52723
  const modelsPath = resolveModelsPath(options.path);
54619
- if (!fs6.existsSync(modelsPath)) {
52724
+ if (!fs4.existsSync(modelsPath)) {
54620
52725
  return {
54621
52726
  ok: false,
54622
52727
  path: modelsPath,
@@ -55411,6 +53516,456 @@ function runCapabilitiesCommand(args) {
55411
53516
  console.log(formatCapabilitiesHelp(report));
55412
53517
  }
55413
53518
 
53519
+ // src/commands/memory-cli.ts
53520
+ import * as fs5 from "node:fs";
53521
+ import * as path5 from "node:path";
53522
+ import { pathToFileURL } from "node:url";
53523
+ var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
53524
+ var MEMORY_MANAGER = "memory";
53525
+ function usage(code = 2) {
53526
+ console.log(`pie memory \u2014 session-derived memory management
53527
+
53528
+ Usage:
53529
+ pie memory distill [--date YYYY-MM-DD | --auto] [--memory-root <dir>] spawn detached worker
53530
+ pie memory distill --worker --date <d> | --auto --memory-root <dir> run in-process (worker mode)
53531
+ pie memory schedule on [--time HH:MM] | off | status daily managed cron job
53532
+ pie memory status [--memory-root <dir>] per-date checkpoints + failures
53533
+ pie memory log [--memory-root <dir>] [-n <lines>] tail the worker log
53534
+
53535
+ The default date is yesterday (local). --auto covers the last 7 days.`);
53536
+ process.exit(code);
53537
+ }
53538
+ function isFlagToken(value) {
53539
+ return value.startsWith("-");
53540
+ }
53541
+ function parseFlag(args, name) {
53542
+ const prefix = `${name}=`;
53543
+ for (const arg of args) {
53544
+ if (arg.startsWith(prefix)) {
53545
+ const value = arg.slice(prefix.length);
53546
+ if (value.length === 0) return { error: `${name}= requires a value` };
53547
+ return { value };
53548
+ }
53549
+ }
53550
+ const index = args.indexOf(name);
53551
+ if (index >= 0) {
53552
+ const value = args[index + 1];
53553
+ if (value === void 0) return { error: `${name} requires a value` };
53554
+ if (isFlagToken(value)) return { error: `${name} requires a value, got "${value}"` };
53555
+ return { value };
53556
+ }
53557
+ return {};
53558
+ }
53559
+ function parseDateFlag(args) {
53560
+ const parsed = parseFlag(args, "--date");
53561
+ if (parsed.error) return parsed;
53562
+ if (parsed.value === void 0) return {};
53563
+ if (!DATE_RE.test(parsed.value)) {
53564
+ return { error: `--date must be YYYY-MM-DD, got "${parsed.value}"` };
53565
+ }
53566
+ const probe = /* @__PURE__ */ new Date(`${parsed.value}T00:00:00`);
53567
+ if (Number.isNaN(probe.getTime())) return { error: `--date is not a real calendar date: "${parsed.value}"` };
53568
+ const pad = (n) => String(n).padStart(2, "0");
53569
+ const roundTrip = `${probe.getFullYear()}-${pad(probe.getMonth() + 1)}-${pad(probe.getDate())}`;
53570
+ if (roundTrip !== parsed.value) return { error: `--date is not a real calendar date: "${parsed.value}" (resolves to ${roundTrip})` };
53571
+ return { value: parsed.value };
53572
+ }
53573
+ function parseMemoryRootFlag(args) {
53574
+ const parsed = parseFlag(args, "--memory-root");
53575
+ if (parsed.error) return parsed;
53576
+ if (parsed.value !== void 0 && parsed.value.length === 0) return { error: "--memory-root requires a value" };
53577
+ return parsed;
53578
+ }
53579
+ function parseLogLimit(args) {
53580
+ for (const name of ["-n", "--lines"]) {
53581
+ const parsed = parseFlag(args, name);
53582
+ if (parsed.error) return { value: 20, error: parsed.error };
53583
+ if (parsed.value === void 0) continue;
53584
+ if (!/^\d+$/.test(parsed.value)) return { value: 20, error: `${name} must be a positive integer, got "${parsed.value}"` };
53585
+ return { value: Math.max(1, Number.parseInt(parsed.value, 10)) };
53586
+ }
53587
+ return { value: 20 };
53588
+ }
53589
+ function die(message) {
53590
+ console.error(`pie memory: ${message}`);
53591
+ process.exit(2);
53592
+ }
53593
+ async function runMemoryCommand(args) {
53594
+ const [sub, ...rest] = args;
53595
+ if (sub === void 0 || sub === "help" || sub === "--help" || sub === "-h") usage(sub === void 0 ? 2 : 0);
53596
+ const rootFlag = parseMemoryRootFlag(args);
53597
+ if (rootFlag.error) die(rootFlag.error);
53598
+ const root = rootFlag.value ?? path5.join(getConfigDir(), "memory");
53599
+ if (sub === "schedule") {
53600
+ if (rootFlag.value !== void 0) die("--memory-root is not supported for 'schedule' (the managed job always distills the default memory root)");
53601
+ return runScheduleCommand(rest);
53602
+ }
53603
+ if (sub === "distill") {
53604
+ const auto = rest.includes("--auto");
53605
+ const dateFlag = parseDateFlag(rest);
53606
+ if (dateFlag.error) die(dateFlag.error);
53607
+ if (auto && dateFlag.value !== void 0) die("--auto and --date are mutually exclusive");
53608
+ if (rest.includes("--worker")) {
53609
+ const workerRootFlag = parseMemoryRootFlag(rest);
53610
+ if (workerRootFlag.error) die(workerRootFlag.error);
53611
+ const workerRoot = workerRootFlag.value;
53612
+ if (!workerRoot) die("--worker requires --memory-root");
53613
+ if (auto) {
53614
+ const summary = await runDistillAuto(workerRoot);
53615
+ console.log(summary.lines.join("\n"));
53616
+ process.exitCode = summary.ok ? 0 : 1;
53617
+ return;
53618
+ }
53619
+ const date2 = dateFlag.value ?? yesterdayKey();
53620
+ const result = await runDistillWorkerMain(workerRoot, date2);
53621
+ if (result.busy) {
53622
+ console.log(`memory distill ${date2}: busy \u2014 another distillation worker holds the lock; nothing recorded, retry later`);
53623
+ return;
53624
+ }
53625
+ if (!result.ok) {
53626
+ console.error(`memory distill ${date2}: ${result.status ?? "failed"}${result.error ? `: ${result.error}` : ""}`);
53627
+ process.exit(1);
53628
+ }
53629
+ console.log(`memory distill ${date2}: ${result.status}`);
53630
+ return;
53631
+ }
53632
+ if (auto) {
53633
+ const spawned2 = spawnDistillAutoWorker(root);
53634
+ console.log(spawned2 ? `memory distill --auto: detached worker started (log: ${distillWorkerLogPath(root)})` : `memory distill --auto: could not spawn worker (log: ${distillWorkerLogPath(root)})`);
53635
+ process.exitCode = spawned2 ? 0 : 1;
53636
+ return;
53637
+ }
53638
+ const date = dateFlag.value ?? yesterdayKey();
53639
+ const store = new MemoryStore(root);
53640
+ if (store.hasRun(date)) {
53641
+ console.log(`memory distill ${date}: already distilled (checkpoint present)`);
53642
+ return;
53643
+ }
53644
+ const spawned = spawnDistillWorker(root, date);
53645
+ console.log(spawned ? `memory distill ${date}: detached worker started (log: ${distillWorkerLogPath(root)})` : `memory distill ${date}: could not spawn worker (log: ${distillWorkerLogPath(root)})`);
53646
+ process.exitCode = spawned ? 0 : 1;
53647
+ return;
53648
+ }
53649
+ if (sub === "status") {
53650
+ const store = new MemoryStore(root);
53651
+ const runs = Object.entries(store.loadState().runs).sort(([a], [b2]) => a < b2 ? 1 : -1);
53652
+ const schedule = describeMemorySchedule();
53653
+ if (schedule) console.log(`schedule: ${schedule}`);
53654
+ for (const line of consumptionSummary(store.loadEntries())) console.log(line);
53655
+ if (runs.length === 0) {
53656
+ console.log("No distillation runs recorded yet.");
53657
+ return;
53658
+ }
53659
+ for (const [date, run] of runs) {
53660
+ const failures = run.failures;
53661
+ const failureNote = failures && failures > 0 ? ` \xB7 failed ${failures}\xD7${run.lastError ? `: ${run.lastError}` : ""}` : "";
53662
+ console.log(`${date}: ${run.ops} ops at ${new Date(run.ranAt).toISOString()}${run.gated ? " (gated)" : ""}${failureNote}`);
53663
+ }
53664
+ return;
53665
+ }
53666
+ if (sub === "log") {
53667
+ const limit = parseLogLimit(rest);
53668
+ if (limit.error) die(limit.error);
53669
+ const lines = readDistillWorkerLog(root, limit.value);
53670
+ console.log(lines.length === 0 ? `No worker log yet (${distillWorkerLogPath(root)}).` : lines.join("\n"));
53671
+ return;
53672
+ }
53673
+ usage(2);
53674
+ }
53675
+ async function cronStore() {
53676
+ const entryUrl = pathToFileURL(path5.join(getBuiltinDir(), "extensions", "cron", "index.js")).href;
53677
+ const { Store, configPath } = await import(entryUrl);
53678
+ return { Store, configPath };
53679
+ }
53680
+ function managedMemoryCommand() {
53681
+ const entry = process.argv[1] ? path5.resolve(process.argv[1]) : null;
53682
+ if (!entry) throw new Error("cannot determine the CLI entrypoint for the managed schedule");
53683
+ return [process.execPath, entry, "memory", "distill", "--worker", "--auto", "--memory-root", path5.join(getConfigDir(), "memory")];
53684
+ }
53685
+ function timeToCron(value) {
53686
+ const match = value.match(/^(\d{1,2}):(\d{2})$/);
53687
+ if (!match) return { error: `--time must be HH:MM (local), got "${value}"` };
53688
+ const probe = /* @__PURE__ */ new Date();
53689
+ probe.setHours(Number(match[1]), Number(match[2]), 0, 0);
53690
+ if (Number(match[1]) > 23 || Number(match[2]) > 59) return { error: `--time out of range: "${value}"` };
53691
+ return { cron: `${probe.getUTCMinutes()} ${probe.getUTCHours()} * * *` };
53692
+ }
53693
+ function describeMemorySchedule() {
53694
+ try {
53695
+ const statePath = path5.join(getConfigDir(), "cron", "state.json");
53696
+ const raw = JSON.parse(fs5.readFileSync(statePath, "utf8"));
53697
+ const mine = (raw.jobs ?? []).find((job) => job.sessionId === "process" && (() => {
53698
+ try {
53699
+ return JSON.parse(job.prompt).managedBy === MEMORY_MANAGER;
53700
+ } catch {
53701
+ return false;
53702
+ }
53703
+ })());
53704
+ if (!mine) return void 0;
53705
+ const qualifier = !mine.enabled ? " (paused)" : mine.state === "blocked" ? ` (blocked: ${(mine.error ?? "").slice(0, 60)})` : "";
53706
+ return `on${qualifier} (job ${mine.id.slice(0, 8)}, next ${mine.next !== null ? new Date(mine.next).toISOString() : "none"})`;
53707
+ } catch {
53708
+ return void 0;
53709
+ }
53710
+ }
53711
+ async function runScheduleCommand(rest) {
53712
+ const [action, ...flags] = rest;
53713
+ const { Store, configPath } = await cronStore();
53714
+ const store = new Store(path5.join(configPath(), "cron"));
53715
+ if (action === "on") {
53716
+ const timeFlag = parseFlag(flags, "--time");
53717
+ if (timeFlag.error) die(timeFlag.error);
53718
+ const time = timeFlag.value ?? "09:00";
53719
+ const cron = timeToCron(time);
53720
+ if ("error" in cron) die(cron.error);
53721
+ const command = managedMemoryCommand();
53722
+ let job;
53723
+ try {
53724
+ job = store.addProcess(command, MEMORY_MANAGER, process.cwd(), cron);
53725
+ } catch (error) {
53726
+ die(String(error instanceof Error ? error.message : error));
53727
+ }
53728
+ console.log(`memory schedule on: daily at ${time} local (${cron.cron} UTC; fixed-UTC \u2014 DST shifts the local time). Runs: ${command.join(" ")}`);
53729
+ console.log("The cron extension triggers it whenever at least one cron-enabled Pie is open; missed days are caught up by --auto.");
53730
+ return;
53731
+ }
53732
+ if (action === "off") {
53733
+ const existing = store.findProcess(MEMORY_MANAGER);
53734
+ if (!existing) {
53735
+ console.log("memory schedule off: no managed job found (already off).");
53736
+ return;
53737
+ }
53738
+ if (existing.state === "running") die("the managed job is currently running; try again after it finishes");
53739
+ store.change(existing.id, "remove");
53740
+ console.log("memory schedule off: managed job removed.");
53741
+ return;
53742
+ }
53743
+ if (action === "status" || action === void 0) {
53744
+ const existing = store.findProcess(MEMORY_MANAGER);
53745
+ if (!existing) {
53746
+ console.log("memory schedule: off (no managed job; enable with `pie memory schedule on`)");
53747
+ return;
53748
+ }
53749
+ const command = (() => {
53750
+ try {
53751
+ return JSON.parse(existing.prompt).command;
53752
+ } catch {
53753
+ return void 0;
53754
+ }
53755
+ })();
53756
+ console.log(`memory schedule: on`);
53757
+ console.log(` job: ${existing.id} (state ${existing.state}, ${existing.enabled ? "enabled" : "paused"})`);
53758
+ console.log(` next: ${existing.next !== null ? new Date(existing.next).toISOString() : "none"}`);
53759
+ if (existing.error) console.log(` last error: ${existing.error}`);
53760
+ if (command) console.log(` command: ${command.join(" ")}`);
53761
+ return;
53762
+ }
53763
+ usage(2);
53764
+ }
53765
+ function yesterdayKey() {
53766
+ const probe = /* @__PURE__ */ new Date();
53767
+ probe.setDate(probe.getDate() - 1);
53768
+ return todayKey(probe.getTime());
53769
+ }
53770
+
53771
+ // src/commands/session-resume-restart.ts
53772
+ import { spawn } from "node:child_process";
53773
+ import * as fs6 from "node:fs";
53774
+ import * as path6 from "node:path";
53775
+
53776
+ // src/commands/session-resume-cwd.ts
53777
+ import { createRequire as createRequire2 } from "node:module";
53778
+ var RESUME_CWD_SENTINEL_ENV = "PIE_RESUME_CWD";
53779
+ function buildChildArgv(argv, sessionId) {
53780
+ const out = [];
53781
+ let i = 0;
53782
+ let sawSessionId = false;
53783
+ while (i < argv.length) {
53784
+ const arg = argv[i];
53785
+ if (arg === "--session-id") {
53786
+ out.push(arg, sessionId);
53787
+ i += 2;
53788
+ sawSessionId = true;
53789
+ continue;
53790
+ }
53791
+ if (arg.startsWith("--session-id=")) {
53792
+ out.push(`--session-id=${sessionId}`);
53793
+ i += 1;
53794
+ sawSessionId = true;
53795
+ continue;
53796
+ }
53797
+ if (arg === "--no-cd") {
53798
+ i += 1;
53799
+ continue;
53800
+ }
53801
+ out.push(arg);
53802
+ i += 1;
53803
+ }
53804
+ if (!sawSessionId) out.push("--session-id", sessionId);
53805
+ return out;
53806
+ }
53807
+ var requireFs = createRequire2(import.meta.url);
53808
+ function defaultRealpath(p) {
53809
+ try {
53810
+ return requireFs("node:fs").realpathSync(p);
53811
+ } catch {
53812
+ return p;
53813
+ }
53814
+ }
53815
+ function resolveResumeRestart(inputs) {
53816
+ const env = inputs.env ?? {};
53817
+ const sentinel = env[RESUME_CWD_SENTINEL_ENV];
53818
+ if (sentinel !== void 0 && typeof sentinel === "string" && sentinel.length > 0) {
53819
+ const resolve0 = inputs.realpath ?? defaultRealpath;
53820
+ const resolveSafe = (p) => {
53821
+ try {
53822
+ return resolve0(p);
53823
+ } catch {
53824
+ return p;
53825
+ }
53826
+ };
53827
+ const stillInSentinelDir = resolveSafe(sentinel) === resolveSafe(inputs.cwd);
53828
+ if (stillInSentinelDir) {
53829
+ const metaEarly = inputs.getMetadata(inputs.sessionId);
53830
+ const targetEarly = typeof metaEarly?.cwd === "string" ? metaEarly.cwd : void 0;
53831
+ if (targetEarly !== void 0 && resolveSafe(targetEarly) === resolveSafe(sentinel)) {
53832
+ return { action: "none", reason: "sentinel" };
53833
+ }
53834
+ }
53835
+ }
53836
+ if (inputs.chdirEnabled === false) {
53837
+ return { action: "none", reason: "disabled" };
53838
+ }
53839
+ if (inputs.argv.includes("--no-cd")) {
53840
+ return { action: "none", reason: "disabled" };
53841
+ }
53842
+ const metadata = inputs.getMetadata(inputs.sessionId);
53843
+ if (!metadata) {
53844
+ return { action: "none", reason: "metadata-unreadable" };
53845
+ }
53846
+ const recorded = metadata.cwd;
53847
+ if (typeof recorded !== "string" || recorded.length === 0) {
53848
+ return { action: "none", reason: "no-cwd-in-metadata" };
53849
+ }
53850
+ const resolve8 = (p) => {
53851
+ const realpath = inputs.realpath ?? defaultRealpath;
53852
+ try {
53853
+ return realpath(p);
53854
+ } catch {
53855
+ return p;
53856
+ }
53857
+ };
53858
+ const here = resolve8(inputs.cwd);
53859
+ const target = resolve8(recorded);
53860
+ if (here === target) {
53861
+ return { action: "none", reason: "same-dir" };
53862
+ }
53863
+ const dirExists = inputs.dirExists ?? ((p) => {
53864
+ try {
53865
+ return requireFs("node:fs").statSync(p).isDirectory();
53866
+ } catch {
53867
+ return false;
53868
+ }
53869
+ });
53870
+ if (!dirExists(target)) {
53871
+ return {
53872
+ action: "none",
53873
+ reason: "missing-dir",
53874
+ warning: `session was recorded in ${recorded}, which does not exist; continuing in ${inputs.cwd}`
53875
+ };
53876
+ }
53877
+ const childArgv = buildChildArgv(inputs.argv, inputs.sessionId);
53878
+ const childEnv = { ...env, [RESUME_CWD_SENTINEL_ENV]: target };
53879
+ return {
53880
+ action: "restart",
53881
+ targetCwd: target,
53882
+ childArgv,
53883
+ childEnv,
53884
+ banner: `resumed session ${inputs.sessionId.slice(0, 8)}; cwd ${inputs.cwd} \u2192 ${target}`
53885
+ };
53886
+ }
53887
+
53888
+ // src/commands/session-resume-restart.ts
53889
+ function readResumeChdirSetting() {
53890
+ try {
53891
+ const parsed = JSON.parse(fs6.readFileSync(getSettingsPath(), "utf8"));
53892
+ if (!parsed || typeof parsed !== "object") return true;
53893
+ const session = parsed.session;
53894
+ if (!session || typeof session !== "object" || Array.isArray(session)) return true;
53895
+ if (!Object.hasOwn(session, "resume")) return true;
53896
+ const resume = session.resume;
53897
+ if (!resume || typeof resume !== "object" || Array.isArray(resume)) return true;
53898
+ if (!Object.hasOwn(resume, "chdir")) return true;
53899
+ const value = resume.chdir;
53900
+ return typeof value === "boolean" ? value : true;
53901
+ } catch {
53902
+ return true;
53903
+ }
53904
+ }
53905
+ var DROPPED_ENV_KEYS = /* @__PURE__ */ new Set();
53906
+ function anchorAgentDirForChild(env) {
53907
+ const value = env["PIE_CODING_AGENT_DIR"];
53908
+ if (value === void 0 || value === "" || value === "~" || value.startsWith("~/") || path6.isAbsolute(value)) {
53909
+ return env;
53910
+ }
53911
+ return { ...env, PIE_CODING_AGENT_DIR: path6.resolve(process.cwd(), value) };
53912
+ }
53913
+ function buildChildEnv(env) {
53914
+ const anchored = anchorAgentDirForChild(env);
53915
+ const out = {};
53916
+ for (const [key, value] of Object.entries(anchored)) {
53917
+ if (DROPPED_ENV_KEYS.has(key)) continue;
53918
+ out[key] = value;
53919
+ }
53920
+ return out;
53921
+ }
53922
+ function decideSessionResumeRestart(argv, sessionId, cwd) {
53923
+ const sessionManager = createSessionManager({ sessionsDir: getSessionsDir() });
53924
+ const decision = resolveResumeRestart({
53925
+ argv,
53926
+ cwd,
53927
+ sessionId,
53928
+ getMetadata: (id) => sessionManager.getMetadata(id),
53929
+ chdirEnabled: readResumeChdirSetting(),
53930
+ env: process.env
53931
+ });
53932
+ return decision.action === "none" && !decision.warning ? null : decision;
53933
+ }
53934
+ function emitOsc7Cwd(cwd) {
53935
+ const slashed = cwd.replace(/\\/g, "/");
53936
+ const prefix = slashed.startsWith("/") ? "" : "/";
53937
+ const encoded = `file://${prefix}${encodeURI(slashed).replace(/#/g, "%23").replace(/\?/g, "%3F")}`;
53938
+ process.stderr.write(`\x1B]7;${encoded}\x07`);
53939
+ }
53940
+ async function performResumeRestart(decision, onSpawnFailure) {
53941
+ let announced = false;
53942
+ const announce = () => {
53943
+ if (announced) return;
53944
+ announced = true;
53945
+ console.error(decision.banner);
53946
+ emitOsc7Cwd(decision.targetCwd);
53947
+ };
53948
+ return await new Promise((resolve8) => {
53949
+ const child = spawn(process.execPath, [...process.execArgv, process.argv[1] ?? ".", ...decision.childArgv], {
53950
+ cwd: decision.targetCwd,
53951
+ stdio: "inherit",
53952
+ env: buildChildEnv(decision.childEnv)
53953
+ });
53954
+ child.on("spawn", () => announce());
53955
+ child.on("error", (error) => {
53956
+ onSpawnFailure(`could not restart in ${decision.targetCwd} (${error.message}); continuing in ${process.cwd()}`);
53957
+ resolve8(null);
53958
+ });
53959
+ child.on("exit", (code, signal) => {
53960
+ if (signal) {
53961
+ process.kill(process.pid, signal);
53962
+ return;
53963
+ }
53964
+ resolve8(code ?? 0);
53965
+ });
53966
+ });
53967
+ }
53968
+
55414
53969
  // src/commands/sessions.ts
55415
53970
  import fs8 from "node:fs";
55416
53971
 
@@ -56303,7 +54858,7 @@ function isRecord2(value) {
56303
54858
  import * as fs9 from "node:fs";
56304
54859
  import * as os2 from "os";
56305
54860
  import * as path8 from "path";
56306
- import { pathToFileURL } from "node:url";
54861
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
56307
54862
 
56308
54863
  // src/command-tree.ts
56309
54864
  var CommandTree = class {
@@ -56681,7 +55236,7 @@ function normalizeExtensionImportPath(extensionPath) {
56681
55236
  return `file:///${extensionPath.replace(/\\/g, "/")}`;
56682
55237
  }
56683
55238
  if (path8.isAbsolute(extensionPath)) {
56684
- return pathToFileURL(extensionPath).href;
55239
+ return pathToFileURL2(extensionPath).href;
56685
55240
  }
56686
55241
  return extensionPath;
56687
55242
  }
@@ -56737,6 +55292,7 @@ function discoverExtensionsInDir(dir, source) {
56737
55292
  let packageIdentity;
56738
55293
  let packageDescription;
56739
55294
  let packageMainPath;
55295
+ let packageDefaultEnablement;
56740
55296
  if (fs9.existsSync(packageJsonPath)) {
56741
55297
  try {
56742
55298
  const pkg = JSON.parse(fs9.readFileSync(packageJsonPath, "utf-8"));
@@ -56747,6 +55303,7 @@ function discoverExtensionsInDir(dir, source) {
56747
55303
  fallbackName: entry.name
56748
55304
  });
56749
55305
  packageDescription = typeof pkg.description === "string" ? pkg.description : void 0;
55306
+ if (manifest?.defaultEnablement === false) packageDefaultEnablement = false;
56750
55307
  if (typeof manifest?.main === "string" && manifest.main.trim().length > 0) {
56751
55308
  const candidate = path8.resolve(entryPath, manifest.main);
56752
55309
  if (fs9.existsSync(candidate)) {
@@ -56761,7 +55318,8 @@ function discoverExtensionsInDir(dir, source) {
56761
55318
  entryPath: packageMainPath,
56762
55319
  source,
56763
55320
  identity: packageIdentity,
56764
- description: packageDescription
55321
+ description: packageDescription,
55322
+ defaultEnablement: packageDefaultEnablement
56765
55323
  });
56766
55324
  continue;
56767
55325
  }
@@ -56771,7 +55329,8 @@ function discoverExtensionsInDir(dir, source) {
56771
55329
  entryPath: indexCjs,
56772
55330
  source,
56773
55331
  identity: packageIdentity ?? resolveExtensionIdentity({ fallbackName: entry.name }),
56774
- description: packageDescription
55332
+ description: packageDescription,
55333
+ defaultEnablement: packageDefaultEnablement
56775
55334
  });
56776
55335
  continue;
56777
55336
  }
@@ -56781,7 +55340,8 @@ function discoverExtensionsInDir(dir, source) {
56781
55340
  entryPath: indexJs,
56782
55341
  source,
56783
55342
  identity: packageIdentity ?? resolveExtensionIdentity({ fallbackName: entry.name }),
56784
- description: packageDescription
55343
+ description: packageDescription,
55344
+ defaultEnablement: packageDefaultEnablement
56785
55345
  });
56786
55346
  continue;
56787
55347
  }
@@ -56791,7 +55351,8 @@ function discoverExtensionsInDir(dir, source) {
56791
55351
  entryPath: indexTs,
56792
55352
  source,
56793
55353
  identity: packageIdentity ?? resolveExtensionIdentity({ fallbackName: entry.name }),
56794
- description: packageDescription
55354
+ description: packageDescription,
55355
+ defaultEnablement: packageDefaultEnablement
56795
55356
  });
56796
55357
  continue;
56797
55358
  }
@@ -56831,13 +55392,22 @@ function collectDiscoveredExtensions(configuredPaths, cwd, options) {
56831
55392
  }
56832
55393
  function discoverAllExtensions(configuredPaths, cwd, options) {
56833
55394
  const { discovered } = collectDiscoveredExtensions(configuredPaths, cwd, options);
56834
- const layers = options?.enablementLayers;
56835
- return discovered.map((item) => ({
55395
+ const layers = options?.enablementLayers ?? [];
55396
+ const seen = /* @__PURE__ */ new Set();
55397
+ const winners = [];
55398
+ for (const item of discovered) {
55399
+ if (item.identity) {
55400
+ if (seen.has(item.identity)) continue;
55401
+ seen.add(item.identity);
55402
+ }
55403
+ winners.push(item);
55404
+ }
55405
+ return winners.map((item) => ({
56836
55406
  entryPath: item.entryPath,
56837
55407
  source: item.source,
56838
55408
  identity: item.identity,
56839
55409
  description: item.description,
56840
- enabled: layers ? item.identity ? isExtensionEnabled(item.identity, ...layers) : true : true
55410
+ enabled: item.identity ? isExtensionEnabled(item.identity, ...layers, manifestDefaultLayer(item.defaultEnablement)) : true
56841
55411
  }));
56842
55412
  }
56843
55413
  async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn, hasUI = true, actions, options) {
@@ -56873,14 +55443,22 @@ async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn
56873
55443
  options
56874
55444
  );
56875
55445
  errors.push(...discoveryErrors);
56876
- const layers = options?.enablementLayers;
55446
+ const layers = options?.enablementLayers ?? [];
56877
55447
  for (const discovered of allDiscovered) {
56878
- if (layers && discovered.identity && !isExtensionEnabled(discovered.identity, ...layers)) {
56879
- continue;
56880
- }
56881
55448
  addDiscovered(discovered);
56882
55449
  }
56883
- for (const extPath of allPaths) {
55450
+ const enabledPaths = /* @__PURE__ */ new Set();
55451
+ for (const [identity, entryPath] of pathByIdentity) {
55452
+ if (isExtensionEnabled(identity, ...layers, manifestDefaultLayer(discoveredByPath.get(entryPath)?.defaultEnablement))) {
55453
+ enabledPaths.add(entryPath);
55454
+ }
55455
+ }
55456
+ const pathsToLoad = allPaths.filter((p) => {
55457
+ const discovered = discoveredByPath.get(p);
55458
+ if (!discovered?.identity) return true;
55459
+ return enabledPaths.has(pathByIdentity.get(discovered.identity));
55460
+ });
55461
+ for (const extPath of pathsToLoad) {
56884
55462
  const { extension, error } = await loadExtension(
56885
55463
  extPath,
56886
55464
  cwd,
@@ -64145,7 +62723,7 @@ import * as fs11 from "node:fs";
64145
62723
  import koffi from "koffi";
64146
62724
 
64147
62725
  // ../../packages/tui/src/osc-5522.ts
64148
- import { randomBytes as randomBytes2 } from "node:crypto";
62726
+ import { randomBytes } from "node:crypto";
64149
62727
  var OSC = "\x1B]";
64150
62728
  var ST = "\x1B\\";
64151
62729
  var READ_TIMEOUT_MS = 8e3;
@@ -64267,14 +62845,14 @@ var Osc5522Client = class {
64267
62845
  */
64268
62846
  async querySupport(timeoutMs = SUPPORT_TIMEOUT_MS) {
64269
62847
  if (this.supportMode !== "unknown") return this.supportMode === "supported";
64270
- return new Promise((resolve7) => {
62848
+ return new Promise((resolve8) => {
64271
62849
  let settled = false;
64272
62850
  const settle = (supported) => {
64273
62851
  if (settled) return;
64274
62852
  settled = true;
64275
62853
  clearTimeout(timer);
64276
62854
  this.pendingSupportResolve = void 0;
64277
- resolve7(supported);
62855
+ resolve8(supported);
64278
62856
  };
64279
62857
  const timer = setTimeout(() => settle(false), timeoutMs);
64280
62858
  this.pendingSupportResolve = settle;
@@ -64292,14 +62870,14 @@ var Osc5522Client = class {
64292
62870
  return { ok: false, kind: "busy", message: "Another OSC 5522 read is already in flight." };
64293
62871
  }
64294
62872
  const session = {
64295
- id: `pie-${randomBytes2(8).toString("hex")}`,
62873
+ id: `pie-${randomBytes(8).toString("hex")}`,
64296
62874
  resolve: void 0,
64297
62875
  timer: void 0,
64298
62876
  chunks: [],
64299
62877
  totalBytes: 0
64300
62878
  };
64301
- const promise = new Promise((resolve7) => {
64302
- session.resolve = resolve7;
62879
+ const promise = new Promise((resolve8) => {
62880
+ session.resolve = resolve8;
64303
62881
  });
64304
62882
  session.timer = setTimeout(() => {
64305
62883
  this.finishFor(session, { ok: false, kind: "timeout", message: "Terminal did not respond to the clipboard read in time." });
@@ -64462,7 +63040,7 @@ var ProcessTerminal = class {
64462
63040
  const timeLeft = endTime - now;
64463
63041
  if (timeLeft <= 0) break;
64464
63042
  if (now - lastDataTime >= idleMs) break;
64465
- await new Promise((resolve7) => setTimeout(resolve7, Math.min(idleMs, timeLeft)));
63043
+ await new Promise((resolve8) => setTimeout(resolve8, Math.min(idleMs, timeLeft)));
64466
63044
  }
64467
63045
  } finally {
64468
63046
  process.stdin.removeListener("data", onData);
@@ -65393,8 +63971,8 @@ function restoreInteractiveSessionState(options) {
65393
63971
  }
65394
63972
 
65395
63973
  // src/keybindings.ts
65396
- import { existsSync as existsSync8, readFileSync as readFileSync7 } from "fs";
65397
- import { join as join8 } from "path";
63974
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
63975
+ import { join as join7 } from "path";
65398
63976
  var DEFAULT_APP_KEYBINDINGS = {
65399
63977
  interrupt: "escape",
65400
63978
  clear: "ctrl+c",
@@ -65409,7 +63987,7 @@ var DEFAULT_APP_KEYBINDINGS = {
65409
63987
  toggleYolo: ["ctrl+x", "alt+o"],
65410
63988
  toggleSessionNamedFilter: "ctrl+n",
65411
63989
  externalEditor: "ctrl+g",
65412
- steer: "alt+enter",
63990
+ steer: ["alt+enter", "ctrl+\\"],
65413
63991
  followUp: [],
65414
63992
  dequeue: ["alt+up", "ctrl+shift+up"],
65415
63993
  pasteImage: ["ctrl+v", "alt+v", "super+v"],
@@ -65460,7 +64038,7 @@ var KeybindingsManager = class _KeybindingsManager {
65460
64038
  * Create from config file and set up editor keybindings.
65461
64039
  */
65462
64040
  static create(agentDir = getAgentDir()) {
65463
- const configPath = join8(agentDir, "keybindings.json");
64041
+ const configPath = join7(agentDir, "keybindings.json");
65464
64042
  const config = _KeybindingsManager.loadFromFile(configPath);
65465
64043
  const manager = new _KeybindingsManager(config);
65466
64044
  const editorConfig = {};
@@ -65479,7 +64057,7 @@ var KeybindingsManager = class _KeybindingsManager {
65479
64057
  return new _KeybindingsManager(config);
65480
64058
  }
65481
64059
  static loadFromFile(path34) {
65482
- if (!existsSync8(path34)) return {};
64060
+ if (!existsSync6(path34)) return {};
65483
64061
  try {
65484
64062
  return JSON.parse(readFileSync7(path34, "utf-8"));
65485
64063
  } catch {
@@ -66887,8 +65465,8 @@ function parseSkillDescription(content) {
66887
65465
  }
66888
65466
  var USER_CONTROLLED_SOURCES = /* @__PURE__ */ new Set(["user-agents", "user"]);
66889
65467
  function pathIsInside(child, parent) {
66890
- const relative3 = path12.relative(parent, child);
66891
- return relative3 !== "" && !relative3.startsWith(`..${path12.sep}`) && relative3 !== ".." && !path12.isAbsolute(relative3);
65468
+ const relative2 = path12.relative(parent, child);
65469
+ return relative2 !== "" && !relative2.startsWith(`..${path12.sep}`) && relative2 !== ".." && !path12.isAbsolute(relative2);
66892
65470
  }
66893
65471
  function resolveSkillSymlink(fullPath, dir, source) {
66894
65472
  let target;
@@ -68264,11 +66842,11 @@ var FileCache = class _FileCache {
68264
66842
  // Hash Computation
68265
66843
  // ============================================================================
68266
66844
  async computeHash(filePath) {
68267
- return new Promise((resolve7, reject) => {
66845
+ return new Promise((resolve8, reject) => {
68268
66846
  const hash = crypto.createHash("sha256");
68269
66847
  const stream = fs18.createReadStream(filePath);
68270
66848
  stream.on("data", (chunk) => hash.update(chunk));
68271
- stream.on("end", () => resolve7(hash.digest("hex")));
66849
+ stream.on("end", () => resolve8(hash.digest("hex")));
68272
66850
  stream.on("error", reject);
68273
66851
  });
68274
66852
  }
@@ -68980,7 +67558,7 @@ var SessionFileManager = class {
68980
67558
  // src/files/ffmpeg-processor.ts
68981
67559
  import * as fs20 from "node:fs";
68982
67560
  import * as path19 from "node:path";
68983
- import { spawn } from "node:child_process";
67561
+ import { spawn as spawn2 } from "node:child_process";
68984
67562
  var FFmpegProcessor = class {
68985
67563
  ffmpegPath = "ffmpeg";
68986
67564
  ffprobePath = "ffprobe";
@@ -68992,17 +67570,17 @@ var FFmpegProcessor = class {
68992
67570
  // Detection
68993
67571
  // ============================================================================
68994
67572
  async checkAvailability() {
68995
- return new Promise((resolve7) => {
68996
- const proc = spawn(this.ffmpegPath, ["-version"]);
68997
- proc.on("error", () => resolve7(false));
68998
- proc.on("exit", (code) => resolve7(code === 0));
67573
+ return new Promise((resolve8) => {
67574
+ const proc = spawn2(this.ffmpegPath, ["-version"]);
67575
+ proc.on("error", () => resolve8(false));
67576
+ proc.on("exit", (code) => resolve8(code === 0));
68999
67577
  });
69000
67578
  }
69001
67579
  // ============================================================================
69002
67580
  // Video Analysis
69003
67581
  // ============================================================================
69004
67582
  async analyzeVideo(videoPath) {
69005
- return new Promise((resolve7, reject) => {
67583
+ return new Promise((resolve8, reject) => {
69006
67584
  const args = [
69007
67585
  "-v",
69008
67586
  "error",
@@ -69014,7 +67592,7 @@ var FFmpegProcessor = class {
69014
67592
  "json",
69015
67593
  videoPath
69016
67594
  ];
69017
- const proc = spawn(this.ffprobePath, args);
67595
+ const proc = spawn2(this.ffprobePath, args);
69018
67596
  let stdout = "";
69019
67597
  let stderr = "";
69020
67598
  proc.stdout.on("data", (data) => stdout += data);
@@ -69031,7 +67609,7 @@ var FFmpegProcessor = class {
69031
67609
  }
69032
67610
  try {
69033
67611
  const info = this.parseProbeOutput(stdout, videoPath);
69034
- resolve7(info);
67612
+ resolve8(info);
69035
67613
  } catch (err) {
69036
67614
  reject(err);
69037
67615
  }
@@ -69226,8 +67804,8 @@ var FFmpegProcessor = class {
69226
67804
  // FFmpeg Execution
69227
67805
  // ============================================================================
69228
67806
  runFFmpeg(args) {
69229
- return new Promise((resolve7, reject) => {
69230
- const proc = spawn(this.ffmpegPath, args);
67807
+ return new Promise((resolve8, reject) => {
67808
+ const proc = spawn2(this.ffmpegPath, args);
69231
67809
  let stderr = "";
69232
67810
  proc.stderr.on("data", (data) => {
69233
67811
  stderr += data;
@@ -69241,7 +67819,7 @@ var FFmpegProcessor = class {
69241
67819
  )
69242
67820
  );
69243
67821
  } else {
69244
- resolve7();
67822
+ resolve8();
69245
67823
  }
69246
67824
  });
69247
67825
  proc.on("error", (err) => {
@@ -69258,13 +67836,13 @@ var FFmpegProcessor = class {
69258
67836
  // Progress Monitoring (for future use)
69259
67837
  // ============================================================================
69260
67838
  async runWithProgress(args, onProgress) {
69261
- return new Promise((resolve7, reject) => {
67839
+ return new Promise((resolve8, reject) => {
69262
67840
  const progressArgs = [
69263
67841
  ...args,
69264
67842
  "-progress",
69265
67843
  "pipe:1"
69266
67844
  ];
69267
- const proc = spawn(this.ffmpegPath, progressArgs);
67845
+ const proc = spawn2(this.ffmpegPath, progressArgs);
69268
67846
  let stderr = "";
69269
67847
  let progressData = "";
69270
67848
  proc.stdout.on("data", (data) => {
@@ -69288,7 +67866,7 @@ var FFmpegProcessor = class {
69288
67866
  )
69289
67867
  );
69290
67868
  } else {
69291
- resolve7();
67869
+ resolve8();
69292
67870
  }
69293
67871
  });
69294
67872
  });
@@ -70283,7 +68861,7 @@ async function waitForReady(params) {
70283
68861
  if (status.status === "error" || status.status === "expired") {
70284
68862
  throw new Error(`Uploaded file is not ready: ${status.status}${status.error ? ` (${status.error})` : ""}`);
70285
68863
  }
70286
- await new Promise((resolve7) => setTimeout(resolve7, 1500));
68864
+ await new Promise((resolve8) => setTimeout(resolve8, 1500));
70287
68865
  }
70288
68866
  throw new Error("Timed out waiting for uploaded file to become ready");
70289
68867
  }
@@ -70380,8 +68958,8 @@ function createIsolatedRegexSession(pattern, ignoreCase) {
70380
68958
  let initError;
70381
68959
  let readyResolve;
70382
68960
  let readyReject;
70383
- const ready = new Promise((resolve7, reject) => {
70384
- readyResolve = resolve7;
68961
+ const ready = new Promise((resolve8, reject) => {
68962
+ readyResolve = resolve8;
70385
68963
  readyReject = reject;
70386
68964
  });
70387
68965
  void ready.catch(() => void 0);
@@ -70403,7 +68981,7 @@ function createIsolatedRegexSession(pattern, ignoreCase) {
70403
68981
  if (initError) throw initError;
70404
68982
  if (signal?.aborted) throw new Error("Operation aborted");
70405
68983
  const id = nextId++;
70406
- return new Promise((resolve7, reject) => {
68984
+ return new Promise((resolve8, reject) => {
70407
68985
  let settled = false;
70408
68986
  const finish = (error, matches) => {
70409
68987
  if (settled) return;
@@ -70413,7 +68991,7 @@ function createIsolatedRegexSession(pattern, ignoreCase) {
70413
68991
  worker.off("message", onMessage);
70414
68992
  worker.off("error", onWorkerError);
70415
68993
  if (error) reject(error);
70416
- else resolve7(matches ?? []);
68994
+ else resolve8(matches ?? []);
70417
68995
  };
70418
68996
  const terminate = (error) => {
70419
68997
  disposed = true;
@@ -70935,7 +69513,7 @@ var SessionTraceWriter = class extends SessionTraceSnapshotWriter {
70935
69513
  };
70936
69514
 
70937
69515
  // src/runtime/context-signals.ts
70938
- import { createHash as createHash4 } from "crypto";
69516
+ import { createHash as createHash3 } from "crypto";
70939
69517
  function applyContextSignalsToFooter(target) {
70940
69518
  if (!target.agent?.state) return;
70941
69519
  const state = target.agent.state;
@@ -70957,7 +69535,7 @@ function applyContextSignalsToFooter(target) {
70957
69535
  });
70958
69536
  }
70959
69537
  function computePromptPrefixHash(systemPrompt, tools, route) {
70960
- return createHash4("sha256").update(
69538
+ return createHash3("sha256").update(
70961
69539
  JSON.stringify({
70962
69540
  systemPrompt,
70963
69541
  tools: tools.map((tool) => ({
@@ -70973,20 +69551,20 @@ function calculateCumulativeCacheHitRate(messages, recentTurns) {
70973
69551
  const usages = [];
70974
69552
  for (const message of messages) {
70975
69553
  if (message.role !== "assistant") continue;
70976
- const usage = message.usage;
70977
- if (!usage) continue;
70978
- usages.push(usage);
69554
+ const usage2 = message.usage;
69555
+ if (!usage2) continue;
69556
+ usages.push(usage2);
70979
69557
  }
70980
69558
  const windowed = recentTurns !== void 0 && usages.length > recentTurns ? usages.slice(-recentTurns) : usages;
70981
69559
  let input = 0;
70982
69560
  let cacheRead = 0;
70983
69561
  let cacheWrite = 0;
70984
69562
  let cacheWriteLong = 0;
70985
- for (const usage of windowed) {
70986
- input += usage.input;
70987
- cacheRead += usage.cacheRead;
70988
- cacheWrite += usage.cacheWrite;
70989
- cacheWriteLong += usage.cacheWriteLong ?? 0;
69563
+ for (const usage2 of windowed) {
69564
+ input += usage2.input;
69565
+ cacheRead += usage2.cacheRead;
69566
+ cacheWrite += usage2.cacheWrite;
69567
+ cacheWriteLong += usage2.cacheWriteLong ?? 0;
70990
69568
  }
70991
69569
  const base = input + cacheRead + cacheWrite + cacheWriteLong;
70992
69570
  return base > 0 ? cacheRead / base : null;
@@ -71113,10 +69691,10 @@ function formatSessionCwdTag(sessionCwd, currentCwd, homeDir) {
71113
69691
  const normalizedSessionCwd = pathApi.normalize(sessionCwd);
71114
69692
  if (homeDir && getPathFlavor(homeDir, sessionCwd) === sessionFlavor) {
71115
69693
  const normalizedHome = pathApi.normalize(homeDir);
71116
- const relative3 = pathApi.relative(normalizedHome, normalizedSessionCwd);
71117
- const outsideHome = relative3 === ".." || relative3.startsWith(`..${pathApi.sep}`) || pathApi.isAbsolute(relative3);
69694
+ const relative2 = pathApi.relative(normalizedHome, normalizedSessionCwd);
69695
+ const outsideHome = relative2 === ".." || relative2.startsWith(`..${pathApi.sep}`) || pathApi.isAbsolute(relative2);
71118
69696
  if (!outsideHome) {
71119
- return relative3 ? `~${pathApi.sep}${relative3}` : "~";
69697
+ return relative2 ? `~${pathApi.sep}${relative2}` : "~";
71120
69698
  }
71121
69699
  }
71122
69700
  return normalizedSessionCwd;
@@ -73216,15 +71794,15 @@ function calculateSessionUsageTotals(messages) {
73216
71794
  let costEstimated = false;
73217
71795
  for (const message of messages) {
73218
71796
  if (message.role !== "assistant") continue;
73219
- const usage = message.usage;
73220
- if (!usage) continue;
73221
- input += usage.input;
73222
- output += usage.output;
73223
- cacheRead += usage.cacheRead;
73224
- cacheWrite += usage.cacheWrite;
73225
- cacheWriteLong += usage.cacheWriteLong ?? 0;
73226
- cost += usage.cost?.total ?? 0;
73227
- if (usage.cost?.cacheWriteLongEstimated === true) costEstimated = true;
71797
+ const usage2 = message.usage;
71798
+ if (!usage2) continue;
71799
+ input += usage2.input;
71800
+ output += usage2.output;
71801
+ cacheRead += usage2.cacheRead;
71802
+ cacheWrite += usage2.cacheWrite;
71803
+ cacheWriteLong += usage2.cacheWriteLong ?? 0;
71804
+ cost += usage2.cost?.total ?? 0;
71805
+ if (usage2.cost?.cacheWriteLongEstimated === true) costEstimated = true;
73228
71806
  }
73229
71807
  return { input, output, cacheRead, cacheWrite, cacheWriteLong, cacheWriteTotal: cacheWrite + cacheWriteLong, cost, costEstimated };
73230
71808
  }
@@ -73309,6 +71887,7 @@ function normalizeSessionTitle(raw) {
73309
71887
  }
73310
71888
 
73311
71889
  // src/commands/interactive-session-commands.ts
71890
+ import { spawn as spawn3 } from "node:child_process";
73312
71891
  function textFromContentBlock(block) {
73313
71892
  if (!block || typeof block !== "object" || !("text" in block)) return "";
73314
71893
  const text = block.text;
@@ -73326,6 +71905,54 @@ async function handleResumeCommand(host) {
73326
71905
  const selector = new SessionSelectorComponent(sessions, {
73327
71906
  onSelect: async (sessionId) => {
73328
71907
  done();
71908
+ const decision = decideSessionResumeRestart(process.argv.slice(2), sessionId, process.cwd());
71909
+ if (decision && decision.action !== "restart" && decision.warning) {
71910
+ host.showWarning(decision.warning);
71911
+ }
71912
+ if (decision && decision.action === "restart") {
71913
+ const beforeSwitch = await host.extensionRunner?.emitSessionBeforeSwitch({
71914
+ type: "session:before_switch",
71915
+ reason: "resume",
71916
+ targetSessionId: sessionId
71917
+ });
71918
+ if (beforeSwitch?.cancel) {
71919
+ host.showStatus("Session switch cancelled by an extension");
71920
+ return;
71921
+ }
71922
+ const scheduled = scheduleResumeRestartAfterExit(() => {
71923
+ let announced = false;
71924
+ const announce = () => {
71925
+ if (announced) return;
71926
+ announced = true;
71927
+ console.error(decision.banner);
71928
+ emitOsc7Cwd(decision.targetCwd);
71929
+ };
71930
+ const child = spawn3(process.execPath, [...process.execArgv, process.argv[1] ?? ".", ...decision.childArgv], {
71931
+ cwd: decision.targetCwd,
71932
+ stdio: "inherit",
71933
+ env: buildChildEnv(decision.childEnv)
71934
+ });
71935
+ child.on("spawn", () => announce());
71936
+ child.on("exit", (code, signal) => {
71937
+ if (signal) {
71938
+ process.kill(process.pid, signal);
71939
+ return;
71940
+ }
71941
+ process.exit(code ?? 0);
71942
+ });
71943
+ child.on("error", (error) => {
71944
+ console.error(`[resume] could not restart in ${decision.targetCwd} (${error.message}).`);
71945
+ console.error(`[resume] the session is intact \u2014 restart manually with: pie --session-id ${sessionId}`);
71946
+ process.exit(1);
71947
+ });
71948
+ });
71949
+ if (scheduled) {
71950
+ host.cleanupAndExit();
71951
+ return;
71952
+ }
71953
+ host.showStatus("Another session switch is already in progress");
71954
+ return;
71955
+ }
73329
71956
  await host.loadSession(sessionId);
73330
71957
  },
73331
71958
  onCancel: () => {
@@ -74282,10 +72909,10 @@ var shutdowns = /* @__PURE__ */ new WeakMap();
74282
72909
  function shutdownInteractiveHost(host, idleTimeoutMs = 5e3) {
74283
72910
  const existing = shutdowns.get(host);
74284
72911
  if (existing) return existing;
74285
- let resolve7;
72912
+ let resolve8;
74286
72913
  let reject;
74287
72914
  const shutdown = new Promise((done, fail) => {
74288
- resolve7 = done;
72915
+ resolve8 = done;
74289
72916
  reject = fail;
74290
72917
  });
74291
72918
  shutdowns.set(host, shutdown);
@@ -74333,7 +72960,7 @@ function shutdownInteractiveHost(host, idleTimeoutMs = 5e3) {
74333
72960
  errors.push(error);
74334
72961
  }
74335
72962
  if (errors.length) throw new AggregateError(errors, "Interactive shutdown failed.");
74336
- })().then(resolve7, reject);
72963
+ })().then(resolve8, reject);
74337
72964
  return shutdown;
74338
72965
  }
74339
72966
 
@@ -74974,7 +73601,7 @@ function assistantDisplayBlocks(content) {
74974
73601
  }
74975
73602
 
74976
73603
  // src/commands/interactive-debug-commands.ts
74977
- import { createHash as createHash5 } from "crypto";
73604
+ import { createHash as createHash4 } from "crypto";
74978
73605
  function errorMessage(error) {
74979
73606
  return error instanceof Error ? error.message : String(error);
74980
73607
  }
@@ -75012,7 +73639,7 @@ async function handleCacheTest(host) {
75012
73639
  timestamp: fixedTimestamp
75013
73640
  }
75014
73641
  ];
75015
- const prefixHash = createHash5("sha256").update(
73642
+ const prefixHash = createHash4("sha256").update(
75016
73643
  JSON.stringify({
75017
73644
  systemPrompt: stablePrefix,
75018
73645
  tools: toolDefs.map((tool) => ({
@@ -75034,7 +73661,7 @@ async function handleCacheTest(host) {
75034
73661
  sessionId: testSessionId,
75035
73662
  maxTokens: Math.min(model.maxTokens, 512)
75036
73663
  };
75037
- const summarizeUsage = (usage) => `Input: ${usage.input}, Output: ${usage.output}, Cache read: ${usage.cacheRead}, Cache write: ${usage.cacheWrite}`;
73664
+ const summarizeUsage = (usage2) => `Input: ${usage2.input}, Output: ${usage2.output}, Cache read: ${usage2.cacheRead}, Cache write: ${usage2.cacheWrite}`;
75038
73665
  const reasonIfNoHit = (() => {
75039
73666
  switch (cacheCapability.mode) {
75040
73667
  case "none":
@@ -75062,7 +73689,7 @@ async function handleCacheTest(host) {
75062
73689
  host.chatContainer.addChild(new Text(theme.fg("dim", ` ${summarizeUsage(result1.usage)}`), 1, 0));
75063
73690
  host.chatContainer.addChild(new Text(theme.fg("dim", " Waiting 2s before replaying identical request..."), 1, 0));
75064
73691
  host.ui.requestRender();
75065
- await new Promise((resolve7) => setTimeout(resolve7, 2e3));
73692
+ await new Promise((resolve8) => setTimeout(resolve8, 2e3));
75066
73693
  host.chatContainer.addChild(new Text(theme.fg("accent", "Request 2/2: replaying identical request..."), 1, 0));
75067
73694
  host.ui.requestRender();
75068
73695
  result2 = await completeSimple(model, context, options);
@@ -76185,10 +74812,10 @@ ${summary}`.slice(0, MAX_ENTRY_BODY_CHARS) || null;
76185
74812
  }
76186
74813
  if (message.role === "assistant") {
76187
74814
  const parts = ["# assistant message"];
76188
- const usage = message.usage;
76189
- if (usage) {
74815
+ const usage2 = message.usage;
74816
+ if (usage2) {
76190
74817
  parts.push(
76191
- `usage: input ${usage.input} \xB7 output ${usage.output} \xB7 cacheRead ${usage.cacheRead} \xB7 cacheWrite ${usage.cacheWrite}`
74818
+ `usage: input ${usage2.input} \xB7 output ${usage2.output} \xB7 cacheRead ${usage2.cacheRead} \xB7 cacheWrite ${usage2.cacheWrite}`
76192
74819
  );
76193
74820
  }
76194
74821
  if (Array.isArray(message.content)) {
@@ -76229,7 +74856,7 @@ function handleContextReportCommand(host) {
76229
74856
  const systemPrompt = host.agent.state.systemPrompt ?? "";
76230
74857
  const knowledgeFiles = parseProjectContextSection(host.knowledgeSection);
76231
74858
  const entries = host.sessionManager.getActiveContextSummaries();
76232
- const usage = host.calculateContextUsage();
74859
+ const usage2 = host.calculateContextUsage();
76233
74860
  const contextWindow = host.options.model?.contextWindow ?? 0;
76234
74861
  const reserveTokens = host.options.settingsManager.getAutoCompactReserveTokens();
76235
74862
  const autoCompactEnabled = host.options.settingsManager.getAutoCompactEnabled();
@@ -76269,10 +74896,10 @@ function handleContextReportCommand(host) {
76269
74896
  entries,
76270
74897
  compactionTokensBefore: (entryId) => host.sessionManager.getEntry(entryId)?.compactionData?.tokensBefore,
76271
74898
  contextWindow,
76272
- estimatedCurrentTokens: usage.estimatedCurrentTokens,
76273
- providerMeasuredTokens: usage.providerMeasuredTokens,
76274
- providerMeasuredAt: usage.providerMeasuredAt,
76275
- measurementMatchesCurrentContext: usage.measurementMatchesCurrentContext,
74899
+ estimatedCurrentTokens: usage2.estimatedCurrentTokens,
74900
+ providerMeasuredTokens: usage2.providerMeasuredTokens,
74901
+ providerMeasuredAt: usage2.providerMeasuredAt,
74902
+ measurementMatchesCurrentContext: usage2.measurementMatchesCurrentContext,
76276
74903
  autoCompactEnabled,
76277
74904
  autoCompactLimitTokens: autoCompactLimit,
76278
74905
  reserveTokens,
@@ -77161,6 +75788,12 @@ function handleCtrlC(host) {
77161
75788
  }
77162
75789
  }
77163
75790
  var exitingHosts = /* @__PURE__ */ new WeakSet();
75791
+ var pendingResumeRestart = null;
75792
+ function scheduleResumeRestartAfterExit(restart) {
75793
+ if (pendingResumeRestart) return false;
75794
+ pendingResumeRestart = restart;
75795
+ return true;
75796
+ }
77164
75797
  function cleanupAndExit(host) {
77165
75798
  if (exitingHosts.has(host)) return;
77166
75799
  exitingHosts.add(host);
@@ -77175,6 +75808,12 @@ function cleanupAndExit(host) {
77175
75808
  process.exitCode = 1;
77176
75809
  }
77177
75810
  console.log(`[Cleanup] Goodbye!${sessionId ? ` session: ${sessionId}` : ""}`);
75811
+ const restart = pendingResumeRestart;
75812
+ pendingResumeRestart = null;
75813
+ if (restart) {
75814
+ restart();
75815
+ return;
75816
+ }
77178
75817
  process.exit(process.exitCode || 0);
77179
75818
  })();
77180
75819
  }
@@ -77584,7 +76223,7 @@ function buildRuntimeModeContext(state) {
77584
76223
  ];
77585
76224
  if (state.planMode === "planning") {
77586
76225
  lines.push(
77587
- "- Plan mode: active (workspace read-only; plan_scratch permits session-local temporary drafts; submit the finished plan by calling plan_submit with the ordered steps for user approval)."
76226
+ "- Plan mode: active \u2014 DISCUSSION FIRST (workspace read-only; plan_scratch permits session-local temporary drafts). Grilling: interview the user in ROUNDS; each round asks every frontier question (whose prerequisites are settled), numbered (\u2753 Qn / \u27A1\uFE0F recommended answer); wait for answers before the next round; find facts yourself with read-only tools, never ask the user what you could look up; challenge wording that conflicts with settled terms. Do NOT output a plan or call plan_submit until the user explicitly asks for the plan (e.g. \u201C\u8F93\u51FA\u8BA1\u5212\u201D / \u201Cgive me the plan\u201D / /tools/plan/submit); when unsure whether they asked, ask back. When asked: decompose into MVP steps \u2014 each independently verifiable (verify criterion, ideally one command), scoped (files it touches, \u201C(new)\u201D for to-be-created), and stable (later steps build on earlier ones, no rework); one step at a time with [DONE:n]+[VERIFIED:n], failed verify stops the ladder (Retry/Revise/Abort, never Skip)."
77588
76227
  );
77589
76228
  if (state.planDisabledToolNames.length > 0) {
77590
76229
  lines.push(
@@ -77602,7 +76241,7 @@ function buildRuntimeModeContext(state) {
77602
76241
  const transitionText = {
77603
76242
  entered_yolo: "YOLO mode was just enabled for this turn.",
77604
76243
  exited_yolo: "YOLO mode was just disabled; do not assume previous absolute-path access still applies.",
77605
- entered_plan: "Plan mode was just enabled; analyze and plan without changing the workspace. Use plan_scratch for temporary drafts, then submit the finished plan by calling plan_submit with the ordered steps for user approval.",
76244
+ entered_plan: "Plan mode was just enabled \u2014 discussion-first: grill the user in rounds (numbered frontier questions + recommended answers); do not output a plan until explicitly asked. Use plan_scratch for drafts.",
77606
76245
  exited_plan: "Plan mode was just disabled; execution tools may be used when the task requires them."
77607
76246
  };
77608
76247
  lines.push(`- Transition: ${transitionText[state.pendingTransition]}`);
@@ -78293,7 +76932,7 @@ function setupInteractiveEditorSubmitHandler(host) {
78293
76932
  host.chatContainer.addChild(userMsg);
78294
76933
  host.editor.setText("");
78295
76934
  host.ui.requestRender();
78296
- await new Promise((resolve7) => setImmediate(resolve7));
76935
+ await new Promise((resolve8) => setImmediate(resolve8));
78297
76936
  let finalContent = messageContent;
78298
76937
  const reminderPrefix = host.executionState.getReminder() ?? host.executionReminder;
78299
76938
  const combinedPrefix = [reminderPrefix].filter((value) => Boolean(value)).join("");
@@ -80118,17 +78757,17 @@ function setupInteractiveKeybindings(host) {
80118
78757
  }
80119
78758
 
80120
78759
  // src/clipboard/read-clipboard-image.ts
80121
- import { spawn as spawn2 } from "node:child_process";
80122
- import { chmodSync as chmodSync2, closeSync as closeSync4, existsSync as existsSync18, fchmodSync, mkdtempSync, openSync as openSync4, readFileSync as readFileSync17, rmdirSync, statSync as statSync12, unlinkSync as unlinkSync7, writeFileSync as writeFileSync11 } from "node:fs";
78760
+ import { spawn as spawn4 } from "node:child_process";
78761
+ import { chmodSync, closeSync as closeSync2, existsSync as existsSync16, fchmodSync, mkdtempSync, openSync as openSync2, readFileSync as readFileSync17, rmdirSync, statSync as statSync12, unlinkSync as unlinkSync5, writeFileSync as writeFileSync9 } from "node:fs";
80123
78762
  import { tmpdir } from "node:os";
80124
- import { join as join20 } from "node:path";
78763
+ import { join as join19 } from "node:path";
80125
78764
  var MAX_IMAGE_BYTES = 50 * 1024 * 1024;
80126
78765
  var COMMAND_TIMEOUT_MS = 1e4;
80127
78766
  function isSpawnFailure(outcome) {
80128
78767
  return !outcome.ok;
80129
78768
  }
80130
- function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYTES, timeoutMs = COMMAND_TIMEOUT_MS) {
80131
- return new Promise((resolve7) => {
78769
+ function defaultSpawnFn(file, args, spawnImpl = spawn4, maxBytes = MAX_IMAGE_BYTES, timeoutMs = COMMAND_TIMEOUT_MS) {
78770
+ return new Promise((resolve8) => {
80132
78771
  let child;
80133
78772
  try {
80134
78773
  child = spawnImpl(file, args, {
@@ -80136,7 +78775,7 @@ function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYT
80136
78775
  windowsHide: true
80137
78776
  });
80138
78777
  } catch (err) {
80139
- resolve7({ ok: false, error: "spawn-failed", message: err instanceof Error ? err.message : String(err) });
78778
+ resolve8({ ok: false, error: "spawn-failed", message: err instanceof Error ? err.message : String(err) });
80140
78779
  return;
80141
78780
  }
80142
78781
  let settled = false;
@@ -80150,13 +78789,13 @@ function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYT
80150
78789
  child.kill("SIGKILL");
80151
78790
  } catch {
80152
78791
  }
80153
- resolve7({ ok: false, error: "timeout" });
78792
+ resolve8({ ok: false, error: "timeout" });
80154
78793
  }, timeoutMs);
80155
78794
  child.on("error", (err) => {
80156
78795
  if (settled) return;
80157
78796
  settled = true;
80158
78797
  clearTimeout(timer);
80159
- resolve7({ ok: false, error: err.code === "ENOENT" ? "not-found" : "spawn-failed", message: err.message });
78798
+ resolve8({ ok: false, error: err.code === "ENOENT" ? "not-found" : "spawn-failed", message: err.message });
80160
78799
  });
80161
78800
  child.stdout?.on("data", (chunk) => {
80162
78801
  if (settled) return;
@@ -80164,7 +78803,7 @@ function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYT
80164
78803
  settled = true;
80165
78804
  clearTimeout(timer);
80166
78805
  stdoutChunks.length = 0;
80167
- resolve7({ ok: false, error: "too-large" });
78806
+ resolve8({ ok: false, error: "too-large" });
80168
78807
  try {
80169
78808
  child.kill("SIGKILL");
80170
78809
  } catch {
@@ -80181,7 +78820,7 @@ function defaultSpawnFn(file, args, spawnImpl = spawn2, maxBytes = MAX_IMAGE_BYT
80181
78820
  if (settled) return;
80182
78821
  settled = true;
80183
78822
  clearTimeout(timer);
80184
- resolve7({ ok: true, result: { code: code ?? -1, stdout: Buffer.concat(stdoutChunks, stdoutBytes), stderr: stderrText } });
78823
+ resolve8({ ok: true, result: { code: code ?? -1, stdout: Buffer.concat(stdoutChunks, stdoutBytes), stderr: stderrText } });
80185
78824
  });
80186
78825
  });
80187
78826
  }
@@ -80194,23 +78833,23 @@ var TempImageResources = class {
80194
78833
  files = /* @__PURE__ */ new Set();
80195
78834
  create = (ext) => {
80196
78835
  if (!this.injectedPath && !this.directory) {
80197
- this.directory = mkdtempSync(join20(tmpdir(), "pie-clipboard-"));
80198
- if (process.platform !== "win32") chmodSync2(this.directory, 448);
78836
+ this.directory = mkdtempSync(join19(tmpdir(), "pie-clipboard-"));
78837
+ if (process.platform !== "win32") chmodSync(this.directory, 448);
80199
78838
  }
80200
- const path34 = this.injectedPath ? this.injectedPath(ext) : join20(this.directory, `image${ext}`);
80201
- const fd = openSync4(path34, "wx", 384);
78839
+ const path34 = this.injectedPath ? this.injectedPath(ext) : join19(this.directory, `image${ext}`);
78840
+ const fd = openSync2(path34, "wx", 384);
80202
78841
  this.files.add(path34);
80203
78842
  try {
80204
78843
  if (process.platform !== "win32") fchmodSync(fd, 384);
80205
78844
  } finally {
80206
- closeSync4(fd);
78845
+ closeSync2(fd);
80207
78846
  }
80208
78847
  return path34;
80209
78848
  };
80210
78849
  cleanup = () => {
80211
78850
  for (const path34 of this.files) {
80212
78851
  try {
80213
- unlinkSync7(path34);
78852
+ unlinkSync5(path34);
80214
78853
  this.files.delete(path34);
80215
78854
  } catch (err) {
80216
78855
  if (err.code === "ENOENT") this.files.delete(path34);
@@ -80428,7 +79067,7 @@ function writeImageBytes(bytes, declaredMime, mkTempPath) {
80428
79067
  const mimeType = detectMimeFromMagic(bytes) ?? declaredMime;
80429
79068
  const targetPath = mkTempPath(extensionForMime(mimeType));
80430
79069
  try {
80431
- writeFileSync11(targetPath, bytes, { flag: "r+", mode: 384 });
79070
+ writeFileSync9(targetPath, bytes, { flag: "r+", mode: 384 });
80432
79071
  } catch (err) {
80433
79072
  return { ok: false, kind: "failed", message: `Failed to write temp image: ${errorMessage4(err)}` };
80434
79073
  }
@@ -80441,7 +79080,7 @@ function writeImageBytes(bytes, declaredMime, mkTempPath) {
80441
79080
  function finalizeTempImage(path34, mimeType) {
80442
79081
  let bytes;
80443
79082
  try {
80444
- if (!existsSync18(path34)) {
79083
+ if (!existsSync16(path34)) {
80445
79084
  return { ok: false, kind: "no-image", message: "Clipboard does not contain an image." };
80446
79085
  }
80447
79086
  const size = statSync12(path34).size;
@@ -80499,9 +79138,9 @@ function formatBytes2(bytes) {
80499
79138
  }
80500
79139
 
80501
79140
  // src/input/image-paste.ts
80502
- import { mkdtempSync as mkdtempSync2, writeFileSync as writeFileSync12, rmSync as rmSync3 } from "node:fs";
79141
+ import { mkdtempSync as mkdtempSync2, writeFileSync as writeFileSync10, rmSync as rmSync3 } from "node:fs";
80503
79142
  import { tmpdir as tmpdir2 } from "node:os";
80504
- import { join as join21 } from "node:path";
79143
+ import { join as join20 } from "node:path";
80505
79144
  var pastingHosts = /* @__PURE__ */ new WeakSet();
80506
79145
  function formatPastedImageName(date, extension = ".png") {
80507
79146
  const pad = (value) => String(value).padStart(2, "0");
@@ -80526,9 +79165,9 @@ function terminalResultToClipboardResult(result) {
80526
79165
  const ext = result.mimeType === "image/jpeg" ? ".jpg" : ".png";
80527
79166
  let dir;
80528
79167
  try {
80529
- dir = mkdtempSync2(join21(tmpdir2(), "pie-osc5522-"));
80530
- const path34 = join21(dir, formatPastedImageName(/* @__PURE__ */ new Date(), ext));
80531
- writeFileSync12(path34, result.bytes);
79168
+ dir = mkdtempSync2(join20(tmpdir2(), "pie-osc5522-"));
79169
+ const path34 = join20(dir, formatPastedImageName(/* @__PURE__ */ new Date(), ext));
79170
+ writeFileSync10(path34, result.bytes);
80532
79171
  return {
80533
79172
  ok: true,
80534
79173
  path: path34,
@@ -80807,11 +79446,24 @@ var ExtensionStatusSlots = class {
80807
79446
  clear() {
80808
79447
  this.slots.clear();
80809
79448
  }
80810
- /** Render-ready suffix for the footer line, e.g. " · git:clean · ci:ok". */
79449
+ /** Render-ready footer cluster for the extension slots, e.g.
79450
+ * `"git:clean · ci:running"`. Bracket-tag values ("[IM]", "[MEM]")
79451
+ * concatenate directly — matching the built-in [PLAN]/[CALM]/[YOLO]
79452
+ * convention — while free-form statuses separate with " · ". No
79453
+ * leading separator: the footer inserts one only before a non-tag. */
80811
79454
  format(maxWidth = 60) {
80812
79455
  if (this.slots.size === 0) return "";
80813
- const joined = [...this.slots.values()].join(" \xB7 ");
80814
- return ` \xB7 ${truncateToWidth(joined, maxWidth, "")}`;
79456
+ let joined = "";
79457
+ for (const value of this.slots.values()) {
79458
+ if (joined === "") {
79459
+ joined = value;
79460
+ } else if (/^\[[^\[\]]+\]$/.test(value) && joined.endsWith("]")) {
79461
+ joined += value;
79462
+ } else {
79463
+ joined += ` \xB7 ${value}`;
79464
+ }
79465
+ }
79466
+ return truncateToWidth(joined, maxWidth, "");
80815
79467
  }
80816
79468
  };
80817
79469
 
@@ -80940,27 +79592,22 @@ var FooterComponent = class {
80940
79592
  if (branch) {
80941
79593
  pwd = `${pwd} (${branch})`;
80942
79594
  }
80943
- if (visibleWidth(pwd) > width) {
80944
- const half = Math.floor(width / 2) - 2;
80945
- if (half > 1) {
80946
- const total = visibleWidth(pwd);
80947
- const head = sliceByColumn(pwd, 0, half);
80948
- const tail = sliceByColumn(pwd, Math.max(0, total - (half - 1)), half - 1);
80949
- pwd = `${head}...${tail}`;
80950
- } else {
80951
- pwd = truncateToWidth(pwd, width);
80952
- }
80953
- }
80954
- const statsParts = [];
79595
+ const tags = [];
80955
79596
  if (state.planMode) {
80956
- statsParts.push(theme.fg("accent", "[PLAN]"));
79597
+ tags.push(theme.fg("accent", "[PLAN]"));
80957
79598
  }
80958
79599
  if (state.calmMode) {
80959
- statsParts.push(theme.fg("dim", "[CALM]"));
79600
+ tags.push(theme.fg("dim", "[CALM]"));
80960
79601
  }
80961
79602
  if (state.yoloMode) {
80962
- statsParts.push(theme.fg("warning", "[YOLO]"));
79603
+ tags.push(theme.fg("warning", "[YOLO]"));
80963
79604
  }
79605
+ const extensionTags = this.extensionStatuses.format();
79606
+ let tagLine = "";
79607
+ if (tags.length > 0 || extensionTags) {
79608
+ tagLine = tags.length > 0 && extensionTags && !/^\[[^\[\]]+\]/.test(extensionTags) ? tags.join("") + " \xB7 " + extensionTags : tags.join("") + extensionTags;
79609
+ }
79610
+ const statsParts = [];
80964
79611
  if (state.inputTokens) statsParts.push(`\u2191${formatTokens(state.inputTokens)}`);
80965
79612
  if (state.outputTokens) statsParts.push(`\u2193${formatTokens(state.outputTokens)}`);
80966
79613
  if (state.cacheRead) statsParts.push(`R${formatTokens(state.cacheRead)}`);
@@ -81017,8 +79664,7 @@ var FooterComponent = class {
81017
79664
  return theme.fg(statusColor[state.status], `${spinner ? `${spinner} ` : ""}${statusText}${busyElapsed}`);
81018
79665
  })();
81019
79666
  statsParts.push(statusWithSpinner);
81020
- let statsLeft = statsParts.join(" ");
81021
- statsLeft += this.extensionStatuses.format();
79667
+ const statsLeft = statsParts.join(" ");
81022
79668
  const modelName = state.modelName || "no-model";
81023
79669
  let rightSide = modelName;
81024
79670
  if (state.thinkingLevel) {
@@ -81043,8 +79689,32 @@ var FooterComponent = class {
81043
79689
  statsLine = truncateToWidth(statsLeft, width);
81044
79690
  }
81045
79691
  }
79692
+ const plainTags = tagLine.replace(/\x1b\[[0-9;]*m/g, "");
79693
+ const tagsWidth = visibleWidth(plainTags);
79694
+ let pwdWidth = visibleWidth(pwd);
79695
+ if (pwdWidth > width || tagsWidth > 0 && pwdWidth + 2 + tagsWidth > width) {
79696
+ const room = tagsWidth > 0 ? Math.max(0, width - 2 - tagsWidth) : width;
79697
+ const half = Math.floor(room / 2) - 2;
79698
+ if (half > 1) {
79699
+ const total = pwdWidth;
79700
+ const head = sliceByColumn(pwd, 0, half);
79701
+ const tail = sliceByColumn(pwd, Math.max(0, total - (half - 1)), half - 1);
79702
+ pwd = `${head}...${tail}`;
79703
+ } else {
79704
+ pwd = truncateToWidth(pwd, room);
79705
+ }
79706
+ pwdWidth = visibleWidth(pwd);
79707
+ }
79708
+ let firstLine;
79709
+ if (tagsWidth === 0) {
79710
+ firstLine = pwd;
79711
+ } else if (pwdWidth + 2 + tagsWidth <= width) {
79712
+ firstLine = pwd + " ".repeat(width - pwdWidth - tagsWidth) + plainTags;
79713
+ } else {
79714
+ firstLine = " ".repeat(Math.max(0, width - tagsWidth)) + truncateToWidth(plainTags, width, "");
79715
+ }
81046
79716
  const lines = [
81047
- truncateToWidth(theme.fg("dim", pwd), width),
79717
+ truncateToWidth(theme.fg("dim", firstLine), width),
81048
79718
  truncateToWidth(theme.fg("dim", statsLine), width)
81049
79719
  ];
81050
79720
  return lines;
@@ -81126,8 +79796,8 @@ function calculateCliContextUsage(params) {
81126
79796
  );
81127
79797
  const estimate = estimateContextTokens(messages);
81128
79798
  const usageMessage = estimate.lastUsageIndex !== null ? messages[estimate.lastUsageIndex] : void 0;
81129
- const usage = usageMessage?.role === "assistant" ? usageMessage.usage : void 0;
81130
- const hasProviderMeasurement = usage !== void 0 && estimate.lastUsageIndex !== null;
79799
+ const usage2 = usageMessage?.role === "assistant" ? usageMessage.usage : void 0;
79800
+ const hasProviderMeasurement = usage2 !== void 0 && estimate.lastUsageIndex !== null;
81131
79801
  return {
81132
79802
  tokens: estimate.tokens,
81133
79803
  estimatedCurrentTokens: estimate.tokens,
@@ -81137,13 +79807,13 @@ function calculateCliContextUsage(params) {
81137
79807
  // tool/user message (or a compaction reset, which zeroes stale usage)
81138
79808
  // makes the two figures different snapshots, so no error may be shown.
81139
79809
  measurementMatchesCurrentContext: hasProviderMeasurement && estimate.lastUsageIndex === messages.length - 1,
81140
- input: usage?.input ?? 0,
81141
- output: usage?.output ?? 0,
81142
- cacheRead: usage?.cacheRead ?? 0,
81143
- cacheWrite: usage?.cacheWrite ?? 0,
81144
- cacheWriteLong: usage?.cacheWriteLong ?? 0,
81145
- cost: usage?.cost.total ?? 0,
81146
- costEstimated: usage?.cost?.cacheWriteLongEstimated === true
79810
+ input: usage2?.input ?? 0,
79811
+ output: usage2?.output ?? 0,
79812
+ cacheRead: usage2?.cacheRead ?? 0,
79813
+ cacheWrite: usage2?.cacheWrite ?? 0,
79814
+ cacheWriteLong: usage2?.cacheWriteLong ?? 0,
79815
+ cost: usage2?.cost.total ?? 0,
79816
+ costEstimated: usage2?.cost?.cacheWriteLongEstimated === true
81147
79817
  };
81148
79818
  }
81149
79819
  function createCliAutoCompactDecision(params) {
@@ -81154,18 +79824,18 @@ function createCliAutoCompactDecision(params) {
81154
79824
  if (!params.autoCompactEnabled || params.contextWindow <= 0) {
81155
79825
  return void 0;
81156
79826
  }
81157
- const usage = calculateCliContextUsage({
79827
+ const usage2 = calculateCliContextUsage({
81158
79828
  messages: params.messages,
81159
79829
  latestCompactionTimestamp: params.latestCompactionTimestamp
81160
79830
  });
81161
- if (!usage.tokens) {
79831
+ if (!usage2.tokens) {
81162
79832
  return void 0;
81163
79833
  }
81164
79834
  const tokenLimit = getAutoCompactTokenLimit(params.contextWindow, params.reserveTokens);
81165
79835
  if (tokenLimit === void 0) {
81166
79836
  return void 0;
81167
79837
  }
81168
- return usage.tokens > tokenLimit ? { reason: "threshold", willRetry: false } : void 0;
79838
+ return usage2.tokens > tokenLimit ? { reason: "threshold", willRetry: false } : void 0;
81169
79839
  }
81170
79840
  function shouldCliAutoCompactTokens(params) {
81171
79841
  if (!params.tokens || params.contextWindow <= 0) {
@@ -81846,7 +80516,7 @@ async function recoverHardStalledTurn(host, stalledMs) {
81846
80516
  try {
81847
80517
  await Promise.race([
81848
80518
  host.agentSessionController?.waitForIdle() ?? Promise.resolve(),
81849
- new Promise((resolve7) => setTimeout(resolve7, 2e3))
80519
+ new Promise((resolve8) => setTimeout(resolve8, 2e3))
81850
80520
  ]);
81851
80521
  } catch (error) {
81852
80522
  host.logDebug("continuation_timeout:hard_stall_wait_failed", {
@@ -82525,8 +81195,8 @@ async function handleDirectBash(host, command) {
82525
81195
  outputContainer.addChild(new Spacer(1));
82526
81196
  host.chatContainer.addChild(outputContainer);
82527
81197
  host.ui.requestRender();
82528
- const { spawn: spawn3 } = await import("child_process");
82529
- const child = spawn3(shellCommand.file, shellCommand.args, {
81198
+ const { spawn: spawn5 } = await import("child_process");
81199
+ const child = spawn5(shellCommand.file, shellCommand.args, {
82530
81200
  cwd: process.cwd(),
82531
81201
  env: process.env
82532
81202
  });
@@ -82537,7 +81207,7 @@ async function handleDirectBash(host, command) {
82537
81207
  child.stderr.on("data", (data) => {
82538
81208
  output.append(data.toString());
82539
81209
  });
82540
- return new Promise((resolve7) => {
81210
+ return new Promise((resolve8) => {
82541
81211
  let settled = false;
82542
81212
  const finish = (code) => {
82543
81213
  if (settled) return;
@@ -82550,7 +81220,7 @@ async function handleDirectBash(host, command) {
82550
81220
  }
82551
81221
  host.chatContainer.addChild(new Spacer(1));
82552
81222
  host.ui.requestRender();
82553
- resolve7();
81223
+ resolve8();
82554
81224
  };
82555
81225
  child.on("error", (error) => {
82556
81226
  output.append(error.message);
@@ -82602,19 +81272,19 @@ function installInteractiveInteractionHandler(host) {
82602
81272
  const endWaitingForUser = (resolution) => {
82603
81273
  endExtensionWaiting(host, attentionRequest, resolution);
82604
81274
  };
82605
- const withTimeout2 = async (createPromise) => {
81275
+ const withTimeout = async (createPromise) => {
82606
81276
  const controller = new AbortController();
82607
81277
  if (!("timeoutMs" in request) || !request.timeoutMs || request.timeoutMs <= 0) {
82608
81278
  return { value: await createPromise(controller.signal), timedOut: false };
82609
81279
  }
82610
- return await new Promise((resolve7, reject) => {
81280
+ return await new Promise((resolve8, reject) => {
82611
81281
  const timer = setTimeout(() => {
82612
81282
  controller.abort();
82613
- resolve7({ timedOut: true });
81283
+ resolve8({ timedOut: true });
82614
81284
  }, request.timeoutMs);
82615
81285
  createPromise(controller.signal).then((value) => {
82616
81286
  clearTimeout(timer);
82617
- resolve7({ value, timedOut: false });
81287
+ resolve8({ value, timedOut: false });
82618
81288
  }).catch((error) => {
82619
81289
  clearTimeout(timer);
82620
81290
  reject(error);
@@ -82625,7 +81295,7 @@ function installInteractiveInteractionHandler(host) {
82625
81295
  beginWaitingForUser();
82626
81296
  let resolution = "cancelled";
82627
81297
  try {
82628
- const result = await withTimeout2(createPromise);
81298
+ const result = await withTimeout(createPromise);
82629
81299
  resolution = interactionAttentionResolution(result);
82630
81300
  return result;
82631
81301
  } finally {
@@ -82762,12 +81432,12 @@ function showExtensionNotification(host, message, type = "info", opts) {
82762
81432
  host.ui.requestRender();
82763
81433
  }
82764
81434
  function showExtensionSelector2(host, title, options, opts) {
82765
- return new Promise((resolve7) => {
81435
+ return new Promise((resolve8) => {
82766
81436
  const promptLine = title.split("\n")[0].trim() || title.trim();
82767
81437
  host.showStatus(`Waiting for selection: ${promptLine}`);
82768
81438
  if (opts?.signal?.aborted) {
82769
81439
  host.clearStatusLine?.();
82770
- resolve7(void 0);
81440
+ resolve8(void 0);
82771
81441
  return;
82772
81442
  }
82773
81443
  const settle = (option) => {
@@ -82777,12 +81447,12 @@ function showExtensionSelector2(host, title, options, opts) {
82777
81447
  host.showStatus(`${promptLine} \u2192 ${option}`);
82778
81448
  }
82779
81449
  host.restoreEditor();
82780
- resolve7(option);
81450
+ resolve8(option);
82781
81451
  };
82782
81452
  const onAbort = () => {
82783
81453
  host.clearStatusLine?.();
82784
81454
  host.restoreEditor();
82785
- resolve7(void 0);
81455
+ resolve8(void 0);
82786
81456
  };
82787
81457
  opts?.signal?.addEventListener("abort", onAbort, { once: true });
82788
81458
  const selector = new ExtensionSelectorComponent(
@@ -82817,17 +81487,17 @@ ${message}`, options, opts);
82817
81487
  return { confirmed: result === "Yes" };
82818
81488
  }
82819
81489
  function showExtensionInput(host, title, placeholder, opts) {
82820
- return new Promise((resolve7) => {
81490
+ return new Promise((resolve8) => {
82821
81491
  host.showStatus(`Waiting for input: ${title}`);
82822
81492
  if (opts?.signal?.aborted) {
82823
81493
  host.clearStatusLine?.();
82824
- resolve7(void 0);
81494
+ resolve8(void 0);
82825
81495
  return;
82826
81496
  }
82827
81497
  const settle = (value) => {
82828
81498
  host.clearStatusLine?.();
82829
81499
  host.restoreEditor();
82830
- resolve7(value);
81500
+ resolve8(value);
82831
81501
  };
82832
81502
  const onAbort = () => settle(void 0);
82833
81503
  opts?.signal?.addEventListener("abort", onAbort, { once: true });
@@ -82851,12 +81521,12 @@ function showExtensionInput(host, title, placeholder, opts) {
82851
81521
  });
82852
81522
  }
82853
81523
  function showExtensionEditor(host, title, prefill, opts) {
82854
- return new Promise((resolve7) => {
81524
+ return new Promise((resolve8) => {
82855
81525
  host.showStatus(`Waiting for input: ${title}`);
82856
81526
  const settle = (value) => {
82857
81527
  host.clearStatusLine?.();
82858
81528
  host.restoreEditor();
82859
- resolve7(value);
81529
+ resolve8(value);
82860
81530
  };
82861
81531
  const onAbort = () => settle(void 0);
82862
81532
  opts?.signal?.addEventListener("abort", onAbort, { once: true });
@@ -82903,14 +81573,14 @@ function showExtensionEditor(host, title, prefill, opts) {
82903
81573
  }
82904
81574
  function showExtensionCustom(host, factory, options) {
82905
81575
  const savedText = host.editor.getText();
82906
- return new Promise((resolve7, reject) => {
81576
+ return new Promise((resolve8, reject) => {
82907
81577
  let closed = false;
82908
81578
  const close = (result) => {
82909
81579
  if (closed) return;
82910
81580
  closed = true;
82911
81581
  host.restoreEditor();
82912
81582
  host.editor.setText(savedText);
82913
- resolve7(result);
81583
+ resolve8(result);
82914
81584
  };
82915
81585
  Promise.resolve(factory(host.ui, theme, close)).then((component) => {
82916
81586
  if (closed) return;
@@ -83796,7 +82466,7 @@ var InteractiveMode = class {
83796
82466
  async init() {
83797
82467
  const activeSession = this.sessionManager.getActiveSession();
83798
82468
  this.thinkingLevel = resolveInitialThinkingLevel({ session: activeSession, settingsManager: this.options.settingsManager });
83799
- const { Agent } = await import("./chunks/src-GX4UBAYF.js");
82469
+ const { Agent } = await import("./chunks/src-YG5M2H44.js");
83800
82470
  this.agent = new Agent({
83801
82471
  initialState: {
83802
82472
  systemPrompt: this.buildSystemPrompt(),
@@ -84119,7 +82789,12 @@ var InteractiveMode = class {
84119
82789
  "/skills/create",
84120
82790
  "/skills/use",
84121
82791
  "/tools/subagent",
84122
- "/sessions/fork"
82792
+ "/sessions/fork",
82793
+ // Plan submit/revise return agent-turn instructions the hierarchical
82794
+ // menu would otherwise discard: route them into the editor so the
82795
+ // input pipeline's result-processing handles them like typed commands.
82796
+ "/tools/plan/submit",
82797
+ "/tools/plan/revise"
84123
82798
  ];
84124
82799
  return interactiveCommands.some((cmd) => commandPath.startsWith(cmd));
84125
82800
  }
@@ -84228,7 +82903,7 @@ var InteractiveMode = class {
84228
82903
  };
84229
82904
 
84230
82905
  // src/app/runtime-composition.ts
84231
- import { existsSync as existsSync19, mkdirSync as mkdirSync13 } from "fs";
82906
+ import { existsSync as existsSync17, mkdirSync as mkdirSync11 } from "fs";
84232
82907
  import { randomUUID as randomUUID2 } from "crypto";
84233
82908
  import * as path31 from "path";
84234
82909
  var CliMissingApiKeyError = class extends Error {
@@ -84256,8 +82931,8 @@ function getCliRuntimePaths() {
84256
82931
  return { configDir, sessionsDir, skillsDir, builtinSkillsDir };
84257
82932
  }
84258
82933
  function ensureCliRuntimePaths(paths = getCliRuntimePaths()) {
84259
- if (!existsSync19(paths.skillsDir)) {
84260
- mkdirSync13(paths.skillsDir, { recursive: true });
82934
+ if (!existsSync17(paths.skillsDir)) {
82935
+ mkdirSync11(paths.skillsDir, { recursive: true });
84261
82936
  }
84262
82937
  return paths;
84263
82938
  }
@@ -84689,7 +83364,7 @@ async function runPrintMode(params) {
84689
83364
  `);
84690
83365
  console.log("Assistant: ");
84691
83366
  }
84692
- const { Agent: AgentClass } = await import("./chunks/src-GX4UBAYF.js");
83367
+ const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
84693
83368
  let agent;
84694
83369
  const printModeExtensions = await loadPrintModeExtensions({
84695
83370
  cwd: runtime.cwd,
@@ -85218,7 +83893,7 @@ async function runJsonEventsMode(params) {
85218
83893
  return typeof message.sessionId === "string" && message.sessionId !== sessionId;
85219
83894
  }
85220
83895
  function delay(ms) {
85221
- return new Promise((resolve7) => setTimeout(resolve7, Math.max(0, ms)));
83896
+ return new Promise((resolve8) => setTimeout(resolve8, Math.max(0, ms)));
85222
83897
  }
85223
83898
  function touch() {
85224
83899
  if (activeTurn) {
@@ -85584,7 +84259,7 @@ async function runJsonEventsMode(params) {
85584
84259
  const sideTrace = trace;
85585
84260
  const sideApiKey = runtime.apiKey;
85586
84261
  const snapshot = structuredClone(parent.state.messages);
85587
- const { Agent: AgentClass } = await import("./chunks/src-GX4UBAYF.js");
84262
+ const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
85588
84263
  const sideAgent = new AgentClass({
85589
84264
  initialState: {
85590
84265
  systemPrompt: parent.state.systemPrompt,
@@ -85901,10 +84576,10 @@ async function runJsonEventsMode(params) {
85901
84576
  if (params.mockResponse !== void 0) return;
85902
84577
  if (!params.createRuntime && !params.runtime) return;
85903
84578
  try {
85904
- await new Promise((resolve7, reject) => {
84579
+ await new Promise((resolve8, reject) => {
85905
84580
  const timer = setTimeout(() => reject(new Error("prewarm timeout")), prewarmTimeoutMs);
85906
84581
  timer.unref?.();
85907
- void ensureRuntime().then(resolve7, reject).finally(() => clearTimeout(timer));
84582
+ void ensureRuntime().then(resolve8, reject).finally(() => clearTimeout(timer));
85908
84583
  });
85909
84584
  } catch {
85910
84585
  }
@@ -85948,7 +84623,7 @@ async function runJsonEventsMode(params) {
85948
84623
  if (runtime.initialModel.unconfigured || controller) {
85949
84624
  return;
85950
84625
  }
85951
- const { Agent: AgentClass } = await import("./chunks/src-GX4UBAYF.js");
84626
+ const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
85952
84627
  if (runtimeClosing) return;
85953
84628
  const compositionRegistry = createCliHostEnvelopeRegistry();
85954
84629
  const jsonModeExtensions = await loadJsonModeExtensions({ runtime, envelopeRegistry: compositionRegistry, getAgent: () => agent });
@@ -86015,6 +84690,9 @@ async function runJsonEventsMode(params) {
86015
84690
  };
86016
84691
  },
86017
84692
  retry: createCliRetryPolicy(),
84693
+ onExecutionEnd: async ({ messages }) => {
84694
+ await jsonModeExtensions.runner.emit({ type: "agent:end", messages });
84695
+ },
86018
84696
  getAutoCompactDecision: ({ message, messages }) => createCliAutoCompactDecision({
86019
84697
  message,
86020
84698
  messages,
@@ -86159,8 +84837,8 @@ async function runJsonEventsMode(params) {
86159
84837
  return;
86160
84838
  }
86161
84839
  let releaseReady;
86162
- const ready = new Promise((resolve7) => {
86163
- releaseReady = resolve7;
84840
+ const ready = new Promise((resolve8) => {
84841
+ releaseReady = resolve8;
86164
84842
  });
86165
84843
  activeTurn = {
86166
84844
  ready,
@@ -86587,6 +85265,7 @@ Print Mode Options:
86587
85265
  --json-events Run JSONL protocol mode over stdin/stdout
86588
85266
  --session-id Reuse or create a specific session in non-interactive mode
86589
85267
  --resume-required In JSON-events mode, fail if --session-id cannot be resumed
85268
+ --no-cd Resume without restarting in the session's project directory
86590
85269
  --developer-instructions <text> Append stable host/developer instructions in JSON-events mode
86591
85270
  --developer-instructions-file <path> Read stable host/developer instructions from a file
86592
85271
  --extension-path Add an extra extension search directory (repeatable)
@@ -86636,7 +85315,7 @@ async function runWithJsonEventsConsoleIsolation(fn) {
86636
85315
  }
86637
85316
  async function createCliTestStreamFnFromEnv() {
86638
85317
  if (!process.env.PIE_TEST_MOCK_STREAM_SEQUENCE) return void 0;
86639
- return (await import("./chunks/test-stream-AKIZNFCM.js")).createTestStreamFnFromSequenceEnv();
85318
+ return (await import("./chunks/test-stream-JBWXKOQA.js")).createTestStreamFnFromSequenceEnv();
86640
85319
  }
86641
85320
  function resolveJsonEventsDetailFlag() {
86642
85321
  for (let index = 0; index < process.argv.length; index += 1) {
@@ -86652,13 +85331,11 @@ function resolveJsonEventsDetailFlag() {
86652
85331
  }
86653
85332
  return { value: "compact" };
86654
85333
  }
86655
- async function startChat(initialPrompt, testCommand) {
85334
+ async function startChat(initialPrompt, testCommand, explicitSessionId) {
86656
85335
  const rawOutput = process.argv.includes("--raw-output");
86657
85336
  const jsonOutput = process.argv.includes("--json-output");
86658
85337
  const jsonEvents = process.argv.includes("--json-events");
86659
85338
  const resumeRequired = process.argv.includes("--resume-required");
86660
- const sessionIdFlagIndex = process.argv.indexOf("--session-id");
86661
- const explicitSessionId = sessionIdFlagIndex >= 0 ? process.argv[sessionIdFlagIndex + 1] : void 0;
86662
85339
  const extensionPaths = parseRepeatedFlag(process.argv, "--extension-path");
86663
85340
  const extensionFlags = parseExtensionFlags(process.argv);
86664
85341
  if (jsonEvents) {
@@ -86754,9 +85431,9 @@ async function startChat(initialPrompt, testCommand) {
86754
85431
  if (testCommand) {
86755
85432
  await interactive.run();
86756
85433
  console.log(`[TEST] Auto-executing command: ${testCommand}`);
86757
- await new Promise((resolve7) => setTimeout(resolve7, 500));
85434
+ await new Promise((resolve8) => setTimeout(resolve8, 500));
86758
85435
  await interactive.executeCommand(testCommand);
86759
- await new Promise((resolve7) => setTimeout(resolve7, 2e3));
85436
+ await new Promise((resolve8) => setTimeout(resolve8, 2e3));
86760
85437
  console.log("[TEST] Command executed, exiting...");
86761
85438
  process.exit(0);
86762
85439
  return;
@@ -86812,16 +85489,33 @@ async function main() {
86812
85489
  runPermissionsCommand(args.slice(1));
86813
85490
  return;
86814
85491
  }
85492
+ if (args[0] === "memory") {
85493
+ await runMemoryCommand(args.slice(1));
85494
+ return;
85495
+ }
86815
85496
  const parsed = parseCliInvocation(args);
86816
85497
  if (parsed.showHelp) {
86817
85498
  showHelp();
86818
85499
  return;
86819
85500
  }
85501
+ if (parsed.sessionId) {
85502
+ const decision = decideSessionResumeRestart(args, parsed.sessionId, process.cwd());
85503
+ if (decision) {
85504
+ if (decision.action === "restart") {
85505
+ const code = await performResumeRestart(decision, (warning) => console.warn(`[resume] ${warning}`));
85506
+ if (code !== null) {
85507
+ process.exit(code);
85508
+ }
85509
+ } else if (decision.warning) {
85510
+ console.warn(`[resume] ${decision.warning}`);
85511
+ }
85512
+ }
85513
+ }
86820
85514
  if (parsed.testCommand) {
86821
- await startChat(void 0, parsed.testCommand);
85515
+ await startChat(void 0, parsed.testCommand, parsed.sessionId);
86822
85516
  return;
86823
85517
  }
86824
- await startChat(parsed.initialPrompt);
85518
+ await startChat(parsed.initialPrompt, void 0, parsed.sessionId);
86825
85519
  }
86826
85520
  main().catch((err) => {
86827
85521
  logError("Fatal error", err);