@cydm/pie 3.0.0 → 4.0.0

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 (31) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +8 -4
  2. package/dist/builtin/extensions/cron/index.js +130 -21
  3. package/dist/builtin/extensions/im-forward/README.md +20 -5
  4. package/dist/builtin/extensions/im-forward/index.js +415 -142
  5. package/dist/builtin/extensions/memory/index.js +71 -20
  6. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  7. package/dist/builtin/extensions/pie-ipc/index.js +269 -30
  8. package/dist/builtin/extensions/pie-proc/README.md +93 -0
  9. package/dist/builtin/extensions/pie-proc/index.js +630 -0
  10. package/dist/builtin/extensions/pie-proc/package.json +11 -0
  11. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  12. package/dist/builtin/extensions/subagent/index.js +5 -5
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +49 -0
  15. package/dist/chunks/{chunk-7FEPQHYX.js → chunk-FDLLNPIE.js} +143 -53
  16. package/dist/chunks/{chunk-3BC5KGDQ.js → chunk-JQRZLVPY.js} +12 -1
  17. package/dist/chunks/{chunk-GH4VW2OT.js → chunk-NCP264ZE.js} +8 -2
  18. package/dist/chunks/{chunk-YRR6C43W.js → chunk-QX6WS73C.js} +1 -1
  19. package/dist/chunks/{chunk-OEQYEYB3.js → chunk-TDKNKNPL.js} +5 -5
  20. package/dist/chunks/{chunk-BUDXV3TR.js → chunk-UOZHQ73X.js} +3 -3
  21. package/dist/chunks/{chunk-3FRKOFSP.js → chunk-WK4N5HT5.js} +32 -22
  22. package/dist/chunks/chunk-X6LBWHK3.js +37 -0
  23. package/dist/chunks/concierge-cli-PIOGXKDR.js +939 -0
  24. package/dist/chunks/{model-registry-LI5THXV4.js → model-registry-YA6U366L.js} +2 -2
  25. package/dist/chunks/{src-AE3OCAE6.js → src-AB7PLORG.js} +6 -4
  26. package/dist/chunks/{src-YG5M2H44.js → src-ODLT57PQ.js} +2 -2
  27. package/dist/chunks/{src-66XSMIAM.js → src-XSLD2IQ2.js} +1 -1
  28. package/dist/chunks/{src-RVTDUSPJ.js → src-ZZZO4HSR.js} +3 -3
  29. package/dist/chunks/{test-stream-JBWXKOQA.js → test-stream-GIUD5JWS.js} +1 -1
  30. package/dist/cli.js +962 -174
  31. package/package.json +105 -105
package/dist/cli.js CHANGED
@@ -1,8 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
3
+ import {
4
+ AuthStorage,
5
+ FileAuthStorageBackend
6
+ } from "./chunks/chunk-6DNYGVZP.js";
3
7
  import {
4
8
  ModelRegistry
5
- } from "./chunks/chunk-YRR6C43W.js";
9
+ } from "./chunks/chunk-QX6WS73C.js";
6
10
  import {
7
11
  distillWorkerLogPath,
8
12
  readDistillWorkerLog,
@@ -10,7 +14,7 @@ import {
10
14
  runDistillWorkerMain,
11
15
  spawnDistillAutoWorker,
12
16
  spawnDistillWorker
13
- } from "./chunks/chunk-OEQYEYB3.js";
17
+ } from "./chunks/chunk-TDKNKNPL.js";
14
18
  import {
15
19
  CLI_RETRY_MAX_RETRIES,
16
20
  classifyCliFailure,
@@ -27,11 +31,7 @@ import {
27
31
  logTransportLifecycle,
28
32
  setYoloGrantListener,
29
33
  truncateHeadTail
30
- } from "./chunks/chunk-BUDXV3TR.js";
31
- import {
32
- AuthStorage,
33
- FileAuthStorageBackend
34
- } from "./chunks/chunk-6DNYGVZP.js";
34
+ } from "./chunks/chunk-UOZHQ73X.js";
35
35
  import {
36
36
  VERSION,
37
37
  getAgentDir,
@@ -76,7 +76,7 @@ import {
76
76
  shouldPreserveExecutionStateForUserText,
77
77
  supersedeExecutionState,
78
78
  todayKey
79
- } from "./chunks/chunk-7FEPQHYX.js";
79
+ } from "./chunks/chunk-FDLLNPIE.js";
80
80
  import {
81
81
  AGENTS_CONTEXT_FILE_NAME,
82
82
  AgentSessionController,
@@ -116,8 +116,8 @@ import {
116
116
  setEnablementInMap,
117
117
  setExtensionEnabledInSettings,
118
118
  verifyPreparedCompactionCommit
119
- } from "./chunks/chunk-3FRKOFSP.js";
120
- import "./chunks/chunk-GH4VW2OT.js";
119
+ } from "./chunks/chunk-WK4N5HT5.js";
120
+ import "./chunks/chunk-NCP264ZE.js";
121
121
  import {
122
122
  Deref,
123
123
  Errors,
@@ -136,7 +136,7 @@ import {
136
136
  setLogger,
137
137
  streamSimple,
138
138
  type_exports
139
- } from "./chunks/chunk-3BC5KGDQ.js";
139
+ } from "./chunks/chunk-JQRZLVPY.js";
140
140
  import {
141
141
  IsArray,
142
142
  IsBigInt,
@@ -51312,7 +51312,7 @@ import * as path33 from "path";
51312
51312
 
51313
51313
  // src/cli-args.ts
51314
51314
  var FLAGS_WITH_VALUES = /* @__PURE__ */ new Set(["--session-id", "--extension-path", "--developer-instructions", "--developer-instructions-file"]);
51315
- var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--raw-output", "--json-output", "--json-events", "--resume-required"]);
51315
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--raw-output", "--json-output", "--json-events", "--resume-required", "--idle"]);
51316
51316
  var HELP_FLAGS = /* @__PURE__ */ new Set(["help", "--help", "-h"]);
51317
51317
  var COMMANDS = /* @__PURE__ */ new Set(["chat", "help"]);
51318
51318
  function parseCliInvocation(args) {
@@ -53912,6 +53912,54 @@ function anchorAgentDirForChild(env) {
53912
53912
  }
53913
53913
  return { ...env, PIE_CODING_AGENT_DIR: path6.resolve(process.cwd(), value) };
53914
53914
  }
53915
+ var LOADER_FLAGS = /* @__PURE__ */ new Set(["--import", "--require", "-r", "--experimental-loader", "--loader"]);
53916
+ var CALLER_FILE_FLAGS = /* @__PURE__ */ new Set(["--developer-instructions-file", "--extension-path"]);
53917
+ function anchorRestartOperands(argv, cwd = process.cwd(), loader = false) {
53918
+ const flags = loader ? LOADER_FLAGS : CALLER_FILE_FLAGS;
53919
+ const anchor = (value) => {
53920
+ if (!value || path6.isAbsolute(value) || /^[a-zA-Z][\w+.-]*:/.test(value) || value.startsWith("\\\\")) return value;
53921
+ if (loader && !/^\.{1,2}[\\/]/.test(value)) return value;
53922
+ return path6.resolve(cwd, value);
53923
+ };
53924
+ const out = [...argv];
53925
+ for (let i = 0; i < out.length; i++) {
53926
+ const arg = out[i];
53927
+ if (arg === "--") break;
53928
+ const equals = arg.indexOf("=");
53929
+ if (equals >= 0 && flags.has(arg.slice(0, equals))) out[i] = `${arg.slice(0, equals + 1)}${anchor(arg.slice(equals + 1))}`;
53930
+ else if (flags.has(arg) && i + 1 < out.length) out[++i] = anchor(out[i]);
53931
+ else if (loader && arg.startsWith("-r") && !arg.startsWith("--") && arg.length > 2) out[i] = `-r${anchor(arg.slice(2))}`;
53932
+ }
53933
+ return out;
53934
+ }
53935
+ function anchorNodeOptions(value, cwd) {
53936
+ const tokens = [];
53937
+ let i = 0;
53938
+ while (i < value.length) {
53939
+ if (/\s/.test(value[i])) {
53940
+ i++;
53941
+ continue;
53942
+ }
53943
+ const start = i;
53944
+ let decoded = "", quoted = false;
53945
+ while (i < value.length && (quoted || !/\s/.test(value[i]))) {
53946
+ const ch = value[i++];
53947
+ if (ch === '"') quoted = !quoted;
53948
+ else if (quoted && ch === "\\") {
53949
+ if (i === value.length) return value;
53950
+ decoded += value[i++];
53951
+ } else decoded += ch;
53952
+ }
53953
+ if (quoted) return value;
53954
+ tokens.push({ start, end: i, value: decoded });
53955
+ }
53956
+ const anchored = anchorRestartOperands(tokens.map((token) => token.value), cwd, true);
53957
+ for (let n = tokens.length - 1; n >= 0; n--) {
53958
+ const token = tokens[n];
53959
+ if (anchored[n] !== token.value) value = value.slice(0, token.start) + JSON.stringify(anchored[n]) + value.slice(token.end);
53960
+ }
53961
+ return value;
53962
+ }
53915
53963
  function buildChildEnv(env) {
53916
53964
  const anchored = anchorAgentDirForChild(env);
53917
53965
  const out = {};
@@ -53919,6 +53967,7 @@ function buildChildEnv(env) {
53919
53967
  if (DROPPED_ENV_KEYS.has(key)) continue;
53920
53968
  out[key] = value;
53921
53969
  }
53970
+ if (out.NODE_OPTIONS) out.NODE_OPTIONS = anchorNodeOptions(out.NODE_OPTIONS, process.cwd());
53922
53971
  return out;
53923
53972
  }
53924
53973
  function decideSessionResumeRestart(argv, sessionId, cwd) {
@@ -53948,7 +53997,7 @@ async function performResumeRestart(decision, onSpawnFailure) {
53948
53997
  emitOsc7Cwd(decision.targetCwd);
53949
53998
  };
53950
53999
  return await new Promise((resolve8) => {
53951
- const child = spawn(process.execPath, [...process.execArgv, process.argv[1] ?? ".", ...decision.childArgv], {
54000
+ const child = spawn(process.execPath, [...anchorRestartOperands(process.execArgv, process.cwd(), true), process.argv[1] ?? ".", ...anchorRestartOperands(decision.childArgv)], {
53952
54001
  cwd: decision.targetCwd,
53953
54002
  stdio: "inherit",
53954
54003
  env: buildChildEnv(decision.childEnv),
@@ -54863,6 +54912,17 @@ import * as os2 from "os";
54863
54912
  import * as path8 from "path";
54864
54913
  import { pathToFileURL as pathToFileURL2 } from "node:url";
54865
54914
 
54915
+ // src/extensions/types.ts
54916
+ function interactiveHostCapabilities() {
54917
+ return { interactiveUI: true, editorInjection: true, eventSink: true, longLived: true };
54918
+ }
54919
+ function oneShotHeadlessCapabilities() {
54920
+ return { interactiveUI: false, editorInjection: false, eventSink: false, longLived: false };
54921
+ }
54922
+ function embeddedHostCapabilities() {
54923
+ return { interactiveUI: false, editorInjection: true, eventSink: true, longLived: true };
54924
+ }
54925
+
54866
54926
  // src/command-tree.ts
54867
54927
  var CommandTree = class {
54868
54928
  root = { name: "", description: "Root", children: [], isCategory: true };
@@ -55025,7 +55085,7 @@ var CommandTree = class {
55025
55085
  var commandTree = new CommandTree();
55026
55086
 
55027
55087
  // src/extensions/loader.ts
55028
- function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, hasUI, actions) {
55088
+ function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, capabilities, actions) {
55029
55089
  const context = {
55030
55090
  registerCleanup: (handler) => (extension.resources ??= new ExtensionResourceScope()).register(handler),
55031
55091
  ui: uiContext,
@@ -55033,7 +55093,8 @@ function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, ha
55033
55093
  request: (request) => requestInteraction(request),
55034
55094
  isAvailable: () => hasInteractionHandler()
55035
55095
  },
55036
- hasUI,
55096
+ capabilities,
55097
+ hasUI: capabilities.interactiveUI,
55037
55098
  cwd,
55038
55099
  log: (message) => {
55039
55100
  if (process.env.PIE_VERBOSE) {
@@ -55236,14 +55297,14 @@ async function loadExtensionModule(extensionPath) {
55236
55297
  }
55237
55298
  function normalizeExtensionImportPath(extensionPath) {
55238
55299
  if (/^[a-zA-Z]:[\\/]/.test(extensionPath)) {
55239
- return `file:///${extensionPath.replace(/\\/g, "/")}`;
55300
+ return pathToFileURL2(extensionPath, { windows: true }).href;
55240
55301
  }
55241
55302
  if (path8.isAbsolute(extensionPath)) {
55242
55303
  return pathToFileURL2(extensionPath).href;
55243
55304
  }
55244
55305
  return extensionPath;
55245
55306
  }
55246
- async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, hasUI, actions, discovered) {
55307
+ async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, capabilities, actions, discovered) {
55247
55308
  const resolvedPath = resolvePath(extensionPath, cwd);
55248
55309
  if (!fs9.existsSync(resolvedPath)) {
55249
55310
  return { extension: null, error: `Extension not found: ${extensionPath}` };
@@ -55257,7 +55318,7 @@ async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, h
55257
55318
  };
55258
55319
  }
55259
55320
  const extension = createExtension(extensionPath, resolvedPath, discovered?.identity, discovered?.source);
55260
- const ctx = createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, hasUI, actions);
55321
+ const ctx = createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, capabilities, actions);
55261
55322
  try {
55262
55323
  await factory(ctx);
55263
55324
  } catch (error) {
@@ -55413,7 +55474,7 @@ function discoverAllExtensions(configuredPaths, cwd, options) {
55413
55474
  enabled: item.identity ? isExtensionEnabled(item.identity, ...layers, manifestDefaultLayer(item.defaultEnablement)) : true
55414
55475
  }));
55415
55476
  }
55416
- async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn, hasUI = true, actions, options) {
55477
+ async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn, capabilities = interactiveHostCapabilities(), actions, options) {
55417
55478
  const extensions = [];
55418
55479
  const errors = [];
55419
55480
  const seenResolvedPaths = /* @__PURE__ */ new Set();
@@ -55468,7 +55529,7 @@ async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn
55468
55529
  uiContext,
55469
55530
  abortFn,
55470
55531
  isIdleFn,
55471
- hasUI,
55532
+ capabilities,
55472
55533
  actions,
55473
55534
  discoveredByPath.get(extPath)
55474
55535
  );
@@ -61946,6 +62007,9 @@ var Markdown = class {
61946
62007
  target.push(this.theme.codeBlockBorder("```"));
61947
62008
  break;
61948
62009
  }
62010
+ case "table":
62011
+ appendLines(target, this.renderTable(token, width));
62012
+ break;
61949
62013
  case "hr":
61950
62014
  target.push(this.theme.hr("\u2500".repeat(Math.min(width, 80))));
61951
62015
  break;
@@ -62059,6 +62123,9 @@ var Markdown = class {
62059
62123
  lines.push(fragment.text);
62060
62124
  break;
62061
62125
  case "table":
62126
+ if (isFirstFragment) {
62127
+ lines.push(indent + this.theme.listBullet(bullet));
62128
+ }
62062
62129
  lines.push(indent + fragment.text);
62063
62130
  break;
62064
62131
  default:
@@ -62125,7 +62192,8 @@ var Markdown = class {
62125
62192
  push(this.theme.codeBlockBorder("```"));
62126
62193
  } else if (token.type === "table") {
62127
62194
  if (availableWidth !== void 0) {
62128
- const tableLines = this.renderTable(token, availableWidth);
62195
+ const tableWidth = Math.max(1, availableWidth - " ".repeat(parentDepth).length);
62196
+ const tableLines = this.renderTable(token, tableWidth);
62129
62197
  for (const tableLine of tableLines) {
62130
62198
  if (tableLine !== "") {
62131
62199
  fragments.push({ kind: "table", text: tableLine });
@@ -63364,16 +63432,16 @@ var ExtensionRunner = class {
63364
63432
  uiContext;
63365
63433
  actions;
63366
63434
  contextActions;
63367
- hasUI;
63435
+ capabilities;
63368
63436
  /** Unregister handles created through this runner, revoked on reload/teardown. */
63369
63437
  unregisterHandles = [];
63370
63438
  disposal;
63371
63439
  resources = new ExtensionResourceScope();
63372
- constructor(extensions, actions, contextActions, hasUI = true) {
63440
+ constructor(extensions, actions, contextActions, capabilities = interactiveHostCapabilities()) {
63373
63441
  this.extensions = extensions;
63374
63442
  this.actions = actions;
63375
63443
  this.contextActions = contextActions;
63376
- this.hasUI = hasUI;
63444
+ this.capabilities = capabilities;
63377
63445
  this.uiContext = this.createNoOpUIContext();
63378
63446
  }
63379
63447
  /**
@@ -63394,11 +63462,11 @@ var ExtensionRunner = class {
63394
63462
  };
63395
63463
  }
63396
63464
  /**
63397
- * Set the UI context for interactive mode. Does NOT change hasUI: the
63398
- * constructor's hasUI argument (host-provided: true for interactive, false
63399
- * for print/json-events no-op contexts) is the single source of truth.
63400
- * Flipping it here used to make headless hosts report ctx.hasUI === true
63401
- * while their ui.* methods silently no-op'd.
63465
+ * Set the UI context for interactive mode. Does NOT change capabilities:
63466
+ * the constructor's capabilities argument (host-provided: interactive for
63467
+ * the TUI, one-shot/embedded for print/json-events) is the single source of
63468
+ * truth. Flipping it here used to make headless hosts report ctx.hasUI ===
63469
+ * true while their ui.* methods silently no-op'd.
63402
63470
  */
63403
63471
  setUIContext(uiContext) {
63404
63472
  this.uiContext = uiContext;
@@ -63497,7 +63565,8 @@ var ExtensionRunner = class {
63497
63565
  request: (request) => requestInteraction(request),
63498
63566
  isAvailable: () => hasInteractionHandler()
63499
63567
  },
63500
- hasUI: this.hasUI,
63568
+ capabilities: this.capabilities,
63569
+ hasUI: this.capabilities.interactiveUI,
63501
63570
  cwd: this.actions.cwd,
63502
63571
  log: (message) => {
63503
63572
  if (process.env.PIE_VERBOSE) {
@@ -71095,16 +71164,17 @@ function isCloseFence(line, fence) {
71095
71164
  }
71096
71165
  function isBoundarySafeSplit(nextLine) {
71097
71166
  if (nextLine.trim() === "") return false;
71098
- if (/^(\t| {4})/.test(nextLine)) return false;
71167
+ if (/^(\t| +)/.test(nextLine)) return false;
71099
71168
  if (/^\s*([-*+]|\d{1,9}[.)])\s/.test(nextLine)) return false;
71100
71169
  if (/^\s*</.test(nextLine)) return false;
71101
71170
  return true;
71102
71171
  }
71103
71172
  var RAW_HTML_UNTIL_CLOSED = /* @__PURE__ */ new Set(["script", "pre", "style", "textarea"]);
71104
71173
  function htmlBlockStateAt(line) {
71105
- const comment = /^ {0,3}<!--/.test(line);
71106
- if (comment) {
71107
- return line.includes("-->") ? null : { kind: "comment" };
71174
+ const opener = /^ {0,3}(<!--|<\?|<!\[CDATA\[|<!)/.exec(line);
71175
+ if (opener) {
71176
+ const close = opener[1] === "<!--" ? "-->" : opener[1] === "<?" ? "?>" : opener[1] === "<![CDATA[" ? "]]>" : ">";
71177
+ return line.includes(close) ? null : { kind: "delimiter", close };
71108
71178
  }
71109
71179
  const match = /^ {0,3}<([a-zA-Z][a-zA-Z0-9-]*)/.exec(line);
71110
71180
  if (!match) return null;
@@ -71113,17 +71183,18 @@ function htmlBlockStateAt(line) {
71113
71183
  return new RegExp(`</${tag}\\s*>`).test(line) ? null : { kind: "tag", tag };
71114
71184
  }
71115
71185
  function closesHtmlBlock(line, state) {
71116
- if (state.kind === "comment") return line.includes("-->");
71186
+ if (state.kind === "delimiter") return line.includes(state.close);
71117
71187
  if (state.kind === "tag") {
71118
71188
  return new RegExp(`^ {0,3}</${state.tag}\\s*>?(\\s|$)`).test(line);
71119
71189
  }
71120
71190
  return false;
71121
71191
  }
71122
- function findStablePrefixEnd(text) {
71192
+ function findStablePrefixEnd(text, scanStart) {
71193
+ const rawOffset = scanStart === 0 ? text.length - text.trimStart().length : 0;
71123
71194
  let fence = null;
71124
71195
  let html = null;
71125
- let lastSafe = -1;
71126
- let pos = 0;
71196
+ let lastSafe = scanStart - 1;
71197
+ let pos = scanStart || rawOffset;
71127
71198
  let candidateBlankAt = -1;
71128
71199
  while (pos < text.length) {
71129
71200
  const lineEnd = text.indexOf("\n", pos);
@@ -71159,7 +71230,9 @@ function findStablePrefixEnd(text) {
71159
71230
  }
71160
71231
  pos = next;
71161
71232
  }
71162
- if (lastSafe >= 0 && lastSafe + 1 >= STREAMING_SPLIT_MIN_CHARS) return lastSafe + 1;
71233
+ if (lastSafe >= 0 && lastSafe + 1 >= STREAMING_SPLIT_MIN_CHARS) {
71234
+ return lastSafe + 1;
71235
+ }
71163
71236
  return -1;
71164
71237
  }
71165
71238
  function hasVisibleContentAfter(content, index) {
@@ -71330,25 +71403,27 @@ var AssistantMessageComponent = class extends Container {
71330
71403
  if (lastBlock.type !== "text") return false;
71331
71404
  const fullText = lastBlock.text;
71332
71405
  if (fullText.length < STREAMING_SPLIT_MIN_CHARS) return false;
71333
- const boundary = findStablePrefixEnd(fullText);
71406
+ const chainStillApplies = this.stablePrefixChunks.length > 0 && this.stablePrefixKind === "text" && this.stablePrefix.length > 0 && fullText.startsWith(this.stablePrefix);
71407
+ const scanStart = chainStillApplies ? this.stablePrefix.length : 0;
71408
+ const boundary = findStablePrefixEnd(fullText, scanStart);
71334
71409
  if (boundary < 0) return false;
71335
71410
  const prefix = fullText.slice(0, boundary);
71336
71411
  const tail = fullText.slice(boundary);
71337
71412
  if (!tail.trim()) return false;
71338
- const prefixStillValid = this.stablePrefixChunks.length > 0 && this.stablePrefixKind === "text" && this.stablePrefix.length > 0 && fullText.startsWith(this.stablePrefix) && fullText.length - this.stablePrefix.length <= STREAMING_TAIL_MAX_CHARS;
71413
+ const prefixStillValid = chainStillApplies && fullText.length - scanStart <= STREAMING_TAIL_MAX_CHARS;
71339
71414
  if (prefixStillValid) {
71340
71415
  this.appendFrozenLeadingBlocks(message, lastEditableIndex, hasVisibleContent);
71341
71416
  for (const chunk of this.stablePrefixChunks) {
71342
71417
  this.contentContainer.addChild(chunk);
71343
71418
  }
71344
- const reuseTail = fullText.slice(this.stablePrefix.length).trim();
71345
- if (reuseTail) {
71346
- this.contentContainer.addChild(new Markdown(reuseTail, 1, 0, this.markdownTheme));
71419
+ const reuseTailSource = fullText.slice(this.stablePrefix.length);
71420
+ const reuseTailRaw = reuseTailSource.replace(/^\n+/, "").replace(/\s+$/, "");
71421
+ if (reuseTailRaw.trim()) {
71422
+ this.contentContainer.addChild(new Markdown(reuseTailRaw, 1, 0, this.markdownTheme));
71347
71423
  }
71348
71424
  return true;
71349
71425
  }
71350
71426
  let advanceFrom = 0;
71351
- const chainStillApplies = this.stablePrefixChunks.length > 0 && this.stablePrefixKind === "text" && this.stablePrefix.length > 0 && prefix.startsWith(this.stablePrefix);
71352
71427
  if (chainStillApplies) {
71353
71428
  advanceFrom = this.stablePrefix.length;
71354
71429
  } else {
@@ -71356,7 +71431,7 @@ var AssistantMessageComponent = class extends Container {
71356
71431
  this.stablePrefix = "";
71357
71432
  }
71358
71433
  this.appendFrozenLeadingBlocks(message, lastEditableIndex, hasVisibleContent);
71359
- const newChunkText = prefix.slice(advanceFrom);
71434
+ const newChunkText = advanceFrom === 0 ? prefix.trimStart() : prefix.slice(advanceFrom);
71360
71435
  if (newChunkText) {
71361
71436
  this.stablePrefixChunks.push(new Markdown(newChunkText, 1, 0, this.markdownTheme));
71362
71437
  }
@@ -71365,9 +71440,9 @@ var AssistantMessageComponent = class extends Container {
71365
71440
  for (const chunk of this.stablePrefixChunks) {
71366
71441
  this.contentContainer.addChild(chunk);
71367
71442
  }
71368
- const tailTrimmed = tail.trim();
71369
- if (tailTrimmed) {
71370
- this.contentContainer.addChild(new Markdown(tailTrimmed, 1, 0, this.markdownTheme));
71443
+ const tailRaw = this.stablePrefix.length > 0 ? tail.replace(/^\n+/, "").replace(/\s+$/, "") : tail.trim();
71444
+ if (tailRaw.trim()) {
71445
+ this.contentContainer.addChild(new Markdown(tailRaw, 1, 0, this.markdownTheme));
71371
71446
  }
71372
71447
  return true;
71373
71448
  }
@@ -76212,6 +76287,7 @@ function createExtensionContextForCommands(host) {
76212
76287
  request: (request) => requestInteraction(request),
76213
76288
  isAvailable: () => hasInteractionHandler()
76214
76289
  },
76290
+ capabilities: interactiveHostCapabilities(),
76215
76291
  hasUI: true,
76216
76292
  cwd: process.cwd(),
76217
76293
  log: (msg) => {
@@ -76955,7 +77031,7 @@ async function handleCompactCommand(host) {
76955
77031
  });
76956
77032
  const compactedMessages = host.sessionManager.getMessages();
76957
77033
  host.replaceAgentMessagesAndMarkSynced(compactedMessages);
76958
- host.resetFileObservationState();
77034
+ host.resetFileObservationState("manual /compact");
76959
77035
  host.resetRuntimeModeBlocks?.();
76960
77036
  host.streamingComponent = void 0;
76961
77037
  host.pendingTools.clear();
@@ -81290,7 +81366,7 @@ function createInteractiveAgentSessionController(host) {
81290
81366
  host.footer.setState({ status: "processing", lifecycleEvent: "auto_compact" });
81291
81367
  host.showStatus(event.reason === "overflow" ? "Context overflow detected, compacting..." : "Auto-compacting context...");
81292
81368
  } else if (event.type === "compaction_committed") {
81293
- host.resetFileObservationState();
81369
+ host.resetFileObservationState(`auto compaction (${event.reason})`);
81294
81370
  host.resetRuntimeModeBlocks?.();
81295
81371
  host.sessionTrace.noteRuntimeEvent("compaction_committed", {
81296
81372
  reason: event.reason,
@@ -82171,8 +82247,9 @@ function beginUserInput(host, extensionIsCurrent = () => true) {
82171
82247
  const session = host.sessionManager.getActiveSession();
82172
82248
  const controller = host.agentSessionController;
82173
82249
  const runner = host.extensionRunner;
82174
- const handler = host.attachmentMentionHandler?.();
82175
- if (!session || !controller || !runner || !handler) return void 0;
82250
+ if (!session || !controller || !runner) return void 0;
82251
+ const handlerAtCapture = host.attachmentMentionHandler?.();
82252
+ if (handlerAtCapture === null) return void 0;
82176
82253
  let retired = false;
82177
82254
  let used = false;
82178
82255
  const unsubscribe = controller.subscribe((event) => {
@@ -82182,7 +82259,7 @@ function beginUserInput(host, extensionIsCurrent = () => true) {
82182
82259
  retired = true;
82183
82260
  unsubscribe();
82184
82261
  });
82185
- const isCurrent = () => !retired && host.sessionManager.getActiveSession() === session && host.agentSessionController === controller && host.extensionRunner === runner && host.attachmentMentionHandler?.() === handler && extensionIsCurrent();
82262
+ const isCurrent = () => !retired && host.sessionManager.getActiveSession() === session && host.agentSessionController === controller && host.extensionRunner === runner && host.attachmentMentionHandler?.() === handlerAtCapture && extensionIsCurrent();
82186
82263
  return {
82187
82264
  isCurrent,
82188
82265
  dispose,
@@ -82193,7 +82270,8 @@ function beginUserInput(host, extensionIsCurrent = () => true) {
82193
82270
  const mentions = [];
82194
82271
  for (const file of files) {
82195
82272
  if (!isCurrent()) return false;
82196
- const mention = await handler.prepareLocalFile(file.path, file.displayName, isCurrent);
82273
+ if (!handlerAtCapture) return false;
82274
+ const mention = await handlerAtCapture.prepareLocalFile(file.path, file.displayName, isCurrent);
82197
82275
  if (!mention || !isCurrent()) return false;
82198
82276
  mentions.push(mention.trim());
82199
82277
  }
@@ -82346,7 +82424,7 @@ async function loadInteractiveExtensions(host) {
82346
82424
  host.extensionUIContext,
82347
82425
  () => host.abortAgent(),
82348
82426
  () => !host.isProcessing,
82349
- true,
82427
+ interactiveHostCapabilities(),
82350
82428
  extensionActions,
82351
82429
  buildExtensionLoadOptions(host.options.settingsManager, host.options.extensionFlags)
82352
82430
  );
@@ -82356,7 +82434,7 @@ async function loadInteractiveExtensions(host) {
82356
82434
  extensions,
82357
82435
  extensionActions,
82358
82436
  contextActions,
82359
- true
82437
+ interactiveHostCapabilities()
82360
82438
  );
82361
82439
  host.extensionRunner.setUIContext(host.extensionUIContext);
82362
82440
  await restoreExtensionProviderCredentials(host.options.modelRegistry);
@@ -82723,8 +82801,8 @@ var InteractiveMode = class {
82723
82801
  getPolicyContext: this.getPolicyContext
82724
82802
  };
82725
82803
  }
82726
- resetFileObservationState() {
82727
- this.options.fileObservationState.clear();
82804
+ resetFileObservationState(reason) {
82805
+ this.options.fileObservationState.clear(reason);
82728
82806
  }
82729
82807
  getRuntimeModeState() {
82730
82808
  const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "local";
@@ -82839,7 +82917,7 @@ var InteractiveMode = class {
82839
82917
  async init() {
82840
82918
  const activeSession = this.sessionManager.getActiveSession();
82841
82919
  this.thinkingLevel = resolveInitialThinkingLevel({ session: activeSession, settingsManager: this.options.settingsManager });
82842
- const { Agent } = await import("./chunks/src-YG5M2H44.js");
82920
+ const { Agent } = await import("./chunks/src-ODLT57PQ.js");
82843
82921
  this.agent = new Agent({
82844
82922
  initialState: {
82845
82923
  systemPrompt: this.buildSystemPrompt(),
@@ -83697,7 +83775,7 @@ async function loadPrintModeExtensions(params) {
83697
83775
  uiContext,
83698
83776
  () => params.getAgent()?.abort(),
83699
83777
  () => true,
83700
- false,
83778
+ oneShotHeadlessCapabilities(),
83701
83779
  actions,
83702
83780
  buildExtensionLoadOptions(params.settingsManager, params.extensionFlags, params.cwd)
83703
83781
  );
@@ -83708,7 +83786,7 @@ async function loadPrintModeExtensions(params) {
83708
83786
  isIdle: () => true,
83709
83787
  abort: () => params.getAgent()?.abort()
83710
83788
  },
83711
- false
83789
+ oneShotHeadlessCapabilities()
83712
83790
  );
83713
83791
  runner.setUIContext(uiContext);
83714
83792
  await restoreExtensionProviderCredentials(params.modelRegistry);
@@ -83737,7 +83815,7 @@ async function runPrintMode(params) {
83737
83815
  `);
83738
83816
  console.log("Assistant: ");
83739
83817
  }
83740
- const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
83818
+ const { Agent: AgentClass } = await import("./chunks/src-ODLT57PQ.js");
83741
83819
  let agent;
83742
83820
  const printModeExtensions = await loadPrintModeExtensions({
83743
83821
  cwd: runtime.cwd,
@@ -83847,7 +83925,7 @@ async function runPrintMode(params) {
83847
83925
  } else if (event.type === "auto_compaction_start") {
83848
83926
  console.error(event.reason === "overflow" ? "Context overflow detected, compacting..." : "Auto-compacting context...");
83849
83927
  } else if (event.type === "compaction_committed") {
83850
- runtime.fileObservationState.clear();
83928
+ runtime.fileObservationState.clear(`auto compaction (${event.reason})`);
83851
83929
  } else {
83852
83930
  reportRetryStatus(event);
83853
83931
  }
@@ -83947,7 +84025,16 @@ var FULL_DETAIL = "full";
83947
84025
  var COMPACT_DETAIL = "compact";
83948
84026
  function createNoOpExtensionUIContext2() {
83949
84027
  return {
83950
- notify: () => {
84028
+ // Embedded eventSink: notifications surface as stdout events for the
84029
+ // GUI host (toasts, logs); they never render anywhere inside pie. The
84030
+ // dialog methods stay no-op — capabilities.interactiveUI is false and
84031
+ // extensions must gate dialogs on that axis.
84032
+ notify: (message, type) => {
84033
+ writeEvent({
84034
+ type: "ui.notification",
84035
+ message: truncateForEvent(message, MAX_EVENT_STRING_LENGTH).value,
84036
+ ...type ? { level: type } : {}
84037
+ });
83951
84038
  },
83952
84039
  select: async () => void 0,
83953
84040
  confirm: async () => false,
@@ -83956,6 +84043,10 @@ function createNoOpExtensionUIContext2() {
83956
84043
  custom: async () => void 0
83957
84044
  };
83958
84045
  }
84046
+ process.stdout.on("error", (error) => {
84047
+ if (error.code === "EPIPE") return;
84048
+ throw error;
84049
+ });
83959
84050
  function writeEvent(event) {
83960
84051
  process.stdout.write(`${JSON.stringify(event)}
83961
84052
  `);
@@ -83965,7 +84056,8 @@ function toJsonValue(value, depth = 0, cap = MAX_EVENT_STRING_LENGTH) {
83965
84056
  if (typeof value === "string") {
83966
84057
  return value.length > cap ? value.slice(0, cap) : value;
83967
84058
  }
83968
- if (typeof value === "number") return Number.isFinite(value) ? value : String(value);
84059
+ if (typeof value === "number")
84060
+ return Number.isFinite(value) ? value : String(value);
83969
84061
  if (typeof value === "boolean") return value;
83970
84062
  if (typeof value === "bigint") return value.toString();
83971
84063
  if (typeof value !== "object") return void 0;
@@ -83974,7 +84066,10 @@ function toJsonValue(value, depth = 0, cap = MAX_EVENT_STRING_LENGTH) {
83974
84066
  return value.slice(0, MAX_EVENT_ARRAY_ITEMS).map((item) => toJsonValue(item, depth + 1, cap) ?? null);
83975
84067
  }
83976
84068
  const result = {};
83977
- for (const [key, item] of Object.entries(value).slice(0, MAX_EVENT_OBJECT_KEYS)) {
84069
+ for (const [key, item] of Object.entries(value).slice(
84070
+ 0,
84071
+ MAX_EVENT_OBJECT_KEYS
84072
+ )) {
83978
84073
  result[key] = toJsonValue(item, depth + 1, cap);
83979
84074
  }
83980
84075
  return result;
@@ -83986,7 +84081,11 @@ function truncateForEvent(text, cap) {
83986
84081
  if (text.length <= cap) {
83987
84082
  return { value: text, truncated: false, fullLength: text.length };
83988
84083
  }
83989
- return { value: text.slice(0, cap), truncated: true, fullLength: text.length };
84084
+ return {
84085
+ value: text.slice(0, cap),
84086
+ truncated: true,
84087
+ fullLength: text.length
84088
+ };
83990
84089
  }
83991
84090
  function hasOversizedValue(value, cap, depth = 0) {
83992
84091
  if (typeof value === "string") return value.length > cap;
@@ -84007,7 +84106,10 @@ function parseInput(line) {
84007
84106
  }
84008
84107
  if (!isRecord3(parsed) || typeof parsed.type !== "string") return null;
84009
84108
  if (parsed.type === "shutdown") {
84010
- return { type: "shutdown", reason: typeof parsed.reason === "string" ? parsed.reason : void 0 };
84109
+ return {
84110
+ type: "shutdown",
84111
+ reason: typeof parsed.reason === "string" ? parsed.reason : void 0
84112
+ };
84011
84113
  }
84012
84114
  if (parsed.type === "turn.interrupt") {
84013
84115
  return {
@@ -84089,7 +84191,8 @@ function assistantErrorFromAgent(agent) {
84089
84191
  const messages = agent?.state.messages ?? [];
84090
84192
  const lastMessage = messages[messages.length - 1];
84091
84193
  if (lastMessage?.role !== "assistant") return "";
84092
- if (lastMessage.stopReason !== "error" && lastMessage.stopReason !== "aborted") return "";
84194
+ if (lastMessage.stopReason !== "error" && lastMessage.stopReason !== "aborted")
84195
+ return "";
84093
84196
  return lastMessage.errorMessage || "assistant response failed";
84094
84197
  }
84095
84198
  function readProgressText(value) {
@@ -84101,7 +84204,9 @@ function extractJsonEventsToolProgressText(partialResult) {
84101
84204
  if (!isRecord3(partialResult)) return "";
84102
84205
  const content = partialResult.content;
84103
84206
  if (Array.isArray(content)) {
84104
- return content.map((block) => isRecord3(block) && block.type === "text" ? readProgressText(block.text) : "").filter(Boolean).join("\n").trim();
84207
+ return content.map(
84208
+ (block) => isRecord3(block) && block.type === "text" ? readProgressText(block.text) : ""
84209
+ ).filter(Boolean).join("\n").trim();
84105
84210
  }
84106
84211
  const directText = readProgressText(partialResult.text) || readProgressText(partialResult.message);
84107
84212
  if (directText) return directText.trim();
@@ -84111,21 +84216,84 @@ function extractJsonEventsToolProgressText(partialResult) {
84111
84216
  }
84112
84217
  return "";
84113
84218
  }
84219
+ function makeQueueExternalUserInput(context) {
84220
+ return (controller, text) => {
84221
+ if (!context.activeTurn() || context.activeTurn().finalized) {
84222
+ const isNew = !context.claimExternalTurn.hasOpenFrame?.();
84223
+ const claimed = context.claimExternalTurn();
84224
+ if (isNew) {
84225
+ writeEvent({
84226
+ type: "turn.started",
84227
+ sessionId: context.sessionId,
84228
+ turnId: claimed.turnId,
84229
+ source: "external"
84230
+ });
84231
+ }
84232
+ }
84233
+ void controller.prompt(
84234
+ {
84235
+ role: "user",
84236
+ content: [{ type: "text", text }],
84237
+ timestamp: Date.now()
84238
+ },
84239
+ {
84240
+ source: "interactive",
84241
+ streamingBehavior: "followUp",
84242
+ displayText: text,
84243
+ clearEditor: false,
84244
+ deliverWhileStreaming: false
84245
+ }
84246
+ ).then(void 0, () => {
84247
+ });
84248
+ };
84249
+ }
84114
84250
  async function loadJsonModeExtensions(params) {
84115
84251
  const uiContext = createNoOpExtensionUIContext2();
84116
84252
  const executionState = new ExecutionStateManager();
84117
84253
  const activeSession = params.runtime.sessionManager.getActiveSession();
84118
84254
  executionState.restoreFromMetadata(activeSession?.metadata?.executionState);
84119
84255
  let availableTools = [...params.runtime.allTools];
84256
+ const runnerCell = {
84257
+ current: void 0
84258
+ };
84259
+ const runnerRef = {
84260
+ trackUnregisterHandle: (unregister) => runnerCell.current.trackUnregisterHandle(unregister),
84261
+ emitTerminalInput: (event) => runnerCell.current.emitTerminalInput(event)
84262
+ };
84120
84263
  const actions = {
84121
84264
  setActiveTools: (toolNames) => {
84122
84265
  const agent = params.getAgent();
84123
84266
  if (!agent) return;
84124
84267
  const toolList = availableTools.length > 0 ? availableTools : agent.state.tools;
84125
- agent.state.tools = toolList.filter((tool) => toolNames.includes(tool.name));
84268
+ agent.state.tools = toolList.filter(
84269
+ (tool) => toolNames.includes(tool.name)
84270
+ );
84126
84271
  },
84127
84272
  getActiveTools: () => params.getAgent()?.state.tools.map((tool) => tool.name) ?? [],
84128
- sendUserMessage: () => {
84273
+ // Embedded eventSink (layer 2 of the IPC-notify plan): out-of-band
84274
+ // extension output becomes a stdout event. sendUserMessage is a REAL
84275
+ // intake on this host now (S1: runtime owns scheduling — the GUI is a
84276
+ // projection, not the scheduler): the content is queued as a follow-up
84277
+ // turn through the same controller queue stdin turns use, AND the
84278
+ // user.message event still fires so an attached front end can render it.
84279
+ sendUserMessage: (content) => {
84280
+ writeEvent({
84281
+ type: "user.message",
84282
+ sessionId: params.runtime.sessionManager.getActiveSession()?.metadata.id,
84283
+ text: truncateForEvent(content, MAX_EVENT_STRING_LENGTH).value,
84284
+ truncated: content.length > MAX_EVENT_STRING_LENGTH,
84285
+ fullLength: content.length
84286
+ });
84287
+ const controller = params.getController();
84288
+ if (!controller) {
84289
+ void params.ensureRuntimeReady().then((ready) => {
84290
+ const composed = ready ? params.getController() : void 0;
84291
+ if (!composed) return;
84292
+ params.queueExternalInput(composed, content);
84293
+ });
84294
+ return;
84295
+ }
84296
+ params.queueExternalInput(controller, content);
84129
84297
  },
84130
84298
  setPlanMode: () => {
84131
84299
  },
@@ -84162,11 +84330,74 @@ async function loadJsonModeExtensions(params) {
84162
84330
  parameters: tool.parameters
84163
84331
  })),
84164
84332
  getRuntimeTools: () => params.getAgent()?.state.tools ?? [],
84333
+ // S1 trusted self-input: the SAME session-bound, one-shot scope contract
84334
+ // im-forward uses on the TUI host, adapted to this host's shape: no
84335
+ // attachment pipeline (file submits fail closed), controller via lazy
84336
+ // getter, composition-on-demand when input precedes the first stdin
84337
+ // turn. The scope runs terminal:input interception and queues through
84338
+ // the controller exactly like an editor submission.
84339
+ // GENERATION FENCING (r2, P1): the deferred scope is captured with THIS
84340
+ // composition's generation; once a new composition lands, its submit
84341
+ // fails closed (no cross-runtime injection into a different cwd).
84342
+ beginUserInput: (isCurrent) => {
84343
+ const capturedGeneration = params.generation;
84344
+ const generationCurrent = () => params.getGeneration() === capturedGeneration;
84345
+ const buildScope = () => {
84346
+ const controller = params.getController();
84347
+ if (!controller) return void 0;
84348
+ return beginUserInput(
84349
+ {
84350
+ agentSessionController: controller,
84351
+ sessionManager: params.runtime.sessionManager,
84352
+ extensionRunner: runnerRef,
84353
+ queueMessage: (text) => params.queueExternalInput(controller, text)
84354
+ },
84355
+ isCurrent
84356
+ );
84357
+ };
84358
+ const immediate = buildScope();
84359
+ if (immediate) return immediate;
84360
+ let settled = false;
84361
+ let deferred;
84362
+ const deferredScope = {
84363
+ isCurrent: () => (deferred?.isCurrent() ?? params.getController() !== void 0) && generationCurrent(),
84364
+ dispose: () => {
84365
+ deferred?.dispose();
84366
+ settled = true;
84367
+ },
84368
+ submit: async (text, files = []) => {
84369
+ if (settled) return false;
84370
+ if (!generationCurrent()) return false;
84371
+ const ready = await params.ensureRuntimeReady();
84372
+ if (settled) return false;
84373
+ if (!generationCurrent()) return false;
84374
+ if (!ready) return false;
84375
+ const scope = deferred ?? (deferred = buildScope());
84376
+ if (!scope) return false;
84377
+ return scope.submit(text, files);
84378
+ }
84379
+ };
84380
+ return deferredScope;
84381
+ },
84165
84382
  resolveModelClass: (modelClass) => params.runtime.modelRegistry.resolveModelClass(modelClass),
84166
84383
  resolveModelRef: (modelRef) => params.runtime.modelRegistry.resolveModelRef(modelRef),
84167
84384
  registerHostEnvelopeProjector: (projector) => registerExternalHostEnvelopeProjector(projector, params.envelopeRegistry),
84168
84385
  getMessages: () => params.getAgent()?.state.messages ?? [],
84169
- getSessionMetadata: () => ({ ...params.runtime.sessionManager.getActiveSession()?.metadata ?? {} }),
84386
+ // r17 P1: session naming on the resident host — im-forward's explicit
84387
+ // addressing escape hatch ("<session name>: text") reads the session
84388
+ // name; without these the json-events host returned undefined and a
84389
+ // cold-started concierge had NO intake route at all (its route table is
84390
+ // empty until the first outbound forward, and --idle closes stdin —
84391
+ // every inbound IM message hit "no route; ignoring" until something
84392
+ // else happened to make the resident speak first).
84393
+ setSessionName: (name) => {
84394
+ const session = params.runtime.sessionManager.getActiveSession();
84395
+ if (session) params.runtime.sessionManager.setSessionName(name);
84396
+ },
84397
+ getSessionName: () => params.runtime.sessionManager.getSessionName(),
84398
+ getSessionMetadata: () => ({
84399
+ ...params.runtime.sessionManager.getActiveSession()?.metadata ?? {}
84400
+ }),
84170
84401
  setSessionMetadata: (key, value) => {
84171
84402
  const session = params.runtime.sessionManager.getActiveSession();
84172
84403
  if (!session) return;
@@ -84181,9 +84412,13 @@ async function loadJsonModeExtensions(params) {
84181
84412
  uiContext,
84182
84413
  () => params.getAgent()?.abort(),
84183
84414
  () => true,
84184
- false,
84415
+ embeddedHostCapabilities(),
84185
84416
  actions,
84186
- buildExtensionLoadOptions(params.runtime.settingsManager, params.runtime.extensionFlags, params.runtime.cwd)
84417
+ buildExtensionLoadOptions(
84418
+ params.runtime.settingsManager,
84419
+ params.runtime.extensionFlags,
84420
+ params.runtime.cwd
84421
+ )
84187
84422
  );
84188
84423
  const runner = new ExtensionRunner(
84189
84424
  extensions,
@@ -84192,12 +84427,15 @@ async function loadJsonModeExtensions(params) {
84192
84427
  isIdle: () => true,
84193
84428
  abort: () => params.getAgent()?.abort()
84194
84429
  },
84195
- false
84430
+ embeddedHostCapabilities()
84196
84431
  );
84432
+ runnerCell.current = runner;
84197
84433
  runner.setUIContext(uiContext);
84198
84434
  if (errors.length) {
84199
84435
  await runner.dispose("shutdown");
84200
- throw new Error(errors.map(({ path: path34, error }) => `${path34}: ${error}`).join("\n"));
84436
+ throw new Error(
84437
+ errors.map(({ path: path34, error }) => `${path34}: ${error}`).join("\n")
84438
+ );
84201
84439
  }
84202
84440
  try {
84203
84441
  await restoreExtensionProviderCredentials(params.runtime.modelRegistry);
@@ -84222,10 +84460,25 @@ async function runJsonEventsMode(params) {
84222
84460
  let agent;
84223
84461
  let controller;
84224
84462
  let disposeAgentSubscription;
84463
+ let disposeAgentRawSubscription;
84225
84464
  let disposeSemanticSubscription;
84226
84465
  let trace;
84227
84466
  let extensionRunner;
84228
84467
  let lastRetryEvent;
84468
+ let recoveryPending = false;
84469
+ let rawBridgeQueue = Promise.resolve();
84470
+ function enqueueBridgeEmission(emission) {
84471
+ const run = async () => {
84472
+ const deadline = new Promise((resolve8) => {
84473
+ const t = setTimeout(resolve8, 1e4);
84474
+ t.unref?.();
84475
+ });
84476
+ await Promise.race([emission().catch(() => void 0), deadline]);
84477
+ };
84478
+ const next = rawBridgeQueue.then(run).catch(() => void 0);
84479
+ rawBridgeQueue = next;
84480
+ return next;
84481
+ }
84229
84482
  let mockActiveEntryId;
84230
84483
  let thinkingLevel = DEFAULT_THINKING_LEVEL;
84231
84484
  let thinkingLevelInitialized = false;
@@ -84234,16 +84487,47 @@ async function runJsonEventsMode(params) {
84234
84487
  let publishRecoveryDone = false;
84235
84488
  const completedSessionControlRequests = /* @__PURE__ */ new Map();
84236
84489
  const completedSidechatRequests = /* @__PURE__ */ new Map();
84490
+ let externalTurn = null;
84491
+ let externalTurnSeq = 0;
84492
+ const claimExternalTurn = Object.assign(
84493
+ () => {
84494
+ if (externalTurn && !externalTurn.finalized) return externalTurn;
84495
+ externalTurnSeq += 1;
84496
+ externalTurn = {
84497
+ turnId: `ext-${externalTurnSeq}`,
84498
+ startedAt: Date.now(),
84499
+ summary: "",
84500
+ lastActivityAt: Date.now(),
84501
+ finalized: false
84502
+ };
84503
+ return externalTurn;
84504
+ },
84505
+ { hasOpenFrame: () => externalTurn !== null && !externalTurn.finalized }
84506
+ );
84507
+ const queueExternalInput = makeQueueExternalUserInput({
84508
+ sessionId,
84509
+ activeTurn: () => activeTurn,
84510
+ claimExternalTurn
84511
+ });
84237
84512
  const ensureRuntimeInFlight = /* @__PURE__ */ new Map();
84238
84513
  let compositionChain = Promise.resolve();
84239
84514
  let runtimeClosing = false;
84515
+ let compositionGeneration = 0;
84240
84516
  let activeSidechat = null;
84241
84517
  let activeSidechatPromise = null;
84242
84518
  let sidechatChainStopped = false;
84243
- const noProgressTimeoutMs = Number(process.env.PIE_JSON_EVENTS_NO_PROGRESS_MS || 6e5);
84244
- const mockResponseDelayMs = Number(process.env.PIE_TEST_MOCK_RESPONSE_DELAY_MS || 0);
84245
- const prewarmTimeoutMs = Number(process.env.PIE_JSON_EVENTS_PREWARM_TIMEOUT_MS || 1e4);
84246
- const sidechatTimeoutMs = Number(process.env.PIE_JSON_EVENTS_SIDECHAT_TIMEOUT_MS || 3e5);
84519
+ const noProgressTimeoutMs = Number(
84520
+ process.env.PIE_JSON_EVENTS_NO_PROGRESS_MS || 6e5
84521
+ );
84522
+ const mockResponseDelayMs = Number(
84523
+ process.env.PIE_TEST_MOCK_RESPONSE_DELAY_MS || 0
84524
+ );
84525
+ const prewarmTimeoutMs = Number(
84526
+ process.env.PIE_JSON_EVENTS_PREWARM_TIMEOUT_MS || 1e4
84527
+ );
84528
+ const sidechatTimeoutMs = Number(
84529
+ process.env.PIE_JSON_EVENTS_SIDECHAT_TIMEOUT_MS || 3e5
84530
+ );
84247
84531
  await prewarmRuntime();
84248
84532
  writeEvent({
84249
84533
  type: "agent.ready",
@@ -84305,7 +84589,15 @@ async function runJsonEventsMode(params) {
84305
84589
  const metadata = {};
84306
84590
  if (existing) {
84307
84591
  for (const [key, value] of Object.entries(existing)) {
84308
- if (["id", "createdAt", "updatedAt", "entryCount", "messageCount", "activeEntryId", "rootEntryId"].includes(key)) {
84592
+ if ([
84593
+ "id",
84594
+ "createdAt",
84595
+ "updatedAt",
84596
+ "entryCount",
84597
+ "messageCount",
84598
+ "activeEntryId",
84599
+ "rootEntryId"
84600
+ ].includes(key)) {
84309
84601
  continue;
84310
84602
  }
84311
84603
  metadata[key] = value;
@@ -84328,13 +84620,23 @@ async function runJsonEventsMode(params) {
84328
84620
  const targetSessionId = message.sessionId ?? sessionId;
84329
84621
  const status = store.headStatus(targetSessionId);
84330
84622
  if (status === "legacy") {
84331
- throw new SessionControlError("session_unsupported_format", `Session uses an unsupported old format: ${targetSessionId}`);
84623
+ throw new SessionControlError(
84624
+ "session_unsupported_format",
84625
+ `Session uses an unsupported old format: ${targetSessionId}`
84626
+ );
84332
84627
  }
84333
84628
  if (status === "corrupt") {
84334
- throw new SessionControlError("session_unrecoverable", `Session could not be recovered: ${targetSessionId}`);
84629
+ throw new SessionControlError(
84630
+ "session_unrecoverable",
84631
+ `Session could not be recovered: ${targetSessionId}`
84632
+ );
84335
84633
  }
84336
84634
  const existing = store.readHead(targetSessionId);
84337
- if (existing) store.createHead(targetSessionId, { name: void 0, createdAt: existing.metadata.createdAt });
84635
+ if (existing)
84636
+ store.createHead(targetSessionId, {
84637
+ name: void 0,
84638
+ createdAt: existing.metadata.createdAt
84639
+ });
84338
84640
  const startedAt = activeTurn?.startedAt ?? Date.now();
84339
84641
  const baseSeq = existing?.committedSeq ?? store.readHead(targetSessionId)?.committedSeq ?? 0;
84340
84642
  const userEntryId = generateEntryId(baseSeq + 1);
@@ -84383,7 +84685,12 @@ async function runJsonEventsMode(params) {
84383
84685
  targetSessionId,
84384
84686
  [userEntry, assistantEntry],
84385
84687
  assistantEntryId,
84386
- persistedMockMetadata(existing?.metadata, assistantEntryId, existing?.metadata.rootEntryId ?? userEntryId, message.cwd)
84688
+ persistedMockMetadata(
84689
+ existing?.metadata,
84690
+ assistantEntryId,
84691
+ existing?.metadata.rootEntryId ?? userEntryId,
84692
+ message.cwd
84693
+ )
84387
84694
  );
84388
84695
  return assistantEntryId;
84389
84696
  }
@@ -84434,13 +84741,26 @@ async function runJsonEventsMode(params) {
84434
84741
  return normalized;
84435
84742
  }
84436
84743
  function requireSessionControlBase(message) {
84437
- const requestedSessionId = requireSessionControlString(message.sessionId, "sessionId");
84438
- const requestId = requireSessionControlString(message.requestId, "requestId");
84744
+ const requestedSessionId = requireSessionControlString(
84745
+ message.sessionId,
84746
+ "sessionId"
84747
+ );
84748
+ const requestId = requireSessionControlString(
84749
+ message.requestId,
84750
+ "requestId"
84751
+ );
84439
84752
  if (requestedSessionId !== sessionId) {
84440
- throw new SessionControlError("session_mismatch", sessionMismatchError(requestedSessionId), false);
84753
+ throw new SessionControlError(
84754
+ "session_mismatch",
84755
+ sessionMismatchError(requestedSessionId),
84756
+ false
84757
+ );
84441
84758
  }
84442
84759
  if (activeTurn && !activeTurn.finalized) {
84443
- throw new SessionControlError("session_busy", `Cannot ${message.type.slice("session.".length)} session while a turn is active`);
84760
+ throw new SessionControlError(
84761
+ "session_busy",
84762
+ `Cannot ${message.type.slice("session.".length)} session while a turn is active`
84763
+ );
84444
84764
  }
84445
84765
  return { sessionId: requestedSessionId, requestId };
84446
84766
  }
@@ -84452,7 +84772,10 @@ async function runJsonEventsMode(params) {
84452
84772
  return entryId;
84453
84773
  }
84454
84774
  function writeSessionControlFailure(message, operation, error) {
84455
- const detail = error instanceof SessionControlError ? error : new SessionControlError("session_io_error", error instanceof Error ? error.message : String(error));
84775
+ const detail = error instanceof SessionControlError ? error : new SessionControlError(
84776
+ "session_io_error",
84777
+ error instanceof Error ? error.message : String(error)
84778
+ );
84456
84779
  writeEvent({
84457
84780
  type: "session.failed",
84458
84781
  sessionId: message.sessionId || sessionId,
@@ -84468,13 +84791,19 @@ async function runJsonEventsMode(params) {
84468
84791
  try {
84469
84792
  await runtime.sessionManager.save();
84470
84793
  } catch (error) {
84471
- throw new SessionControlError("session_io_error", error instanceof Error ? error.message : String(error));
84794
+ throw new SessionControlError(
84795
+ "session_io_error",
84796
+ error instanceof Error ? error.message : String(error)
84797
+ );
84472
84798
  }
84473
84799
  }
84474
84800
  async function syncRuntimeAfterRewind(controlSessionId) {
84475
84801
  if (params.mockResponse !== void 0) return;
84476
- if (runtime?.sessionManager.getActiveSessionId() !== controlSessionId) return;
84477
- const loaded = await runtime.sessionManager.loadSession(controlSessionId, { warnIfMissing: false });
84802
+ if (runtime?.sessionManager.getActiveSessionId() !== controlSessionId)
84803
+ return;
84804
+ const loaded = await runtime.sessionManager.loadSession(controlSessionId, {
84805
+ warnIfMissing: false
84806
+ });
84478
84807
  if (!loaded) {
84479
84808
  const exists = await runtime.sessionManager.hasSession(controlSessionId);
84480
84809
  throw new SessionControlError(
@@ -84518,8 +84847,14 @@ async function runJsonEventsMode(params) {
84518
84847
  async function handleSessionFork(message) {
84519
84848
  try {
84520
84849
  const { sessionId: controlSessionId, requestId } = requireSessionControlBase(message);
84521
- const sourceEntryId = requireSessionControlString(message.fromEntryId, "fromEntryId");
84522
- const targetSessionId = requireSessionControlString(message.targetSessionId, "targetSessionId");
84850
+ const sourceEntryId = requireSessionControlString(
84851
+ message.fromEntryId,
84852
+ "fromEntryId"
84853
+ );
84854
+ const targetSessionId = requireSessionControlString(
84855
+ message.targetSessionId,
84856
+ "targetSessionId"
84857
+ );
84523
84858
  const name = requireSessionControlString(message.name, "name");
84524
84859
  const forkCwd = message.cwd?.trim() || void 0;
84525
84860
  const cached = completedSessionControlRequests.get(requestId);
@@ -84564,7 +84899,11 @@ async function runJsonEventsMode(params) {
84564
84899
  }
84565
84900
  async function handleSidechat(message) {
84566
84901
  if (isSessionMismatch(message)) {
84567
- writeSidechatFailure(message, sessionMismatchError(message.sessionId), "session_mismatch");
84902
+ writeSidechatFailure(
84903
+ message,
84904
+ sessionMismatchError(message.sessionId),
84905
+ "session_mismatch"
84906
+ );
84568
84907
  return;
84569
84908
  }
84570
84909
  const requestId = message.requestId.trim();
@@ -84578,14 +84917,22 @@ async function runJsonEventsMode(params) {
84578
84917
  return;
84579
84918
  }
84580
84919
  if (activeTurn && !activeTurn.finalized) {
84581
- writeSidechatFailure(message, "Cannot run sidechat while a turn is active", "session_busy");
84920
+ writeSidechatFailure(
84921
+ message,
84922
+ "Cannot run sidechat while a turn is active",
84923
+ "session_busy"
84924
+ );
84582
84925
  return;
84583
84926
  }
84584
84927
  const startedAt = Date.now();
84585
84928
  if (params.mockResponse !== void 0) {
84586
84929
  const hostContextFailure = validateIntakeHostContext(message);
84587
84930
  if (hostContextFailure) {
84588
- writeSidechatFailure(message, hostContextFailure.message, hostContextFailure.code);
84931
+ writeSidechatFailure(
84932
+ message,
84933
+ hostContextFailure.message,
84934
+ hostContextFailure.code
84935
+ );
84589
84936
  return;
84590
84937
  }
84591
84938
  writeEvent({ type: "sidechat.started", sessionId, requestId });
@@ -84613,18 +84960,29 @@ async function runJsonEventsMode(params) {
84613
84960
  await ensureRuntime(runtime?.cwd);
84614
84961
  const hostContextFailure = validateIntakeHostContext(message);
84615
84962
  if (hostContextFailure) {
84616
- writeSidechatFailure(message, hostContextFailure.message, hostContextFailure.code);
84963
+ writeSidechatFailure(
84964
+ message,
84965
+ hostContextFailure.message,
84966
+ hostContextFailure.code
84967
+ );
84617
84968
  return;
84618
84969
  }
84619
84970
  if (!agent || !runtime) {
84620
84971
  throw new Error("JSON events runtime was not initialized");
84621
84972
  }
84622
84973
  if (runtime.initialModel.unconfigured) {
84623
- writeSidechatFailure(message, runtime.initialModel.warning || "No models are configured.");
84974
+ writeSidechatFailure(
84975
+ message,
84976
+ runtime.initialModel.warning || "No models are configured."
84977
+ );
84624
84978
  return;
84625
84979
  }
84626
84980
  if (sidechatController.signal.aborted) {
84627
- writeSidechatFailure(message, "sidechat aborted before dispatch", "sidechat_interrupted");
84981
+ writeSidechatFailure(
84982
+ message,
84983
+ "sidechat aborted before dispatch",
84984
+ "sidechat_interrupted"
84985
+ );
84628
84986
  return;
84629
84987
  }
84630
84988
  const parent = agent;
@@ -84632,7 +84990,7 @@ async function runJsonEventsMode(params) {
84632
84990
  const sideTrace = trace;
84633
84991
  const sideApiKey = runtime.apiKey;
84634
84992
  const snapshot = structuredClone(parent.state.messages);
84635
- const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
84993
+ const { Agent: AgentClass } = await import("./chunks/src-ODLT57PQ.js");
84636
84994
  const sideAgent = new AgentClass({
84637
84995
  initialState: {
84638
84996
  systemPrompt: parent.state.systemPrompt,
@@ -84644,17 +85002,25 @@ async function runJsonEventsMode(params) {
84644
85002
  apiKey: sideApiKey,
84645
85003
  // The sidechat snapshot clones the parent's stored history, including
84646
85004
  // persisted hostContext facts; project them like the main agent does.
84647
- transformContext: async (messages) => projectCliHostEnvelopes(messages, (outcome) => sideTrace?.noteRuntimeEvent(
84648
- outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
84649
- outcome.audit
84650
- ), sideRegistry),
85005
+ transformContext: async (messages) => projectCliHostEnvelopes(
85006
+ messages,
85007
+ (outcome) => sideTrace?.noteRuntimeEvent(
85008
+ outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
85009
+ outcome.audit
85010
+ ),
85011
+ sideRegistry
85012
+ ),
84651
85013
  // Same body-free transport timeline as the main agent: a sidechat is
84652
85014
  // an independent Responses request and previously had no record at all
84653
85015
  // when it stalled. `streamSimple` matches the host default when the
84654
85016
  // caller injected no stream function.
84655
85017
  streamFn: createJsonEventsTransportStreamFn(params.streamFn)
84656
85018
  });
84657
- sidechatController.signal.addEventListener("abort", () => sideAgent.abort(), { once: true });
85019
+ sidechatController.signal.addEventListener(
85020
+ "abort",
85021
+ () => sideAgent.abort(),
85022
+ { once: true }
85023
+ );
84658
85024
  const timer = setTimeout(() => {
84659
85025
  if (!abortKind) abortKind = "timeout";
84660
85026
  sidechatController.abort();
@@ -84667,7 +85033,11 @@ async function runJsonEventsMode(params) {
84667
85033
  }
84668
85034
  if (abortKind) {
84669
85035
  const code = abortKind === "timeout" ? "sidechat_timeout" : "sidechat_interrupted";
84670
- writeSidechatFailure(message, sideAgent.state.error || "sidechat aborted", code);
85036
+ writeSidechatFailure(
85037
+ message,
85038
+ sideAgent.state.error || "sidechat aborted",
85039
+ code
85040
+ );
84671
85041
  return;
84672
85042
  }
84673
85043
  const failure = sideAgent.state.error;
@@ -84726,10 +85096,18 @@ async function runJsonEventsMode(params) {
84726
85096
  writeEvent({ type: "turn.failed", ...base, ...failureDetail(detail) });
84727
85097
  break;
84728
85098
  case "cancelled":
84729
- writeEvent({ type: "turn.cancelled", ...base, reason: detail || "interrupted" });
85099
+ writeEvent({
85100
+ type: "turn.cancelled",
85101
+ ...base,
85102
+ reason: detail || "interrupted"
85103
+ });
84730
85104
  break;
84731
85105
  case "stalled":
84732
- writeEvent({ type: "turn.stalled", ...base, reason: detail || "no_progress_timeout" });
85106
+ writeEvent({
85107
+ type: "turn.stalled",
85108
+ ...base,
85109
+ reason: detail || "no_progress_timeout"
85110
+ });
84733
85111
  break;
84734
85112
  }
84735
85113
  }
@@ -84770,20 +85148,29 @@ async function runJsonEventsMode(params) {
84770
85148
  turnId: activeTurn.turnId,
84771
85149
  toolCallId: event.toolCallId,
84772
85150
  name: event.toolName,
84773
- data: toJsonValue({
84774
- args: event.args,
84775
- ...argsOversized ? { truncated: true } : {}
84776
- }, 0, eventStringCap)
85151
+ data: toJsonValue(
85152
+ {
85153
+ args: event.args,
85154
+ ...argsOversized ? { truncated: true } : {}
85155
+ },
85156
+ 0,
85157
+ eventStringCap
85158
+ )
84777
85159
  });
84778
85160
  }
84779
85161
  break;
84780
85162
  case "tool_progressed":
84781
85163
  touch();
84782
85164
  {
84783
- const progressText = extractJsonEventsToolProgressText(event.partialResult);
85165
+ const progressText = extractJsonEventsToolProgressText(
85166
+ event.partialResult
85167
+ );
84784
85168
  if (progressText) {
84785
- display(progressText.endsWith("\n") ? progressText : `${progressText}
84786
- `, { appendToSummary: false });
85169
+ display(
85170
+ progressText.endsWith("\n") ? progressText : `${progressText}
85171
+ `,
85172
+ { appendToSummary: false }
85173
+ );
84787
85174
  }
84788
85175
  }
84789
85176
  break;
@@ -84799,20 +85186,138 @@ async function runJsonEventsMode(params) {
84799
85186
  toolCallId: event.toolCallId,
84800
85187
  name: event.toolName,
84801
85188
  status: event.isError ? "error" : "ok",
84802
- data: toJsonValue({
84803
- resultText: capped?.value,
84804
- isError: event.isError,
84805
- ...capped?.truncated ? { truncated: true, fullLength: capped.fullLength } : {}
84806
- }, 0, eventStringCap)
85189
+ data: toJsonValue(
85190
+ {
85191
+ resultText: capped?.value,
85192
+ isError: event.isError,
85193
+ ...capped?.truncated ? { truncated: true, fullLength: capped.fullLength } : {}
85194
+ },
85195
+ 0,
85196
+ eventStringCap
85197
+ )
84807
85198
  });
84808
85199
  }
84809
85200
  break;
84810
85201
  }
84811
85202
  }
84812
- function handleControllerEvent(event) {
85203
+ async function handleControllerEvent(event) {
84813
85204
  trace?.noteRuntimeEvent(event.type, event);
84814
85205
  if (event.type === "compaction_committed") {
84815
- runtime?.fileObservationState.clear();
85206
+ runtime?.fileObservationState.clear(`auto compaction (${event.reason})`);
85207
+ }
85208
+ if (!activeTurn || activeTurn.finalized) {
85209
+ const external = externalTurn;
85210
+ if (external && !external.finalized) {
85211
+ external.lastActivityAt = Date.now();
85212
+ if (event.type === "turn_recovery_pending" && (event.recovery === "retry" || event.recovery === "compaction")) {
85213
+ recoveryPending = true;
85214
+ if (event.recovery === "retry") {
85215
+ lastRetryEvent = {
85216
+ attempt: event.attempt ?? 0,
85217
+ maxRetries: event.maxRetries ?? CLI_RETRY_MAX_RETRIES,
85218
+ delayMs: event.delayMs,
85219
+ error: event.failure.message
85220
+ };
85221
+ }
85222
+ await enqueueBridgeEmission(
85223
+ () => extensionRunner?.emit({
85224
+ type: "message:end",
85225
+ message: {
85226
+ role: "assistant",
85227
+ content: [{ type: "text", text: "" }],
85228
+ stopReason: "error",
85229
+ errorMessage: event.failure.message
85230
+ }
85231
+ }) ?? Promise.resolve()
85232
+ );
85233
+ return;
85234
+ }
85235
+ if (event.type === "turn_completed") {
85236
+ const text = assistantTextFromMessage(event.message);
85237
+ external.summary = text;
85238
+ recoveryPending = false;
85239
+ const queueHasMore = (controller?.pendingMessageCount ?? 0) > 0;
85240
+ if (queueHasMore) {
85241
+ writeEvent({
85242
+ type: "turn.completed",
85243
+ sessionId,
85244
+ turnId: external.turnId,
85245
+ summary: text,
85246
+ source: "external",
85247
+ continued: true
85248
+ });
85249
+ return;
85250
+ }
85251
+ external.finalized = true;
85252
+ recoveryPending = false;
85253
+ writeEvent({
85254
+ type: "turn.completed",
85255
+ sessionId,
85256
+ turnId: external.turnId,
85257
+ summary: text,
85258
+ source: "external"
85259
+ });
85260
+ writeEvent({
85261
+ type: "turn.settled",
85262
+ sessionId,
85263
+ turnId: external.turnId,
85264
+ source: "external"
85265
+ });
85266
+ await enqueueBridgeEmission(
85267
+ () => extensionRunner?.emit({ type: "turn:completed" }) ?? Promise.resolve()
85268
+ );
85269
+ await runtime?.sessionManager.save().catch(() => void 0);
85270
+ } else if (event.type === "turn_failed_terminal") {
85271
+ external.finalized = true;
85272
+ recoveryPending = false;
85273
+ writeEvent({
85274
+ type: "turn.failed",
85275
+ sessionId,
85276
+ turnId: external.turnId,
85277
+ error: event.failure?.message ?? "external turn failed",
85278
+ source: "external"
85279
+ });
85280
+ writeEvent({
85281
+ type: "turn.settled",
85282
+ sessionId,
85283
+ turnId: external.turnId,
85284
+ source: "external"
85285
+ });
85286
+ const failureCarrier = event.message ?? {
85287
+ role: "assistant",
85288
+ content: [{ type: "text", text: "" }],
85289
+ stopReason: "error",
85290
+ errorMessage: event.failure?.message ?? "external turn failed"
85291
+ };
85292
+ await enqueueBridgeEmission(
85293
+ () => extensionRunner?.emit({
85294
+ type: "turn:failed",
85295
+ turnIndex: 0,
85296
+ message: failureCarrier,
85297
+ toolResults: []
85298
+ }) ?? Promise.resolve()
85299
+ );
85300
+ await runtime?.sessionManager.save().catch(() => void 0);
85301
+ } else if (event.type === "turn_cancelled") {
85302
+ external.finalized = true;
85303
+ recoveryPending = false;
85304
+ writeEvent({
85305
+ type: "turn.settled",
85306
+ sessionId,
85307
+ turnId: external.turnId,
85308
+ source: "external"
85309
+ });
85310
+ await enqueueBridgeEmission(
85311
+ () => extensionRunner?.emit({
85312
+ type: "turn:cancelled",
85313
+ turnIndex: 0,
85314
+ reason: event.reason ?? "cancelled"
85315
+ }) ?? Promise.resolve()
85316
+ );
85317
+ await runtime?.sessionManager.save().catch(() => void 0);
85318
+ }
85319
+ }
85320
+ return;
84816
85321
  }
84817
85322
  if (event.type === "turn_settled" && activeTurn) {
84818
85323
  touch();
@@ -84820,6 +85325,7 @@ async function runJsonEventsMode(params) {
84820
85325
  }
84821
85326
  if (!activeTurn || activeTurn.finalized) return;
84822
85327
  if (event.type === "turn_recovery_pending" && event.recovery === "retry") {
85328
+ recoveryPending = true;
84823
85329
  lastRetryEvent = {
84824
85330
  attempt: event.attempt ?? 0,
84825
85331
  maxRetries: event.maxRetries ?? CLI_RETRY_MAX_RETRIES,
@@ -84838,6 +85344,7 @@ async function runJsonEventsMode(params) {
84838
85344
  error: event.failure.message
84839
85345
  });
84840
85346
  } else if (event.type === "turn_recovery_pending" && event.recovery === "compaction") {
85347
+ recoveryPending = true;
84841
85348
  activeTurn.summary = "";
84842
85349
  clearPendingAssistantOutput();
84843
85350
  touch();
@@ -84868,6 +85375,7 @@ async function runJsonEventsMode(params) {
84868
85375
  error: lastRetryEvent.error
84869
85376
  });
84870
85377
  } else if (event.type === "turn_retry_succeeded") {
85378
+ recoveryPending = false;
84871
85379
  touch();
84872
85380
  writeEvent({
84873
85381
  type: "turn.retry.succeeded",
@@ -84893,8 +85401,12 @@ async function runJsonEventsMode(params) {
84893
85401
  willRetry: event.willRetry
84894
85402
  });
84895
85403
  } else if (event.type === "turn_completed") {
85404
+ recoveryPending = false;
84896
85405
  const text = assistantTextFromMessage(event.message);
84897
85406
  flushAssistantOutput(text);
85407
+ await enqueueBridgeEmission(
85408
+ () => extensionRunner?.emit({ type: "turn:completed" }) ?? Promise.resolve()
85409
+ );
84898
85410
  rememberTerminal("completed", text || activeTurn.summary.trim());
84899
85411
  } else if (event.type === "turn_failed_terminal") {
84900
85412
  touch();
@@ -84910,12 +85422,37 @@ async function runJsonEventsMode(params) {
84910
85422
  });
84911
85423
  lastRetryEvent = void 0;
84912
85424
  }
85425
+ recoveryPending = false;
84913
85426
  rememberTerminal("failed", event.failure.message);
85427
+ const failureCarrier = event.message ?? {
85428
+ role: "assistant",
85429
+ content: [{ type: "text", text: "" }],
85430
+ stopReason: "error",
85431
+ errorMessage: event.failure.message
85432
+ };
85433
+ await enqueueBridgeEmission(
85434
+ () => extensionRunner?.emit({
85435
+ type: "turn:failed",
85436
+ turnIndex: 0,
85437
+ message: failureCarrier,
85438
+ toolResults: []
85439
+ }) ?? Promise.resolve()
85440
+ );
84914
85441
  } else if (event.type === "turn_cancelled") {
85442
+ recoveryPending = false;
85443
+ lastRetryEvent = void 0;
84915
85444
  rememberTerminal("cancelled", event.reason, { overwrite: false });
85445
+ await enqueueBridgeEmission(
85446
+ () => extensionRunner?.emit({
85447
+ type: "turn:cancelled",
85448
+ turnIndex: 0,
85449
+ reason: event.reason ?? "cancelled"
85450
+ }) ?? Promise.resolve()
85451
+ );
84916
85452
  }
84917
85453
  }
84918
85454
  async function disposeRuntime(reason = "runtime_switch") {
85455
+ externalTurn = null;
84919
85456
  const runner = extensionRunner;
84920
85457
  extensionRunner = void 0;
84921
85458
  try {
@@ -84926,6 +85463,8 @@ async function runJsonEventsMode(params) {
84926
85463
  }
84927
85464
  disposeAgentSubscription?.();
84928
85465
  disposeAgentSubscription = void 0;
85466
+ disposeAgentRawSubscription?.();
85467
+ disposeAgentRawSubscription = void 0;
84929
85468
  disposeSemanticSubscription?.();
84930
85469
  disposeSemanticSubscription = void 0;
84931
85470
  controller?.dispose();
@@ -84950,7 +85489,10 @@ async function runJsonEventsMode(params) {
84950
85489
  if (!params.createRuntime && !params.runtime) return;
84951
85490
  try {
84952
85491
  await new Promise((resolve8, reject) => {
84953
- const timer = setTimeout(() => reject(new Error("prewarm timeout")), prewarmTimeoutMs);
85492
+ const timer = setTimeout(
85493
+ () => reject(new Error("prewarm timeout")),
85494
+ prewarmTimeoutMs
85495
+ );
84954
85496
  timer.unref?.();
84955
85497
  void ensureRuntime().then(resolve8, reject).finally(() => clearTimeout(timer));
84956
85498
  });
@@ -84973,6 +85515,8 @@ async function runJsonEventsMode(params) {
84973
85515
  }
84974
85516
  async function composeRuntime(effectiveCwd) {
84975
85517
  if (params.createRuntime && (!runtime || runtime.cwd !== effectiveCwd)) {
85518
+ compositionGeneration += 1;
85519
+ externalTurn = null;
84976
85520
  await disposeRuntime();
84977
85521
  runtime = await params.createRuntime({ cwd: effectiveCwd, sessionId });
84978
85522
  }
@@ -84996,15 +85540,44 @@ async function runJsonEventsMode(params) {
84996
85540
  if (runtime.initialModel.unconfigured || controller) {
84997
85541
  return;
84998
85542
  }
84999
- const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
85543
+ const { Agent: AgentClass } = await import("./chunks/src-ODLT57PQ.js");
85000
85544
  if (runtimeClosing) return;
85001
85545
  const compositionRegistry = createCliHostEnvelopeRegistry();
85002
- const jsonModeExtensions = await loadJsonModeExtensions({ runtime, envelopeRegistry: compositionRegistry, getAgent: () => agent });
85546
+ const jsonModeExtensions = await loadJsonModeExtensions({
85547
+ runtime,
85548
+ envelopeRegistry: compositionRegistry,
85549
+ getAgent: () => agent,
85550
+ getController: () => controller,
85551
+ generation: compositionGeneration,
85552
+ getGeneration: () => compositionGeneration,
85553
+ queueExternalInput,
85554
+ ensureRuntimeReady: async () => {
85555
+ if (controller && !runtimeClosing) return true;
85556
+ try {
85557
+ await ensureRuntime(runtime?.cwd);
85558
+ return !runtimeClosing && controller !== void 0;
85559
+ } catch {
85560
+ return false;
85561
+ }
85562
+ }
85563
+ });
85003
85564
  if (runtimeClosing) {
85004
85565
  await jsonModeExtensions.runner.dispose("shutdown");
85005
85566
  return;
85006
85567
  }
85007
85568
  extensionRunner = jsonModeExtensions.runner;
85569
+ {
85570
+ const activeSessionId = runtime.sessionManager.getActiveSessionId();
85571
+ await enqueueBridgeEmission(
85572
+ () => jsonModeExtensions.runner.emit({
85573
+ type: "session:changed",
85574
+ sessionId: activeSessionId ?? null,
85575
+ metadata: {
85576
+ ...runtime.sessionManager.getActiveSession()?.metadata ?? {}
85577
+ }
85578
+ }) ?? Promise.resolve()
85579
+ );
85580
+ }
85008
85581
  envelopeRegistry = compositionRegistry;
85009
85582
  const tools = [...runtime.tools, ...jsonModeExtensions.extensionTools];
85010
85583
  const restoredApiKey = runtime.modelRegistry.getApiKey(runtime.model);
@@ -85038,10 +85611,14 @@ async function runJsonEventsMode(params) {
85038
85611
  // Restored interactive sessions carry persisted hostContext facts; project
85039
85612
  // them to model-visible text at the request boundary or the provider
85040
85613
  // converters reject the request (`Unprojected hostContext block`).
85041
- transformContext: async (messages) => projectCliHostEnvelopes(messages, (outcome) => trace?.noteRuntimeEvent(
85042
- outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
85043
- outcome.audit
85044
- ), compositionRegistry),
85614
+ transformContext: async (messages) => projectCliHostEnvelopes(
85615
+ messages,
85616
+ (outcome) => trace?.noteRuntimeEvent(
85617
+ outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
85618
+ outcome.audit
85619
+ ),
85620
+ compositionRegistry
85621
+ ),
85045
85622
  // Body-free transport timeline for the main (JSON-events) agent.
85046
85623
  streamFn: createJsonEventsTransportStreamFn(params.streamFn)
85047
85624
  });
@@ -85064,7 +85641,31 @@ async function runJsonEventsMode(params) {
85064
85641
  },
85065
85642
  retry: createCliRetryPolicy(),
85066
85643
  onExecutionEnd: async ({ messages }) => {
85067
- await jsonModeExtensions.runner.emit({ type: "agent:end", messages });
85644
+ const lastAssistant = [...messages].reverse().find((m2) => m2.role === "assistant");
85645
+ const retrying = recoveryPending && (!activeTurn?.finalized || externalTurn !== null);
85646
+ if (retrying) {
85647
+ const failedAssistant = [...messages].reverse().find(
85648
+ (m2) => m2.role === "assistant" && (m2.stopReason === "error" || m2.stopReason === "aborted")
85649
+ );
85650
+ if (failedAssistant)
85651
+ await enqueueBridgeEmission(
85652
+ () => jsonModeExtensions.runner.emit({
85653
+ type: "message:end",
85654
+ message: failedAssistant
85655
+ })
85656
+ );
85657
+ return;
85658
+ }
85659
+ if (lastAssistant)
85660
+ await enqueueBridgeEmission(
85661
+ () => jsonModeExtensions.runner.emit({
85662
+ type: "message:end",
85663
+ message: lastAssistant
85664
+ })
85665
+ );
85666
+ await enqueueBridgeEmission(
85667
+ () => jsonModeExtensions.runner.emit({ type: "agent:end", messages })
85668
+ );
85068
85669
  },
85069
85670
  getAutoCompactDecision: ({ message, messages }) => createCliAutoCompactDecision({
85070
85671
  message,
@@ -85096,14 +85697,40 @@ async function runJsonEventsMode(params) {
85096
85697
  classifyFailure: (context) => classifyCliFailure(context),
85097
85698
  onEvent: handleControllerEvent
85098
85699
  });
85099
- trace = new SessionTraceWriter(runtime.paths.sessionsDir, runtime.sessionManager);
85700
+ trace = new SessionTraceWriter(
85701
+ runtime.paths.sessionsDir,
85702
+ runtime.sessionManager
85703
+ );
85100
85704
  attachAgentEventsToSessionTrace({ agent, trace });
85101
- agent.setTools(wrapToolsWithExtensions(agent.state.tools, jsonModeExtensions.runner));
85705
+ agent.setTools(
85706
+ wrapToolsWithExtensions(agent.state.tools, jsonModeExtensions.runner)
85707
+ );
85102
85708
  controller.updateRuntimeContext({ tools: agent.state.tools });
85103
85709
  disposeSemanticSubscription = agent.subscribeSemantic(handleSemanticEvent);
85710
+ disposeAgentRawSubscription = agent.subscribe((event) => {
85711
+ if (event.type === "turn_start") {
85712
+ void enqueueBridgeEmission(
85713
+ () => extensionRunner?.emit({
85714
+ type: "turn:start",
85715
+ turnIndex: turnCounter++,
85716
+ timestamp: Date.now()
85717
+ }) ?? Promise.resolve()
85718
+ );
85719
+ } else if (event.type === "message_end" && event.message?.role === "user") {
85720
+ void enqueueBridgeEmission(
85721
+ () => extensionRunner?.emit({
85722
+ type: "message:end",
85723
+ message: event.message
85724
+ }) ?? Promise.resolve()
85725
+ );
85726
+ }
85727
+ });
85104
85728
  if (!thinkingLevelInitialized) {
85105
85729
  thinkingLevelInitialized = true;
85106
- thinkingLevel = resolveInitialThinkingLevel({ session: runtime.sessionManager.getActiveSession(), settingsManager: runtime.settingsManager });
85730
+ thinkingLevel = resolveInitialThinkingLevel({
85731
+ session: runtime.sessionManager.getActiveSession(),
85732
+ settingsManager: runtime.settingsManager
85733
+ });
85107
85734
  agent.setThinkingLevel(thinkingLevel);
85108
85735
  }
85109
85736
  }
@@ -85111,7 +85738,8 @@ async function runJsonEventsMode(params) {
85111
85738
  if (!metadata || !(key in metadata)) return void 0;
85112
85739
  const value = metadata[key];
85113
85740
  if (value === null) return null;
85114
- if (typeof value !== "string") throw new Error(`${key} must be a string or null`);
85741
+ if (typeof value !== "string")
85742
+ throw new Error(`${key} must be a string or null`);
85115
85743
  const normalized = value.trim();
85116
85744
  return normalized && normalized !== "default" ? normalized : null;
85117
85745
  }
@@ -85136,7 +85764,10 @@ async function runJsonEventsMode(params) {
85136
85764
  function applyRuntimeSelection(message) {
85137
85765
  if (!runtime || !agent) return;
85138
85766
  const requestedModel = metadataSelection(message.metadata, "model");
85139
- const requestedThinkingLevel = metadataSelection(message.metadata, "thinkingLevel");
85767
+ const requestedThinkingLevel = metadataSelection(
85768
+ message.metadata,
85769
+ "thinkingLevel"
85770
+ );
85140
85771
  if (requestedModel !== void 0) {
85141
85772
  if (requestedModel === null) {
85142
85773
  const defaults = defaultModelState;
@@ -85150,7 +85781,10 @@ async function runJsonEventsMode(params) {
85150
85781
  }
85151
85782
  } else {
85152
85783
  const parsed = parseRequestedModel(requestedModel);
85153
- if (!parsed) throw new Error(`model must use profile/modelId format: ${requestedModel}`);
85784
+ if (!parsed)
85785
+ throw new Error(
85786
+ `model must use profile/modelId format: ${requestedModel}`
85787
+ );
85154
85788
  const { provider, modelId } = parsed;
85155
85789
  const model = runtime.modelRegistry.find(provider, modelId);
85156
85790
  if (!model) throw new Error(`Model "${requestedModel}" not found`);
@@ -85165,7 +85799,8 @@ async function runJsonEventsMode(params) {
85165
85799
  }
85166
85800
  if (requestedThinkingLevel !== void 0) {
85167
85801
  const nextLevel = requestedThinkingLevel === null ? "off" : requestedThinkingLevel;
85168
- if (!isThinkingLevel(nextLevel)) throw new Error(`Unsupported thinkingLevel: ${nextLevel}`);
85802
+ if (!isThinkingLevel(nextLevel))
85803
+ throw new Error(`Unsupported thinkingLevel: ${nextLevel}`);
85169
85804
  thinkingLevel = nextLevel;
85170
85805
  thinkingLevelInitialized = true;
85171
85806
  applyThinkingLevel({
@@ -85181,12 +85816,21 @@ async function runJsonEventsMode(params) {
85181
85816
  persist: false
85182
85817
  });
85183
85818
  } else {
85184
- syncSessionModelMetadata(runtime.sessionManager, runtime.model, thinkingLevel);
85819
+ syncSessionModelMetadata(
85820
+ runtime.sessionManager,
85821
+ runtime.model,
85822
+ thinkingLevel
85823
+ );
85185
85824
  }
85186
85825
  }
85187
85826
  function promptInputFor(message) {
85188
85827
  return message.hostContext ? [message.hostContext, { type: "text", text: message.prompt }] : message.prompt;
85189
85828
  }
85829
+ let turnCounter = 0;
85830
+ function promptAgentMessage(message) {
85831
+ const content = promptInputFor(message);
85832
+ return { role: "user", content, timestamp: Date.now() };
85833
+ }
85190
85834
  function sidechatPromptBlocks(message) {
85191
85835
  return message.hostContext ? [message.hostContext, { type: "text", text: message.prompt }] : [{ type: "text", text: message.prompt }];
85192
85836
  }
@@ -85205,7 +85849,9 @@ async function runJsonEventsMode(params) {
85205
85849
  }
85206
85850
  if (activeTurn && !activeTurn.finalized) {
85207
85851
  const owner = activeTurn;
85208
- owner.queue = owner.queue.then(() => queueActiveTurnInput(message, owner));
85852
+ owner.queue = owner.queue.then(
85853
+ () => queueActiveTurnInput(message, owner)
85854
+ );
85209
85855
  await owner.queue;
85210
85856
  return;
85211
85857
  }
@@ -85230,7 +85876,13 @@ async function runJsonEventsMode(params) {
85230
85876
  pendingAssistantOutput: ""
85231
85877
  };
85232
85878
  const turn = activeTurn;
85233
- writeEvent({ type: "turn.started", sessionId: activeTurn.sessionId, turnId: activeTurn.turnId });
85879
+ recoveryPending = false;
85880
+ lastRetryEvent = void 0;
85881
+ writeEvent({
85882
+ type: "turn.started",
85883
+ sessionId: activeTurn.sessionId,
85884
+ turnId: activeTurn.turnId
85885
+ });
85234
85886
  if (params.mockResponse !== void 0) {
85235
85887
  const mockHostContextFailure = validateIntakeHostContext(message);
85236
85888
  if (mockHostContextFailure) {
@@ -85278,7 +85930,8 @@ async function runJsonEventsMode(params) {
85278
85930
  return;
85279
85931
  }
85280
85932
  if (activeTurn !== turn || turn.finalized || turn.interrupted) {
85281
- if (activeTurn === turn && !turn.finalized) finalize("cancelled", "user_interrupt");
85933
+ if (activeTurn === turn && !turn.finalized)
85934
+ finalize("cancelled", "user_interrupt");
85282
85935
  turn.releaseReady();
85283
85936
  if (activeTurn === turn) {
85284
85937
  emitSettled(turn);
@@ -85299,7 +85952,10 @@ async function runJsonEventsMode(params) {
85299
85952
  }
85300
85953
  const activeRuntime = runtime;
85301
85954
  if (activeRuntime?.initialModel.unconfigured) {
85302
- finalize("failed", activeRuntime.initialModel.warning || "No models are configured.");
85955
+ finalize(
85956
+ "failed",
85957
+ activeRuntime.initialModel.warning || "No models are configured."
85958
+ );
85303
85959
  if (activeTurn === turn) emitSettled(turn);
85304
85960
  if (activeTurn === turn) activeTurn = null;
85305
85961
  return;
@@ -85313,25 +85969,34 @@ async function runJsonEventsMode(params) {
85313
85969
  try {
85314
85970
  applyRuntimeSelection(message);
85315
85971
  } catch (error) {
85316
- finalize("failed", error instanceof Error ? error.message : String(error));
85972
+ finalize(
85973
+ "failed",
85974
+ error instanceof Error ? error.message : String(error)
85975
+ );
85317
85976
  if (activeTurn === turn) emitSettled(turn);
85318
85977
  if (activeTurn === turn) activeTurn = null;
85319
85978
  return;
85320
85979
  }
85321
- const progressTimer = setInterval(() => {
85322
- const turn2 = activeTurn;
85323
- if (!turn2 || turn2.finalized) return;
85324
- if (Date.now() - turn2.lastActivityAt >= noProgressTimeoutMs) {
85325
- turn2.stalled = true;
85326
- controller?.abort();
85327
- finalize("stalled", "no_progress_timeout");
85328
- }
85329
- }, Math.max(1e3, Math.min(noProgressTimeoutMs, 1e4)));
85980
+ const progressTimer = setInterval(
85981
+ () => {
85982
+ const turn2 = activeTurn;
85983
+ if (!turn2 || turn2.finalized) return;
85984
+ if (Date.now() - turn2.lastActivityAt >= noProgressTimeoutMs) {
85985
+ turn2.stalled = true;
85986
+ controller?.abort();
85987
+ finalize("stalled", "no_progress_timeout");
85988
+ }
85989
+ },
85990
+ Math.max(1e3, Math.min(noProgressTimeoutMs, 1e4))
85991
+ );
85330
85992
  progressTimer.unref?.();
85331
85993
  try {
85332
85994
  trace?.notePendingUserText(message.prompt);
85333
85995
  trace?.noteDispatchStart({ mode: "json-events" });
85334
- const dispatched = controller.prompt(promptInputFor(message), { source: "json-events" });
85996
+ const promptMessage = promptAgentMessage(message);
85997
+ const dispatched = controller.prompt(promptMessage, {
85998
+ source: "json-events"
85999
+ });
85335
86000
  turn.releaseReady();
85336
86001
  await dispatched;
85337
86002
  trace?.noteDispatchSettled({ mode: "json-events" });
@@ -85361,7 +86026,30 @@ async function runJsonEventsMode(params) {
85361
86026
  } catch {
85362
86027
  }
85363
86028
  if (!activeTurn?.finalized) {
85364
- finalize(activeTurn?.interrupted ? "cancelled" : "failed", activeTurn?.interrupted ? "user_interrupt" : messageText);
86029
+ if (activeTurn?.interrupted) {
86030
+ await extensionRunner?.emit({
86031
+ type: "turn:cancelled",
86032
+ turnIndex: 0,
86033
+ reason: "user_interrupt"
86034
+ });
86035
+ } else {
86036
+ const failureCarrier = {
86037
+ role: "assistant",
86038
+ content: [{ type: "text", text: "" }],
86039
+ stopReason: "error",
86040
+ errorMessage: messageText
86041
+ };
86042
+ await extensionRunner?.emit({
86043
+ type: "turn:failed",
86044
+ turnIndex: 0,
86045
+ message: failureCarrier,
86046
+ toolResults: []
86047
+ });
86048
+ }
86049
+ finalize(
86050
+ activeTurn?.interrupted ? "cancelled" : "failed",
86051
+ activeTurn?.interrupted ? "user_interrupt" : messageText
86052
+ );
85365
86053
  }
85366
86054
  if (activeTurn === turn) emitSettled(turn);
85367
86055
  } finally {
@@ -85487,12 +86175,73 @@ async function runJsonEventsMode(params) {
85487
86175
  }
85488
86176
  const input = readline.createInterface({ input: process.stdin });
85489
86177
  let activeTurnPromise = null;
86178
+ if (params.idle) {
86179
+ input.close();
86180
+ const keepalive = setInterval(() => {
86181
+ }, 3e4);
86182
+ let signalled = false;
86183
+ let hardDeadline;
86184
+ const shutdown = (signal) => {
86185
+ if (signalled) {
86186
+ writeEvent({
86187
+ type: "shutdown.pending",
86188
+ sessionId,
86189
+ reason: `force:${signal}`
86190
+ });
86191
+ process.exit(1);
86192
+ return;
86193
+ }
86194
+ signalled = true;
86195
+ writeEvent({
86196
+ type: "shutdown.pending",
86197
+ sessionId,
86198
+ reason: `signal:${signal}`
86199
+ });
86200
+ runtimeClosing = true;
86201
+ shutdownActiveTurn(`signal:${signal}`);
86202
+ sidechatChainStopped = true;
86203
+ activeSidechat?.abort();
86204
+ clearInterval(keepalive);
86205
+ hardDeadline = setTimeout(() => {
86206
+ writeEvent({
86207
+ type: "shutdown.pending",
86208
+ sessionId,
86209
+ reason: "deadline-exceeded"
86210
+ });
86211
+ process.exit(0);
86212
+ }, 15e3);
86213
+ hardDeadline.unref?.();
86214
+ void (async () => {
86215
+ try {
86216
+ await activeTurnPromise;
86217
+ await activeSidechatPromise;
86218
+ await Promise.allSettled([...ensureRuntimeInFlight.values()]);
86219
+ await disposeRuntime("shutdown");
86220
+ } finally {
86221
+ if (hardDeadline) clearTimeout(hardDeadline);
86222
+ process.exit(0);
86223
+ }
86224
+ })();
86225
+ };
86226
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
86227
+ process.on("SIGINT", () => shutdown("SIGINT"));
86228
+ process.on("SIGHUP", () => {
86229
+ });
86230
+ await new Promise(() => {
86231
+ });
86232
+ return;
86233
+ }
85490
86234
  try {
85491
86235
  for await (const line of input) {
85492
86236
  if (!line.trim()) continue;
85493
86237
  const message = parseInput(line);
85494
86238
  if (!message) {
85495
- writeEvent({ type: "turn.failed", sessionId, turnId: `invalid-${Date.now()}`, error: "invalid JSON events input" });
86239
+ writeEvent({
86240
+ type: "turn.failed",
86241
+ sessionId,
86242
+ turnId: `invalid-${Date.now()}`,
86243
+ error: "invalid JSON events input"
86244
+ });
85496
86245
  continue;
85497
86246
  }
85498
86247
  if (message.type === "shutdown") {
@@ -85516,20 +86265,31 @@ async function runJsonEventsMode(params) {
85516
86265
  }
85517
86266
  if (message.type === "sidechat.request") {
85518
86267
  const prior = activeSidechatPromise ?? Promise.resolve();
85519
- trackSidechatPromise(prior.then(async () => {
85520
- if (sidechatChainStopped) {
85521
- const cached = completedSidechatRequests.get(message.requestId.trim());
85522
- if (cached) {
85523
- writeEvent(cached);
85524
- } else {
85525
- writeSidechatFailure(message, "sidechat discarded on shutdown", "sidechat_interrupted");
86268
+ trackSidechatPromise(
86269
+ prior.then(async () => {
86270
+ if (sidechatChainStopped) {
86271
+ const cached = completedSidechatRequests.get(
86272
+ message.requestId.trim()
86273
+ );
86274
+ if (cached) {
86275
+ writeEvent(cached);
86276
+ } else {
86277
+ writeSidechatFailure(
86278
+ message,
86279
+ "sidechat discarded on shutdown",
86280
+ "sidechat_interrupted"
86281
+ );
86282
+ }
86283
+ return;
85526
86284
  }
85527
- return;
85528
- }
85529
- await handleSidechat(message).catch((error) => {
85530
- writeSidechatFailure(message, error instanceof Error ? error.message : String(error));
85531
- });
85532
- }));
86285
+ await handleSidechat(message).catch((error) => {
86286
+ writeSidechatFailure(
86287
+ message,
86288
+ error instanceof Error ? error.message : String(error)
86289
+ );
86290
+ });
86291
+ })
86292
+ );
85533
86293
  continue;
85534
86294
  }
85535
86295
  const shouldTrackTurn = !activeTurn || activeTurn.finalized;
@@ -85636,6 +86396,7 @@ Print Mode Options:
85636
86396
  --raw-output Print assistant text only in non-interactive mode
85637
86397
  --json-output Print structured JSON in non-interactive mode
85638
86398
  --json-events Run JSONL protocol mode over stdin/stdout
86399
+ --idle Resident mode (with --json-events): no stdin loop, runs until SIGTERM/SIGINT; input arrives via extension intake (IM/IPC), stdout events are the log
85639
86400
  --session-id Reuse or create a specific session in non-interactive mode
85640
86401
  --resume-required In JSON-events mode, fail if --session-id cannot be resumed
85641
86402
  --no-cd Resume without restarting in the session's project directory
@@ -85704,7 +86465,8 @@ var STABLE_CLI_COMMANDS = {
85704
86465
  models: "models",
85705
86466
  sessions: "sessions",
85706
86467
  extensions: "extensions",
85707
- permissions: "permissions"
86468
+ permissions: "permissions",
86469
+ concierge: "concierge"
85708
86470
  };
85709
86471
  async function runWithJsonEventsConsoleIsolation(fn) {
85710
86472
  const originalLog = console.log;
@@ -85724,7 +86486,7 @@ async function runWithJsonEventsConsoleIsolation(fn) {
85724
86486
  }
85725
86487
  async function createCliTestStreamFnFromEnv() {
85726
86488
  if (!process.env.PIE_TEST_MOCK_STREAM_SEQUENCE) return void 0;
85727
- return (await import("./chunks/test-stream-JBWXKOQA.js")).createTestStreamFnFromSequenceEnv();
86489
+ return (await import("./chunks/test-stream-GIUD5JWS.js")).createTestStreamFnFromSequenceEnv();
85728
86490
  }
85729
86491
  function resolveJsonEventsDetailFlag() {
85730
86492
  for (let index = 0; index < process.argv.length; index += 1) {
@@ -85748,6 +86510,11 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
85748
86510
  const extensionPaths = parseRepeatedFlag(process.argv, "--extension-path");
85749
86511
  const extensionFlags = parseExtensionFlags(process.argv);
85750
86512
  if (jsonEvents) {
86513
+ const idle = process.argv.includes("--idle");
86514
+ if (idle && !explicitSessionId) {
86515
+ console.error("--idle requires --session-id: a resident host needs a stable identity across restarts.");
86516
+ process.exit(2);
86517
+ }
85751
86518
  const detailFlag = resolveJsonEventsDetailFlag();
85752
86519
  if ("error" in detailFlag) {
85753
86520
  console.error(`Invalid --event-detail value: ${detailFlag.error}. Use compact or full.`);
@@ -85777,6 +86544,7 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
85777
86544
  resumeRequired,
85778
86545
  developerInstructions,
85779
86546
  eventDetail,
86547
+ idle: process.argv.includes("--idle"),
85780
86548
  streamFn: await createCliTestStreamFnFromEnv(),
85781
86549
  createRuntime: async ({ cwd, sessionId }) => composeCliRuntime({
85782
86550
  explicitSessionId: explicitSessionId ?? sessionId,
@@ -85805,6 +86573,10 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
85805
86573
  return;
85806
86574
  }
85807
86575
  let runtime;
86576
+ if (process.argv.includes("--idle") && !jsonEvents) {
86577
+ console.error("--idle is only valid together with --json-events (resident embedded host).");
86578
+ process.exit(2);
86579
+ }
85808
86580
  try {
85809
86581
  runtime = await composeCliRuntime({ explicitSessionId, extensionPaths, extensionFlags });
85810
86582
  } catch (error) {
@@ -85864,6 +86636,12 @@ async function main() {
85864
86636
  console.log(VERSION);
85865
86637
  return;
85866
86638
  }
86639
+ const oneshotTask = process.env.PIE_PROC_ONESHOT_TASK;
86640
+ if (typeof oneshotTask === "string" && oneshotTask && args[0] === "--session-id" && typeof args[1] === "string" && args.length === 2) {
86641
+ delete process.env.PIE_PROC_ONESHOT_TASK;
86642
+ await startChat(oneshotTask, void 0, args[1]);
86643
+ return;
86644
+ }
85867
86645
  if (args.length === 0 && !process.stdin.isTTY) {
85868
86646
  console.error("pie: no arguments and stdin is not a terminal; refusing to start interactive mode.");
85869
86647
  showHelp();
@@ -85903,6 +86681,16 @@ async function main() {
85903
86681
  await runMemoryCommand(args.slice(1));
85904
86682
  return;
85905
86683
  }
86684
+ if (args[0] === STABLE_CLI_COMMANDS.concierge) {
86685
+ const { runConciergeCommand } = await import("./chunks/concierge-cli-PIOGXKDR.js");
86686
+ try {
86687
+ await runConciergeCommand(args.slice(1));
86688
+ } catch (error) {
86689
+ console.error(error instanceof Error ? error.message : String(error));
86690
+ process.exitCode = 1;
86691
+ }
86692
+ return;
86693
+ }
85906
86694
  const parsed = parseCliInvocation(args);
85907
86695
  if (parsed.showHelp) {
85908
86696
  showHelp();