@cydm/pie 4.4.0 → 4.4.2

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 (41) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +6 -6
  2. package/dist/builtin/extensions/changelog/index.js +1 -1
  3. package/dist/builtin/extensions/cron/index.js +2 -2
  4. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  5. package/dist/builtin/extensions/herdr-agent-state/index.js +1 -1
  6. package/dist/builtin/extensions/im-forward/README.md +4 -3
  7. package/dist/builtin/extensions/im-forward/index.js +24 -5
  8. package/dist/builtin/extensions/init/index.js +1 -1
  9. package/dist/builtin/extensions/mcp-adapter/index.js +2 -2
  10. package/dist/builtin/extensions/memory/index.js +11 -9
  11. package/dist/builtin/extensions/pie-ipc/index.js +270 -344
  12. package/dist/builtin/extensions/pie-proc/index.js +70 -7
  13. package/dist/builtin/extensions/plan-mode/index.js +6 -6
  14. package/dist/builtin/extensions/subagent/index.js +11 -9
  15. package/dist/builtin/extensions/todo/index.js +6 -6
  16. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +1 -1
  17. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +1 -1
  18. package/dist/chunks/{auth-storage-3EGM3VTK.js → auth-storage-RABPRJ6T.js} +3 -3
  19. package/dist/chunks/chunk-7KLWHWZD.js +164 -0
  20. package/dist/chunks/{chunk-I7PBXG5Q.js → chunk-7LTQLJJF.js} +9 -6
  21. package/dist/chunks/{chunk-XXGYUYXI.js → chunk-BPSCGGVF.js} +1 -1
  22. package/dist/chunks/{chunk-VHKMWOG3.js → chunk-EQOI6RZV.js} +5 -3
  23. package/dist/chunks/{chunk-B4N5LJMD.js → chunk-IPLMGAML.js} +1 -1
  24. package/dist/chunks/{chunk-GY47MKCJ.js → chunk-IZDNZW3S.js} +8 -8
  25. package/dist/chunks/{chunk-AKXEZH7K.js → chunk-OFLKAWI4.js} +0 -7
  26. package/dist/chunks/{chunk-6DNYGVZP.js → chunk-OV7SLSHR.js} +4 -2
  27. package/dist/chunks/{chunk-6JEYRAQM.js → chunk-R7VO46EK.js} +2 -2
  28. package/dist/chunks/{chunk-LZQXQOPJ.js → chunk-RZGYXAJU.js} +12 -1
  29. package/dist/chunks/{chunk-ILUHTKF3.js → chunk-UCKOXAME.js} +61 -11
  30. package/dist/chunks/{chunk-XMOWWL4B.js → chunk-XO3NM7BB.js} +3 -3
  31. package/dist/chunks/{chunk-N5B5IGJ6.js → chunk-YNTIOWCD.js} +5 -5
  32. package/dist/chunks/{config-74AUVDLT.js → config-HF2PDLN5.js} +8 -4
  33. package/dist/chunks/{manager-cli-4Z6RZ7F4.js → manager-cli-BYCF4RKN.js} +5 -3
  34. package/dist/chunks/{model-registry-NKE3BRSZ.js → model-registry-7FNIUYPF.js} +5 -5
  35. package/dist/chunks/{src-V2M7FLWY.js → src-A5YI46OD.js} +6 -6
  36. package/dist/chunks/{src-4EQ7PBEI.js → src-OA3TP6DS.js} +5 -5
  37. package/dist/chunks/{src-46R5ZFOU.js → src-OVWRBWKU.js} +4 -4
  38. package/dist/chunks/{src-BHIH4VLE.js → src-TF2RAGRU.js} +3 -3
  39. package/dist/chunks/{test-stream-FC6ZRENI.js → test-stream-7YZDGBPO.js} +3 -3
  40. package/dist/cli.js +231 -49
  41. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -3,10 +3,10 @@ import { createRequire as __createRequire } from "node:module"; const require =
3
3
  import {
4
4
  AuthStorage,
5
5
  FileAuthStorageBackend
6
- } from "./chunks/chunk-6DNYGVZP.js";
6
+ } from "./chunks/chunk-OV7SLSHR.js";
7
7
  import {
8
8
  ModelRegistry
9
- } from "./chunks/chunk-VHKMWOG3.js";
9
+ } from "./chunks/chunk-EQOI6RZV.js";
10
10
  import {
11
11
  distillWorkerLogPath,
12
12
  readDistillWorkerLog,
@@ -14,7 +14,10 @@ import {
14
14
  runDistillWorkerMain,
15
15
  spawnDistillAutoWorker,
16
16
  spawnDistillWorker
17
- } from "./chunks/chunk-GY47MKCJ.js";
17
+ } from "./chunks/chunk-IZDNZW3S.js";
18
+ import {
19
+ claimSessionOwnership
20
+ } from "./chunks/chunk-7KLWHWZD.js";
18
21
  import {
19
22
  CLI_RETRY_MAX_RETRIES,
20
23
  classifyCliFailure,
@@ -31,7 +34,7 @@ import {
31
34
  logTransportLifecycle,
32
35
  setYoloGrantListener,
33
36
  truncateHeadTail
34
- } from "./chunks/chunk-I7PBXG5Q.js";
37
+ } from "./chunks/chunk-7LTQLJJF.js";
35
38
  import {
36
39
  VERSION,
37
40
  getAgentDir,
@@ -45,8 +48,9 @@ import {
45
48
  getSessionsDir,
46
49
  getSettingsPath,
47
50
  getThemesDir,
51
+ init_config,
48
52
  migrateConfigFromAgentDir
49
- } from "./chunks/chunk-ILUHTKF3.js";
53
+ } from "./chunks/chunk-UCKOXAME.js";
50
54
  import {
51
55
  BUILTIN_TOOL_CAPABILITY_METADATA,
52
56
  MemoryStore,
@@ -76,7 +80,7 @@ import {
76
80
  shouldPreserveExecutionStateForUserText,
77
81
  supersedeExecutionState,
78
82
  todayKey
79
- } from "./chunks/chunk-N5B5IGJ6.js";
83
+ } from "./chunks/chunk-YNTIOWCD.js";
80
84
  import {
81
85
  AGENTS_CONTEXT_FILE_NAME,
82
86
  AgentSessionController,
@@ -116,8 +120,8 @@ import {
116
120
  setEnablementInMap,
117
121
  setExtensionEnabledInSettings,
118
122
  verifyPreparedCompactionCommit
119
- } from "./chunks/chunk-XMOWWL4B.js";
120
- import "./chunks/chunk-B4N5LJMD.js";
123
+ } from "./chunks/chunk-XO3NM7BB.js";
124
+ import "./chunks/chunk-IPLMGAML.js";
121
125
  import {
122
126
  Deref,
123
127
  Errors,
@@ -136,7 +140,7 @@ import {
136
140
  setLogger,
137
141
  streamSimple,
138
142
  type_exports
139
- } from "./chunks/chunk-6JEYRAQM.js";
143
+ } from "./chunks/chunk-R7VO46EK.js";
140
144
  import {
141
145
  IsArray,
142
146
  IsBigInt,
@@ -150,7 +154,7 @@ import {
150
154
  Type,
151
155
  TypeBoxError,
152
156
  TypeSystemPolicy
153
- } from "./chunks/chunk-XXGYUYXI.js";
157
+ } from "./chunks/chunk-BPSCGGVF.js";
154
158
  import {
155
159
  readImageFormat
156
160
  } from "./chunks/chunk-F7EBZTZO.js";
@@ -161,7 +165,7 @@ import {
161
165
  __commonJS,
162
166
  __require,
163
167
  __toESM
164
- } from "./chunks/chunk-LZQXQOPJ.js";
168
+ } from "./chunks/chunk-RZGYXAJU.js";
165
169
 
166
170
  // ../../node_modules/color-name/index.js
167
171
  var require_color_name = __commonJS({
@@ -50857,14 +50861,14 @@ var require_parser2 = __commonJS({
50857
50861
  case "scalar":
50858
50862
  case "single-quoted-scalar":
50859
50863
  case "double-quoted-scalar": {
50860
- const fs31 = this.flowScalar(this.type);
50864
+ const fs32 = this.flowScalar(this.type);
50861
50865
  if (atNextItem || it.value) {
50862
- map.items.push({ start, key: fs31, sep: [] });
50866
+ map.items.push({ start, key: fs32, sep: [] });
50863
50867
  this.onKeyLine = true;
50864
50868
  } else if (it.sep) {
50865
- this.stack.push(fs31);
50869
+ this.stack.push(fs32);
50866
50870
  } else {
50867
- Object.assign(it, { key: fs31, sep: [] });
50871
+ Object.assign(it, { key: fs32, sep: [] });
50868
50872
  this.onKeyLine = true;
50869
50873
  }
50870
50874
  return;
@@ -50992,13 +50996,13 @@ var require_parser2 = __commonJS({
50992
50996
  case "scalar":
50993
50997
  case "single-quoted-scalar":
50994
50998
  case "double-quoted-scalar": {
50995
- const fs31 = this.flowScalar(this.type);
50999
+ const fs32 = this.flowScalar(this.type);
50996
51000
  if (!it || it.value)
50997
- fc.items.push({ start: [], key: fs31, sep: [] });
51001
+ fc.items.push({ start: [], key: fs32, sep: [] });
50998
51002
  else if (it.sep)
50999
- this.stack.push(fs31);
51003
+ this.stack.push(fs32);
51000
51004
  else
51001
- Object.assign(it, { key: fs31, sep: [] });
51005
+ Object.assign(it, { key: fs32, sep: [] });
51002
51006
  return;
51003
51007
  }
51004
51008
  case "flow-map-end":
@@ -51307,11 +51311,11 @@ var require_dist2 = __commonJS({
51307
51311
  });
51308
51312
 
51309
51313
  // src/cli.ts
51310
- import * as fs30 from "fs";
51314
+ import * as fs31 from "fs";
51311
51315
  import * as path34 from "path";
51312
51316
 
51313
51317
  // src/cli-args.ts
51314
- var FLAGS_WITH_VALUES = /* @__PURE__ */ new Set(["--session-id", "--extension-path", "--developer-instructions", "--developer-instructions-file"]);
51318
+ var FLAGS_WITH_VALUES = /* @__PURE__ */ new Set(["--session-id", "--extension-path", "--developer-instructions", "--developer-instructions-file", "--worker-token"]);
51315
51319
  var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--raw-output", "--json-output", "--json-events", "--resume-required", "--idle"]);
51316
51320
  var HELP_FLAGS = /* @__PURE__ */ new Set(["help", "--help", "-h"]);
51317
51321
  var COMMANDS = /* @__PURE__ */ new Set(["chat", "help"]);
@@ -51392,7 +51396,11 @@ function parseRepeatedFlag(args, flag) {
51392
51396
  return values;
51393
51397
  }
51394
51398
 
51399
+ // src/cli.ts
51400
+ init_config();
51401
+
51395
51402
  // src/debug/file-logger.ts
51403
+ init_config();
51396
51404
  import * as fs from "fs";
51397
51405
  import * as path from "path";
51398
51406
  var FileLogger = class {
@@ -51748,6 +51756,7 @@ import { delimiter } from "node:path";
51748
51756
  // src/core/settings-manager.ts
51749
51757
  import * as fs2 from "fs";
51750
51758
  import * as path2 from "path";
51759
+ init_config();
51751
51760
  function getDisabledToolNames(settingsManager) {
51752
51761
  const disabled = new Set(typeof settingsManager?.getDisabledTools === "function" ? settingsManager.getDisabledTools() : []);
51753
51762
  if (disabled.has("bash") || disabled.has("shell")) {
@@ -52151,6 +52160,7 @@ var SettingsManager = class {
52151
52160
  };
52152
52161
 
52153
52162
  // src/doctor.ts
52163
+ init_config();
52154
52164
  var require2 = createRequire(import.meta.url);
52155
52165
  var UNITY_INSTANCE_MAX_AGE_SEC = 120;
52156
52166
  function checkStatus(checks) {
@@ -52634,6 +52644,7 @@ Disable or narrow capabilities:
52634
52644
  }
52635
52645
 
52636
52646
  // src/commands/models-config.ts
52647
+ init_config();
52637
52648
  import * as fs4 from "node:fs";
52638
52649
  import * as path4 from "node:path";
52639
52650
  function getDefaultModelsPath() {
@@ -53321,6 +53332,7 @@ function truncateText(text, maxChars) {
53321
53332
  }
53322
53333
 
53323
53334
  // src/capabilities.ts
53335
+ init_config();
53324
53336
  function buildCapabilitiesReport() {
53325
53337
  return {
53326
53338
  name: "pie",
@@ -53545,6 +53557,7 @@ function runCapabilitiesCommand(args) {
53545
53557
  }
53546
53558
 
53547
53559
  // src/commands/memory-cli.ts
53560
+ init_config();
53548
53561
  import * as fs5 from "node:fs";
53549
53562
  import * as path5 from "node:path";
53550
53563
  import { pathToFileURL } from "node:url";
@@ -53813,6 +53826,7 @@ function yesterdayKey() {
53813
53826
  }
53814
53827
 
53815
53828
  // src/commands/session-resume-restart.ts
53829
+ init_config();
53816
53830
  import { spawn } from "node:child_process";
53817
53831
  import * as fs6 from "node:fs";
53818
53832
  import * as path6 from "node:path";
@@ -54062,6 +54076,7 @@ async function performResumeRestart(decision, onSpawnFailure) {
54062
54076
 
54063
54077
  // src/commands/sessions.ts
54064
54078
  import fs8 from "node:fs";
54079
+ init_config();
54065
54080
 
54066
54081
  // src/session-control.ts
54067
54082
  import fs7 from "fs";
@@ -54953,6 +54968,7 @@ import * as fs9 from "node:fs";
54953
54968
  import * as os2 from "os";
54954
54969
  import * as path8 from "path";
54955
54970
  import { pathToFileURL as pathToFileURL2 } from "node:url";
54971
+ init_config();
54956
54972
 
54957
54973
  // src/extensions/types.ts
54958
54974
  function interactiveHostCapabilities() {
@@ -55130,7 +55146,7 @@ var CommandTree = class {
55130
55146
  var commandTree = new CommandTree();
55131
55147
 
55132
55148
  // src/extensions/loader.ts
55133
- function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, capabilities, actions) {
55149
+ function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, capabilities, actions, logSink) {
55134
55150
  const context = {
55135
55151
  registerCleanup: (handler) => (extension.resources ??= new ExtensionResourceScope()).register(handler),
55136
55152
  ui: uiContext,
@@ -55142,7 +55158,8 @@ function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, ca
55142
55158
  hasUI: capabilities.interactiveUI,
55143
55159
  cwd,
55144
55160
  log: (message) => {
55145
- if (process.env.PIE_VERBOSE) {
55161
+ if (logSink) logSink(message);
55162
+ else if (process.env.PIE_VERBOSE) {
55146
55163
  console.error(`[${extension.path}] ${message}`);
55147
55164
  }
55148
55165
  },
@@ -55364,7 +55381,7 @@ function normalizeExtensionImportPath(extensionPath) {
55364
55381
  }
55365
55382
  return extensionPath;
55366
55383
  }
55367
- async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, capabilities, actions, discovered) {
55384
+ async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, capabilities, actions, discovered, logSink) {
55368
55385
  const resolvedPath = resolvePath(extensionPath, cwd);
55369
55386
  if (!fs9.existsSync(resolvedPath)) {
55370
55387
  return { extension: null, error: `Extension not found: ${extensionPath}` };
@@ -55378,7 +55395,7 @@ async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, c
55378
55395
  };
55379
55396
  }
55380
55397
  const extension = createExtension(extensionPath, resolvedPath, discovered?.identity, discovered?.source);
55381
- const ctx = createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, capabilities, actions);
55398
+ const ctx = createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, capabilities, actions, logSink);
55382
55399
  try {
55383
55400
  await factory(ctx);
55384
55401
  } catch (error) {
@@ -55534,7 +55551,7 @@ function discoverAllExtensions(configuredPaths, cwd, options) {
55534
55551
  enabled: item.identity ? isExtensionEnabled(item.identity, ...layers, manifestDefaultLayer(item.defaultEnablement)) : true
55535
55552
  }));
55536
55553
  }
55537
- async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn, capabilities = interactiveHostCapabilities(), actions, options) {
55554
+ async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn, capabilities = interactiveHostCapabilities(), actions, options, logSink) {
55538
55555
  const extensions = [];
55539
55556
  const errors = [];
55540
55557
  const seenResolvedPaths = /* @__PURE__ */ new Set();
@@ -55591,7 +55608,8 @@ async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn
55591
55608
  isIdleFn,
55592
55609
  capabilities,
55593
55610
  actions,
55594
- discoveredByPath.get(extPath)
55611
+ discoveredByPath.get(extPath),
55612
+ logSink
55595
55613
  );
55596
55614
  if (error) {
55597
55615
  errors.push({ path: extPath, error });
@@ -63590,6 +63608,10 @@ var ExtensionRunner = class {
63590
63608
  }
63591
63609
  contextActions;
63592
63610
  capabilities;
63611
+ /** Optional diagnostic sink for ctx.log (r2-dogfood): json-events hosts
63612
+ * wire this to a stdout event so extension logs are observable in
63613
+ * production (detached workers have no terminal for stderr). */
63614
+ logSink;
63593
63615
  /** Unregister handles created through this runner, revoked on reload/teardown. */
63594
63616
  unregisterHandles = [];
63595
63617
  disposal;
@@ -63628,6 +63650,12 @@ var ExtensionRunner = class {
63628
63650
  setUIContext(uiContext) {
63629
63651
  this.uiContext = uiContext;
63630
63652
  }
63653
+ /** r2-dogfood: install a diagnostic sink for ctx.log (json-events hosts
63654
+ * route it to a stdout event so detached-worker extension logs are
63655
+ * observable in production). */
63656
+ setLogSink(sink) {
63657
+ this.logSink = sink;
63658
+ }
63631
63659
  /**
63632
63660
  * Wrap an unregister handle so this runner can revoke it during
63633
63661
  * reload/teardown even if the extension drops the handle it was returned.
@@ -63726,7 +63754,8 @@ var ExtensionRunner = class {
63726
63754
  hasUI: this.capabilities.interactiveUI,
63727
63755
  cwd: this.actions.cwd,
63728
63756
  log: (message) => {
63729
- if (process.env.PIE_VERBOSE) {
63757
+ if (this.logSink) this.logSink(message);
63758
+ else if (process.env.PIE_VERBOSE) {
63730
63759
  console.error(`[Extension] ${message}`);
63731
63760
  }
63732
63761
  },
@@ -64258,9 +64287,14 @@ function getSavedSessionModelSelection(activeSession) {
64258
64287
  const thinkingLevel = typeof activeSession.metadata.thinkingLevel === "string" ? activeSession.metadata.thinkingLevel : void 0;
64259
64288
  return { provider, modelId, thinkingLevel };
64260
64289
  }
64261
- function syncSessionModelMetadata(sessionManager, model, thinkingLevel) {
64290
+ function syncSessionModelMetadata(sessionManager, model, thinkingLevel, options) {
64262
64291
  const activeSession = sessionManager.getActiveSession();
64263
64292
  if (!activeSession || !model) return;
64293
+ if (options?.isFallback) {
64294
+ activeSession.metadata.thinkingLevel = thinkingLevel;
64295
+ activeSession.isDirty = true;
64296
+ return;
64297
+ }
64264
64298
  activeSession.metadata.provider = model.provider;
64265
64299
  activeSession.metadata.modelId = model.id;
64266
64300
  activeSession.metadata.defaultProvider = model.provider;
@@ -64381,6 +64415,7 @@ function restoreInteractiveSessionState(options) {
64381
64415
  }
64382
64416
 
64383
64417
  // src/keybindings.ts
64418
+ init_config();
64384
64419
  import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
64385
64420
  import { join as join7 } from "path";
64386
64421
  var DEFAULT_APP_KEYBINDINGS = {
@@ -65146,6 +65181,7 @@ var TypeCompiler;
65146
65181
  // src/theme/theme.ts
65147
65182
  var import_chalk = __toESM(require_source(), 1);
65148
65183
  var import_cli_highlight = __toESM(require_dist(), 1);
65184
+ init_config();
65149
65185
  var ColorValueSchema = Type.Union([
65150
65186
  Type.String(),
65151
65187
  // hex "#ff0000", var ref "primary", or empty ""
@@ -72595,11 +72631,19 @@ async function loadSession(host, sessionId) {
72595
72631
  return;
72596
72632
  }
72597
72633
  try {
72634
+ const claim = claimSessionOwnership(sessionId, process.env.PIE_IPC_DISPLAY_NAME || `tui-pid-${process.pid}`);
72635
+ if ("holder" in claim) {
72636
+ host.showError(`\u4F1A\u8BDD\u88AB\u5360\u7528\uFF08pid ${claim.holder.pid} ${claim.holder.holder}\uFF09\u2014\u2014\u540C\u4E00\u4F1A\u8BDD\u4E0D\u5141\u8BB8\u4E24\u4E2A\u6D3B\u8DC3\u5199\u5165\u8005`);
72637
+ return;
72638
+ }
72598
72639
  const success = await host.sessionManager.loadSession(sessionId);
72599
72640
  if (!success) {
72641
+ claim.handle.release();
72600
72642
  host.showError(`Session not found: ${sessionId}`);
72601
72643
  return;
72602
72644
  }
72645
+ host.releaseSessionOwnership?.();
72646
+ host.setSessionOwnershipHandle?.(claim.handle);
72603
72647
  setControllerBusy(host, false);
72604
72648
  setWaitingForUser(host, false);
72605
72649
  await host.initializeFileManager();
@@ -73540,6 +73584,9 @@ function shutdownInteractiveHost(host, idleTimeoutMs = 5e3) {
73540
73584
  () => host.abortAgent(),
73541
73585
  () => host.agentSessionController?.dispose(),
73542
73586
  () => host.fileStatusMonitor?.stop(),
73587
+ // r3-P1: release the session write-ownership claim on shutdown so the
73588
+ // next host claims immediately instead of waiting out staleness.
73589
+ () => host.releaseSessionOwnership?.(),
73543
73590
  () => host.ui.stop()
73544
73591
  ]) {
73545
73592
  try {
@@ -74442,6 +74489,9 @@ async function handleSubagentCommand(host, args) {
74442
74489
  }
74443
74490
  }
74444
74491
 
74492
+ // src/commands/interactive-skill-commands.ts
74493
+ init_config();
74494
+
74445
74495
  // src/components/extension-input.ts
74446
74496
  var ExtensionInputComponent = class extends Container {
74447
74497
  input;
@@ -76377,7 +76427,9 @@ async function handleClearCommand(host) {
76377
76427
  host.executionState.clear();
76378
76428
  host.executionReminder = null;
76379
76429
  host.agent.reset();
76430
+ host.releaseSessionOwnership?.();
76380
76431
  await host.sessionManager.createSession();
76432
+ host.claimSessionOwnershipFor?.(host.sessionManager.getActiveSessionId() ?? "");
76381
76433
  const activeSession = host.sessionManager.getActiveSession();
76382
76434
  if (activeSession) {
76383
76435
  host.agent.sessionId = activeSession.id;
@@ -81276,6 +81328,7 @@ function scheduleContinuationTimeout(host) {
81276
81328
  }
81277
81329
 
81278
81330
  // src/runtime/interactive-controller-setup.ts
81331
+ init_config();
81279
81332
  async function prepareAgentTurn(host, context) {
81280
81333
  let messages = context.messages;
81281
81334
  if (context.source === "interactive" && context.streamingBehavior && host.tryBuildAttachmentContentFromExtensions) {
@@ -82765,6 +82818,7 @@ async function loadInteractiveExtensions(host) {
82765
82818
 
82766
82819
  // src/extensions/interactive-runtime-reload.ts
82767
82820
  import { AsyncLocalStorage } from "async_hooks";
82821
+ init_config();
82768
82822
  import * as os8 from "os";
82769
82823
  import * as path30 from "path";
82770
82824
  var runtimeReloadContext = new AsyncLocalStorage();
@@ -83187,7 +83241,7 @@ var InteractiveMode = class {
83187
83241
  async init() {
83188
83242
  const activeSession = this.sessionManager.getActiveSession();
83189
83243
  this.thinkingLevel = resolveInitialThinkingLevel({ session: activeSession, settingsManager: this.options.settingsManager });
83190
- const { Agent } = await import("./chunks/src-46R5ZFOU.js");
83244
+ const { Agent } = await import("./chunks/src-OVWRBWKU.js");
83191
83245
  this.agent = new Agent({
83192
83246
  initialState: {
83193
83247
  systemPrompt: this.buildSystemPrompt(),
@@ -83230,7 +83284,7 @@ var InteractiveMode = class {
83230
83284
  this.setupAutocomplete();
83231
83285
  this.registerExtensionShortcuts();
83232
83286
  await this.initializeFileManager();
83233
- this.syncSessionModelMetadata();
83287
+ if (!this.options.sessionModelFallback) this.syncSessionModelMetadata();
83234
83288
  if (!this.hasConfiguredModel()) {
83235
83289
  showMissingModelConfigurationNotice(this.filePipelineHost);
83236
83290
  }
@@ -83446,6 +83500,33 @@ var InteractiveMode = class {
83446
83500
  async loadSession(sessionId) {
83447
83501
  return loadSession(this, sessionId);
83448
83502
  }
83503
+ /** 4.4.1 session write ownership: the TUI holds at most one claim (the
83504
+ * active resumed session); switching releases the previous one.
83505
+ * adoptSessionOwnership transfers a STARTUP composition claim into this
83506
+ * same lifecycle (r3-P1) so switch-away/shutdown releases it too. */
83507
+ sessionOwnershipHandle;
83508
+ adoptedRelease;
83509
+ adoptSessionOwnership(releaseFn) {
83510
+ this.adoptedRelease = releaseFn;
83511
+ }
83512
+ setSessionOwnershipHandle(handle) {
83513
+ this.adoptedRelease?.();
83514
+ this.adoptedRelease = void 0;
83515
+ this.sessionOwnershipHandle = handle;
83516
+ }
83517
+ releaseSessionOwnership() {
83518
+ this.adoptedRelease?.();
83519
+ this.adoptedRelease = void 0;
83520
+ this.sessionOwnershipHandle?.release();
83521
+ this.sessionOwnershipHandle = void 0;
83522
+ }
83523
+ /** r2-review: /clear creates a fresh active session — claim it under the
83524
+ * same single-writer lifecycle. */
83525
+ claimSessionOwnershipFor(sessionId) {
83526
+ if (!sessionId) return;
83527
+ const claim = claimSessionOwnership(sessionId, process.env.PIE_IPC_DISPLAY_NAME || `tui-pid-${process.pid}`);
83528
+ if ("handle" in claim) this.sessionOwnershipHandle = claim.handle;
83529
+ }
83449
83530
  updateTerminalTitle() {
83450
83531
  return updateTerminalTitle(this);
83451
83532
  }
@@ -83659,6 +83740,7 @@ function applyManagerServiceBootstrapEnv() {
83659
83740
  // src/app/runtime-composition.ts
83660
83741
  import { randomUUID as randomUUID2 } from "crypto";
83661
83742
  import * as path32 from "path";
83743
+ init_config();
83662
83744
  var CliMissingApiKeyError = class extends Error {
83663
83745
  constructor(message) {
83664
83746
  super(message);
@@ -83666,7 +83748,7 @@ var CliMissingApiKeyError = class extends Error {
83666
83748
  }
83667
83749
  };
83668
83750
  var CliSessionResumeError = class extends Error {
83669
- constructor(sessionId, code, message = code === "session_not_found" ? `Session not found: ${sessionId}` : `Session could not be recovered: ${sessionId}`) {
83751
+ constructor(sessionId, code, message = code === "session_not_found" ? `Session not found: ${sessionId}` : code === "session_busy" ? `Session is owned by another live host: ${sessionId} (close it first, or wait \u2014 a crashed holder's lock goes stale in 20s)` : `Session could not be recovered: ${sessionId}`) {
83670
83752
  super(message);
83671
83753
  this.sessionId = sessionId;
83672
83754
  this.code = code;
@@ -83746,15 +83828,25 @@ async function composeCliRuntime(params) {
83746
83828
  const cwd = params.cwd ?? process.cwd();
83747
83829
  const sessionManager = createSessionManager({ sessionsDir: paths.sessionsDir });
83748
83830
  let createdNewSession = false;
83831
+ let sessionOwnership;
83832
+ let restoredViaFallback = false;
83749
83833
  if (params.explicitSessionId) {
83750
83834
  const ref = settingsManager.getManagerScopedModelRef();
83751
83835
  const managerScopedSelection = !!ref && !!model && model.id === ref.modelId && normalizeProviderName(model.provider) === normalizeProviderName(ref.provider);
83752
83836
  const sessionFileExists = params.requireExistingSession ? await sessionManager.hasSession(params.explicitSessionId) : false;
83837
+ const claim = claimSessionOwnership(params.explicitSessionId, process.env.PIE_IPC_DISPLAY_NAME || `pid-${process.pid}`);
83838
+ if ("holder" in claim) {
83839
+ if (params.requireExistingSession) {
83840
+ throw new CliSessionResumeError(params.explicitSessionId, "session_busy");
83841
+ }
83842
+ throw new CliSessionResumeError(params.explicitSessionId, "session_busy");
83843
+ }
83753
83844
  const loaded = await sessionManager.loadSession(params.explicitSessionId, {
83754
83845
  warnIfMissing: params.warnIfExplicitSessionMissing
83755
83846
  });
83756
83847
  if (!loaded) {
83757
83848
  if (params.requireExistingSession) {
83849
+ claim.handle.release();
83758
83850
  throw new CliSessionResumeError(
83759
83851
  params.explicitSessionId,
83760
83852
  sessionFileExists ? "session_unrecoverable" : "session_not_found"
@@ -83762,13 +83854,16 @@ async function composeCliRuntime(params) {
83762
83854
  }
83763
83855
  await sessionManager.createSession(void 0, void 0, params.explicitSessionId);
83764
83856
  createdNewSession = true;
83765
- } else {
83857
+ }
83858
+ {
83859
+ sessionOwnership = claim.handle;
83766
83860
  const restored = restoreSessionModelState({
83767
83861
  activeSession: sessionManager.getActiveSession(),
83768
83862
  registry: modelRegistry,
83769
83863
  currentModel: model,
83770
83864
  managerScopedSelection
83771
83865
  });
83866
+ restoredViaFallback = Boolean(restored.fallbackMessage);
83772
83867
  if (restored.model) {
83773
83868
  model = restored.model;
83774
83869
  provider = restored.model.provider;
@@ -83783,9 +83878,14 @@ async function composeCliRuntime(params) {
83783
83878
  } else {
83784
83879
  await sessionManager.createSession();
83785
83880
  createdNewSession = true;
83881
+ const created = sessionManager.getActiveSessionId();
83882
+ if (created) {
83883
+ const claimNew = claimSessionOwnership(created, process.env.PIE_IPC_DISPLAY_NAME || `pid-${process.pid}`);
83884
+ if ("handle" in claimNew) sessionOwnership = claimNew.handle;
83885
+ }
83786
83886
  }
83787
83887
  const activeSession = sessionManager.getActiveSession();
83788
- syncSessionModelMetadata(sessionManager, model, resolveInitialThinkingLevel({ session: activeSession, settingsManager }));
83888
+ syncSessionModelMetadata(sessionManager, model, resolveInitialThinkingLevel({ session: activeSession, settingsManager }), { isFallback: restoredViaFallback });
83789
83889
  if (activeSession && createdNewSession) {
83790
83890
  activeSession.metadata.cwd = cwd;
83791
83891
  const curatedName = process.env.PIE_PROC_CURATED_NAME?.trim();
@@ -83915,6 +84015,8 @@ async function composeCliRuntime(params) {
83915
84015
  extensionPaths: params.extensionPaths,
83916
84016
  extensionFlags: params.extensionFlags ?? {},
83917
84017
  compositionTrace,
84018
+ // 4.4.1 session write ownership (resume path claims above).
84019
+ releaseSessionOwnership: () => sessionOwnership?.release(),
83918
84020
  createInteractiveOptions() {
83919
84021
  interactiveOptions = {
83920
84022
  model,
@@ -83931,7 +84033,8 @@ async function composeCliRuntime(params) {
83931
84033
  modelRegistry,
83932
84034
  extensionPaths: params.extensionPaths,
83933
84035
  extensionFlags: params.extensionFlags,
83934
- compositionTrace
84036
+ compositionTrace,
84037
+ sessionModelFallback: restoredViaFallback
83935
84038
  };
83936
84039
  return interactiveOptions;
83937
84040
  }
@@ -84123,7 +84226,7 @@ async function runPrintMode(params) {
84123
84226
  `);
84124
84227
  console.log("Assistant: ");
84125
84228
  }
84126
- const { Agent: AgentClass } = await import("./chunks/src-46R5ZFOU.js");
84229
+ const { Agent: AgentClass } = await import("./chunks/src-OVWRBWKU.js");
84127
84230
  let agent;
84128
84231
  const printModeExtensions = await loadPrintModeExtensions({
84129
84232
  cwd: runtime.cwd,
@@ -84324,6 +84427,8 @@ async function runPrintMode(params) {
84324
84427
 
84325
84428
  // src/app/json-events-mode.ts
84326
84429
  import readline from "node:readline";
84430
+ import * as fs29 from "node:fs";
84431
+ init_config();
84327
84432
 
84328
84433
  // src/app/host-idle.ts
84329
84434
  var PENDING_RECOVERY = /* @__PURE__ */ new Set([
@@ -84370,9 +84475,32 @@ process.stdout.on("error", (error) => {
84370
84475
  throw error;
84371
84476
  });
84372
84477
  function writeEvent(event) {
84373
- process.stdout.write(`${JSON.stringify(event)}
84374
- `);
84478
+ const line = `${JSON.stringify(event)}
84479
+ `;
84480
+ if (eventSinkOverride) {
84481
+ eventSinkOverride(line);
84482
+ return;
84483
+ }
84484
+ if (process.stdout.isTTY) {
84485
+ process.stdout.write(line);
84486
+ return;
84487
+ }
84488
+ const buffer = Buffer.from(line, "utf8");
84489
+ let offset = 0;
84490
+ while (offset < buffer.length) {
84491
+ try {
84492
+ offset += fs29.writeSync(1, buffer, offset, buffer.length - offset);
84493
+ } catch (error) {
84494
+ const code = error?.code;
84495
+ if (code === "EAGAIN") {
84496
+ process.stdout.write(buffer.subarray(offset));
84497
+ return;
84498
+ }
84499
+ return;
84500
+ }
84501
+ }
84375
84502
  }
84503
+ var eventSinkOverride;
84376
84504
  function toJsonValue(value, depth = 0, cap = MAX_EVENT_STRING_LENGTH) {
84377
84505
  if (value === null) return null;
84378
84506
  if (typeof value === "string") {
@@ -84767,6 +84895,12 @@ async function loadJsonModeExtensions(params) {
84767
84895
  yoloMode: false
84768
84896
  };
84769
84897
  const isIdleNow = () => hostIsIdle(params.getController());
84898
+ const extensionLogSink = (message) => {
84899
+ writeEvent({
84900
+ type: "extension.log",
84901
+ message: truncateForEvent(message, MAX_EVENT_STRING_LENGTH).value
84902
+ });
84903
+ };
84770
84904
  const { extensions, errors } = await loadExtensions(
84771
84905
  params.runtime.extensionPaths,
84772
84906
  params.runtime.cwd,
@@ -84779,7 +84913,8 @@ async function loadJsonModeExtensions(params) {
84779
84913
  params.runtime.settingsManager,
84780
84914
  params.runtime.extensionFlags,
84781
84915
  params.runtime.cwd
84782
- )
84916
+ ),
84917
+ extensionLogSink
84783
84918
  );
84784
84919
  const runner = new ExtensionRunner(
84785
84920
  extensions,
@@ -84792,6 +84927,12 @@ async function loadJsonModeExtensions(params) {
84792
84927
  );
84793
84928
  runnerCell.current = runner;
84794
84929
  runner.setUIContext(uiContext);
84930
+ runner.setLogSink((message) => {
84931
+ writeEvent({
84932
+ type: "extension.log",
84933
+ message: truncateForEvent(message, MAX_EVENT_STRING_LENGTH).value
84934
+ });
84935
+ });
84795
84936
  if (errors.length) {
84796
84937
  await runner.dispose("shutdown");
84797
84938
  throw new Error(
@@ -85351,7 +85492,7 @@ async function runJsonEventsMode(params) {
85351
85492
  const sideTrace = trace;
85352
85493
  const sideApiKey = runtime.apiKey;
85353
85494
  const snapshot = structuredClone(parent.state.messages);
85354
- const { Agent: AgentClass } = await import("./chunks/src-46R5ZFOU.js");
85495
+ const { Agent: AgentClass } = await import("./chunks/src-OVWRBWKU.js");
85355
85496
  const sideAgent = new AgentClass({
85356
85497
  initialState: {
85357
85498
  systemPrompt: parent.state.systemPrompt,
@@ -85814,6 +85955,7 @@ async function runJsonEventsMode(params) {
85814
85955
  }
85815
85956
  async function disposeRuntime(reason = "runtime_switch") {
85816
85957
  externalTurn = null;
85958
+ runtime?.releaseSessionOwnership?.();
85817
85959
  const runner = extensionRunner;
85818
85960
  extensionRunner = void 0;
85819
85961
  try {
@@ -85857,7 +85999,16 @@ async function runJsonEventsMode(params) {
85857
85999
  timer.unref?.();
85858
86000
  void ensureRuntime().then(resolve8, reject).finally(() => clearTimeout(timer));
85859
86001
  });
85860
- } catch {
86002
+ } catch (error) {
86003
+ if (error instanceof CliSessionResumeError) {
86004
+ writeEvent({
86005
+ type: "turn.failed",
86006
+ sessionId: params.explicitSessionId ?? "",
86007
+ error: `resume-required failed: ${error.message}`,
86008
+ source: "external"
86009
+ });
86010
+ process.exit(1);
86011
+ }
85861
86012
  }
85862
86013
  }
85863
86014
  async function ensureRuntime(requestedCwd) {
@@ -85899,9 +86050,39 @@ async function runJsonEventsMode(params) {
85899
86050
  defaultModelState = configuredDefaultModelState(runtime);
85900
86051
  }
85901
86052
  if (runtime.initialModel.unconfigured || controller) {
86053
+ if (!controller) {
86054
+ const logSink = (message) => {
86055
+ writeEvent({ type: "extension.log", message: truncateForEvent(message, MAX_EVENT_STRING_LENGTH).value });
86056
+ };
86057
+ const caps = params.idle ? residentHostCapabilities() : embeddedHostCapabilities();
86058
+ const { extensions: uncExtensions, errors: uncErrors } = await loadExtensions(
86059
+ runtime.extensionPaths,
86060
+ runtime.cwd,
86061
+ createNoOpExtensionUIContext2(),
86062
+ () => agent?.abort(),
86063
+ () => controller ? hostIsIdle(controller) : true,
86064
+ caps,
86065
+ void 0,
86066
+ void 0,
86067
+ logSink
86068
+ ).catch((e) => {
86069
+ writeEvent({ type: "extension.load_failed", message: String(e?.message ?? e) });
86070
+ return { extensions: [], errors: [] };
86071
+ });
86072
+ for (const { path: path35, error } of uncErrors) writeEvent({ type: "extension.load_failed", message: `${path35}: ${error}` });
86073
+ if (uncExtensions.length && !extensionRunner) {
86074
+ const runner = new ExtensionRunner(uncExtensions, { cwd: runtime.cwd }, {
86075
+ isIdle: () => controller ? hostIsIdle(controller) : true,
86076
+ abort: () => agent?.abort()
86077
+ }, caps);
86078
+ runner.setUIContext(createNoOpExtensionUIContext2());
86079
+ runner.setLogSink(logSink);
86080
+ extensionRunner = runner;
86081
+ }
86082
+ }
85902
86083
  return;
85903
86084
  }
85904
- const { Agent: AgentClass } = await import("./chunks/src-46R5ZFOU.js");
86085
+ const { Agent: AgentClass } = await import("./chunks/src-OVWRBWKU.js");
85905
86086
  if (runtimeClosing) return;
85906
86087
  const compositionRegistry = createCliHostEnvelopeRegistry();
85907
86088
  const jsonModeExtensions = await loadJsonModeExtensions({
@@ -86681,19 +86862,19 @@ async function runJsonEventsMode(params) {
86681
86862
  }
86682
86863
 
86683
86864
  // src/developer-instructions.ts
86684
- import * as fs29 from "fs";
86865
+ import * as fs30 from "fs";
86685
86866
  import * as path33 from "path";
86686
86867
  var MAX_DEVELOPER_INSTRUCTIONS_CHARS = 64e3;
86687
86868
  function readTextFileBounded(filePath) {
86688
86869
  const resolved = path33.resolve(filePath);
86689
- const stat2 = fs29.statSync(resolved);
86870
+ const stat2 = fs30.statSync(resolved);
86690
86871
  if (!stat2.isFile()) {
86691
86872
  throw new Error(`Developer instructions file is not a regular file: ${filePath}`);
86692
86873
  }
86693
86874
  if (stat2.size > MAX_DEVELOPER_INSTRUCTIONS_CHARS * 4) {
86694
86875
  throw new Error(`Developer instructions file is too large: ${filePath}`);
86695
86876
  }
86696
- return fs29.readFileSync(resolved, "utf8");
86877
+ return fs30.readFileSync(resolved, "utf8");
86697
86878
  }
86698
86879
  function collectFlagValues(args, flag) {
86699
86880
  const values = [];
@@ -86812,8 +86993,8 @@ var logError = (msg, err) => {
86812
86993
  const logPath = getRuntimeLogPath();
86813
86994
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
86814
86995
  const stack = err instanceof Error ? err.stack || "" : "";
86815
- fs30.mkdirSync(path34.dirname(logPath), { recursive: true });
86816
- fs30.appendFileSync(logPath, `[${timestamp}] ${msg}
86996
+ fs31.mkdirSync(path34.dirname(logPath), { recursive: true });
86997
+ fs31.appendFileSync(logPath, `[${timestamp}] ${msg}
86817
86998
  ${stack}
86818
86999
 
86819
87000
  `);
@@ -86848,7 +87029,7 @@ async function runWithJsonEventsConsoleIsolation(fn) {
86848
87029
  }
86849
87030
  async function createCliTestStreamFnFromEnv() {
86850
87031
  if (!process.env.PIE_TEST_MOCK_STREAM_SEQUENCE) return void 0;
86851
- return (await import("./chunks/test-stream-FC6ZRENI.js")).createTestStreamFnFromSequenceEnv();
87032
+ return (await import("./chunks/test-stream-7YZDGBPO.js")).createTestStreamFnFromSequenceEnv();
86852
87033
  }
86853
87034
  function resolveJsonEventsDetailFlag() {
86854
87035
  for (let index = 0; index < process.argv.length; index += 1) {
@@ -86965,6 +87146,7 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
86965
87146
  const interactiveOptions = runtime.createInteractiveOptions();
86966
87147
  interactiveOptions.streamFn = await createCliTestStreamFnFromEnv();
86967
87148
  const interactive = new InteractiveMode(interactiveOptions);
87149
+ interactive.adoptSessionOwnership?.(() => runtime.releaseSessionOwnership());
86968
87150
  try {
86969
87151
  await interactive.init();
86970
87152
  if (runtime.initialModel.unconfigured && runtime.initialModel.warning) {
@@ -87044,7 +87226,7 @@ async function main() {
87044
87226
  return;
87045
87227
  }
87046
87228
  if (args[0] === STABLE_CLI_COMMANDS.manager) {
87047
- const { runManagerCommand } = await import("./chunks/manager-cli-4Z6RZ7F4.js");
87229
+ const { runManagerCommand } = await import("./chunks/manager-cli-BYCF4RKN.js");
87048
87230
  try {
87049
87231
  await runManagerCommand(args.slice(1));
87050
87232
  } catch (error) {