@cydm/pie 2.8.1 → 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 (42) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +8 -4
  2. package/dist/builtin/extensions/changelog/index.js +2 -2
  3. package/dist/builtin/extensions/cron/index.js +295 -33
  4. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  5. package/dist/builtin/extensions/herdr-agent-state/index.js +2 -2
  6. package/dist/builtin/extensions/im-forward/README.md +20 -5
  7. package/dist/builtin/extensions/im-forward/index.js +415 -142
  8. package/dist/builtin/extensions/memory/index.js +83 -30
  9. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  10. package/dist/builtin/extensions/pie-ipc/index.js +269 -30
  11. package/dist/builtin/extensions/pie-proc/README.md +93 -0
  12. package/dist/builtin/extensions/pie-proc/index.js +630 -0
  13. package/dist/builtin/extensions/pie-proc/package.json +11 -0
  14. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  15. package/dist/builtin/extensions/subagent/index.js +6 -6
  16. package/dist/builtin/extensions/todo/index.js +4 -4
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +106 -2
  18. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +1 -0
  19. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  20. package/dist/builtin/skills/chrome-devtools-axi/{chunk-BNSAEVRT.js → chunk-WOGAQ4P5.js} +2 -2
  21. package/dist/builtin/skills/chrome-devtools-axi/{cli-AO2ZTPRM.js → cli-CHC7XYFU.js} +27 -3
  22. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +2 -2
  23. package/dist/builtin/skills/computer-use-axi/computer-use-axi-cli.js +1 -0
  24. package/dist/builtin/skills/computer-use-axi/scripts/setup-helper.mjs +6 -2
  25. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +179 -9
  26. package/dist/chunks/{chunk-PK72LVWQ.js → chunk-FDLLNPIE.js} +143 -53
  27. package/dist/chunks/{chunk-3BC5KGDQ.js → chunk-JQRZLVPY.js} +12 -1
  28. package/dist/chunks/{chunk-GH4VW2OT.js → chunk-NCP264ZE.js} +8 -2
  29. package/dist/chunks/{chunk-YRR6C43W.js → chunk-QX6WS73C.js} +1 -1
  30. package/dist/chunks/{chunk-3NHP7HK5.js → chunk-TDKNKNPL.js} +6 -5
  31. package/dist/chunks/{chunk-GDIYSMTS.js → chunk-UOZHQ73X.js} +25 -17
  32. package/dist/chunks/{chunk-RSL7E4R7.js → chunk-WK4N5HT5.js} +66 -23
  33. package/dist/chunks/chunk-X6LBWHK3.js +37 -0
  34. package/dist/chunks/concierge-cli-PIOGXKDR.js +939 -0
  35. package/dist/chunks/{model-registry-LI5THXV4.js → model-registry-YA6U366L.js} +2 -2
  36. package/dist/chunks/{src-BPSQMSSC.js → src-AB7PLORG.js} +6 -4
  37. package/dist/chunks/{src-YG5M2H44.js → src-ODLT57PQ.js} +2 -2
  38. package/dist/chunks/{src-66XSMIAM.js → src-XSLD2IQ2.js} +1 -1
  39. package/dist/chunks/{src-OPPYTPWG.js → src-ZZZO4HSR.js} +11 -3
  40. package/dist/chunks/{test-stream-JBWXKOQA.js → test-stream-GIUD5JWS.js} +1 -1
  41. package/dist/cli.js +1433 -235
  42. 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-3NHP7HK5.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-GDIYSMTS.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-PK72LVWQ.js";
79
+ } from "./chunks/chunk-FDLLNPIE.js";
80
80
  import {
81
81
  AGENTS_CONTEXT_FILE_NAME,
82
82
  AgentSessionController,
@@ -84,6 +84,8 @@ import {
84
84
  DEFAULT_COMPACTION_CONFIG,
85
85
  ExtensionResourceScope,
86
86
  FileSessionStore,
87
+ SUPERVISOR_PID_ENV,
88
+ SUPERVISOR_START_TIME_ENV,
87
89
  SessionTraceSnapshotWriter,
88
90
  attachAgentEventsToSessionTrace,
89
91
  buildProjectContextSection,
@@ -114,8 +116,8 @@ import {
114
116
  setEnablementInMap,
115
117
  setExtensionEnabledInSettings,
116
118
  verifyPreparedCompactionCommit
117
- } from "./chunks/chunk-RSL7E4R7.js";
118
- import "./chunks/chunk-GH4VW2OT.js";
119
+ } from "./chunks/chunk-WK4N5HT5.js";
120
+ import "./chunks/chunk-NCP264ZE.js";
119
121
  import {
120
122
  Deref,
121
123
  Errors,
@@ -134,7 +136,7 @@ import {
134
136
  setLogger,
135
137
  streamSimple,
136
138
  type_exports
137
- } from "./chunks/chunk-3BC5KGDQ.js";
139
+ } from "./chunks/chunk-JQRZLVPY.js";
138
140
  import {
139
141
  IsArray,
140
142
  IsBigInt,
@@ -51310,7 +51312,7 @@ import * as path33 from "path";
51310
51312
 
51311
51313
  // src/cli-args.ts
51312
51314
  var FLAGS_WITH_VALUES = /* @__PURE__ */ new Set(["--session-id", "--extension-path", "--developer-instructions", "--developer-instructions-file"]);
51313
- 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"]);
51314
51316
  var HELP_FLAGS = /* @__PURE__ */ new Set(["help", "--help", "-h"]);
51315
51317
  var COMMANDS = /* @__PURE__ */ new Set(["chat", "help"]);
51316
51318
  function parseCliInvocation(args) {
@@ -52147,7 +52149,7 @@ function commandVersion(command, args = ["--version"]) {
52147
52149
  function checkShell() {
52148
52150
  const shell = process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : process.env.SHELL || "/bin/sh";
52149
52151
  const args = process.platform === "win32" ? ["/d", "/s", "/c", "exit 0"] : ["-lc", "exit 0"];
52150
- const result = spawnSync(shell, args, { encoding: "utf8", shell: false });
52152
+ const result = spawnSync(shell, args, { encoding: "utf8", shell: false, windowsHide: true });
52151
52153
  const ok = (result.status ?? 1) === 0;
52152
52154
  return {
52153
52155
  id: "shell",
@@ -52231,7 +52233,7 @@ function checkChromeDevtoolsAxiCli() {
52231
52233
  message: "chrome-devtools-axi is not resolvable from Pie's runtime dependencies."
52232
52234
  };
52233
52235
  }
52234
- const result = spawnSync(process.execPath, [cliPath, "--version"], { encoding: "utf8", shell: false });
52236
+ const result = spawnSync(process.execPath, [cliPath, "--version"], { encoding: "utf8", shell: false, windowsHide: true });
52235
52237
  const ok = (result.status ?? 1) === 0;
52236
52238
  return {
52237
52239
  id: "chrome_devtools_axi",
@@ -53910,6 +53912,54 @@ function anchorAgentDirForChild(env) {
53910
53912
  }
53911
53913
  return { ...env, PIE_CODING_AGENT_DIR: path6.resolve(process.cwd(), value) };
53912
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
+ }
53913
53963
  function buildChildEnv(env) {
53914
53964
  const anchored = anchorAgentDirForChild(env);
53915
53965
  const out = {};
@@ -53917,6 +53967,7 @@ function buildChildEnv(env) {
53917
53967
  if (DROPPED_ENV_KEYS.has(key)) continue;
53918
53968
  out[key] = value;
53919
53969
  }
53970
+ if (out.NODE_OPTIONS) out.NODE_OPTIONS = anchorNodeOptions(out.NODE_OPTIONS, process.cwd());
53920
53971
  return out;
53921
53972
  }
53922
53973
  function decideSessionResumeRestart(argv, sessionId, cwd) {
@@ -53946,10 +53997,11 @@ async function performResumeRestart(decision, onSpawnFailure) {
53946
53997
  emitOsc7Cwd(decision.targetCwd);
53947
53998
  };
53948
53999
  return await new Promise((resolve8) => {
53949
- 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)], {
53950
54001
  cwd: decision.targetCwd,
53951
54002
  stdio: "inherit",
53952
- env: buildChildEnv(decision.childEnv)
54003
+ env: buildChildEnv(decision.childEnv),
54004
+ windowsHide: true
53953
54005
  });
53954
54006
  child.on("spawn", () => announce());
53955
54007
  child.on("error", (error) => {
@@ -54860,6 +54912,17 @@ import * as os2 from "os";
54860
54912
  import * as path8 from "path";
54861
54913
  import { pathToFileURL as pathToFileURL2 } from "node:url";
54862
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
+
54863
54926
  // src/command-tree.ts
54864
54927
  var CommandTree = class {
54865
54928
  root = { name: "", description: "Root", children: [], isCategory: true };
@@ -55022,7 +55085,7 @@ var CommandTree = class {
55022
55085
  var commandTree = new CommandTree();
55023
55086
 
55024
55087
  // src/extensions/loader.ts
55025
- function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, hasUI, actions) {
55088
+ function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, capabilities, actions) {
55026
55089
  const context = {
55027
55090
  registerCleanup: (handler) => (extension.resources ??= new ExtensionResourceScope()).register(handler),
55028
55091
  ui: uiContext,
@@ -55030,7 +55093,8 @@ function createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, ha
55030
55093
  request: (request) => requestInteraction(request),
55031
55094
  isAvailable: () => hasInteractionHandler()
55032
55095
  },
55033
- hasUI,
55096
+ capabilities,
55097
+ hasUI: capabilities.interactiveUI,
55034
55098
  cwd,
55035
55099
  log: (message) => {
55036
55100
  if (process.env.PIE_VERBOSE) {
@@ -55233,14 +55297,14 @@ async function loadExtensionModule(extensionPath) {
55233
55297
  }
55234
55298
  function normalizeExtensionImportPath(extensionPath) {
55235
55299
  if (/^[a-zA-Z]:[\\/]/.test(extensionPath)) {
55236
- return `file:///${extensionPath.replace(/\\/g, "/")}`;
55300
+ return pathToFileURL2(extensionPath, { windows: true }).href;
55237
55301
  }
55238
55302
  if (path8.isAbsolute(extensionPath)) {
55239
55303
  return pathToFileURL2(extensionPath).href;
55240
55304
  }
55241
55305
  return extensionPath;
55242
55306
  }
55243
- async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, hasUI, actions, discovered) {
55307
+ async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, capabilities, actions, discovered) {
55244
55308
  const resolvedPath = resolvePath(extensionPath, cwd);
55245
55309
  if (!fs9.existsSync(resolvedPath)) {
55246
55310
  return { extension: null, error: `Extension not found: ${extensionPath}` };
@@ -55254,7 +55318,7 @@ async function loadExtension(extensionPath, cwd, uiContext, abortFn, isIdleFn, h
55254
55318
  };
55255
55319
  }
55256
55320
  const extension = createExtension(extensionPath, resolvedPath, discovered?.identity, discovered?.source);
55257
- const ctx = createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, hasUI, actions);
55321
+ const ctx = createExtensionContext(extension, cwd, uiContext, abortFn, isIdleFn, capabilities, actions);
55258
55322
  try {
55259
55323
  await factory(ctx);
55260
55324
  } catch (error) {
@@ -55410,7 +55474,7 @@ function discoverAllExtensions(configuredPaths, cwd, options) {
55410
55474
  enabled: item.identity ? isExtensionEnabled(item.identity, ...layers, manifestDefaultLayer(item.defaultEnablement)) : true
55411
55475
  }));
55412
55476
  }
55413
- 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) {
55414
55478
  const extensions = [];
55415
55479
  const errors = [];
55416
55480
  const seenResolvedPaths = /* @__PURE__ */ new Set();
@@ -55465,7 +55529,7 @@ async function loadExtensions(configuredPaths, cwd, uiContext, abortFn, isIdleFn
55465
55529
  uiContext,
55466
55530
  abortFn,
55467
55531
  isIdleFn,
55468
- hasUI,
55532
+ capabilities,
55469
55533
  actions,
55470
55534
  discoveredByPath.get(extPath)
55471
55535
  );
@@ -61811,7 +61875,7 @@ var Markdown = class {
61811
61875
  break;
61812
61876
  }
61813
61877
  case "list": {
61814
- const listLines = this.renderList(token, 0);
61878
+ const listLines = this.renderList(token, 0, void 0, width);
61815
61879
  appendLines(lines, listLines);
61816
61880
  break;
61817
61881
  }
@@ -61821,20 +61885,7 @@ var Markdown = class {
61821
61885
  break;
61822
61886
  }
61823
61887
  case "blockquote": {
61824
- const quoteStyle = (text) => this.theme.quote(this.theme.italic(text));
61825
- const quoteStyleContext = {
61826
- applyText: quoteStyle,
61827
- stylePrefix: this.getStylePrefix(quoteStyle)
61828
- };
61829
- const quoteText = this.renderInlineTokens(token.tokens || [], quoteStyleContext);
61830
- const quoteLines = quoteText.split("\n");
61831
- const quoteContentWidth = Math.max(1, width - 2);
61832
- for (const quoteLine of quoteLines) {
61833
- const wrappedLines = wrapTextWithAnsi(quoteLine, quoteContentWidth);
61834
- for (const wrappedLine of wrappedLines) {
61835
- lines.push(this.theme.quoteBorder("\u2502 ") + wrappedLine);
61836
- }
61837
- }
61888
+ appendLines(lines, this.renderBlockquote(token, width, void 0));
61838
61889
  if (nextTokenType !== "space") {
61839
61890
  lines.push("");
61840
61891
  }
@@ -61861,6 +61912,124 @@ var Markdown = class {
61861
61912
  }
61862
61913
  return lines;
61863
61914
  }
61915
+ /**
61916
+ * Render a blockquote token to bordered, wrapped lines.
61917
+ * Used both at top level and inside list items.
61918
+ */
61919
+ renderBlockquote(token, width, styleContext) {
61920
+ const lines = [];
61921
+ const quoteStyle = (text) => this.theme.quote(this.theme.italic(text));
61922
+ const quoteStyleContext = styleContext ?? {
61923
+ applyText: quoteStyle,
61924
+ stylePrefix: this.getStylePrefix(quoteStyle)
61925
+ };
61926
+ const quoteContentWidth = Math.max(1, width - 2);
61927
+ const innerTokens = token.tokens || [];
61928
+ const quoteTextLines = [];
61929
+ for (let i = 0; i < innerTokens.length; i++) {
61930
+ this.renderQuoteInnerToken(
61931
+ innerTokens[i],
61932
+ innerTokens[i + 1]?.type,
61933
+ quoteStyleContext,
61934
+ quoteContentWidth,
61935
+ quoteTextLines
61936
+ );
61937
+ }
61938
+ for (const quoteLine of quoteTextLines) {
61939
+ if (quoteLine === "") {
61940
+ lines.push(this.theme.quoteBorder("\u2502 "));
61941
+ continue;
61942
+ }
61943
+ const wrappedLines = wrapTextWithAnsi(quoteLine, quoteContentWidth);
61944
+ for (const wrappedLine of wrappedLines) {
61945
+ lines.push(this.theme.quoteBorder("\u2502 ") + wrappedLine);
61946
+ }
61947
+ }
61948
+ return lines;
61949
+ }
61950
+ /**
61951
+ * Render a block-level token inside a blockquote.
61952
+ * Produces UNWRAPPED, UNBORDERED lines; the caller adds wrapping + border.
61953
+ */
61954
+ renderQuoteInnerToken(token, nextTokenType, styleContext, width, target) {
61955
+ switch (token.type) {
61956
+ case "paragraph": {
61957
+ const text = this.renderInlineTokens(token.tokens || [], styleContext);
61958
+ appendLines(target, text.split("\n"));
61959
+ break;
61960
+ }
61961
+ case "space":
61962
+ target.push("");
61963
+ break;
61964
+ case "list":
61965
+ appendLines(target, this.renderList(token, 0, styleContext, width));
61966
+ break;
61967
+ case "blockquote": {
61968
+ const nestedBorder = this.theme.quoteBorder("\u2502 ");
61969
+ const nestedWidth = Math.max(1, width - 2);
61970
+ const nestedTokens = token.tokens || [];
61971
+ const nestedLines = [];
61972
+ for (let i = 0; i < nestedTokens.length; i++) {
61973
+ this.renderQuoteInnerToken(
61974
+ nestedTokens[i],
61975
+ nestedTokens[i + 1]?.type,
61976
+ styleContext,
61977
+ nestedWidth,
61978
+ nestedLines
61979
+ );
61980
+ }
61981
+ for (const nestedLine of nestedLines) {
61982
+ if (nestedLine === "") {
61983
+ target.push(nestedBorder);
61984
+ continue;
61985
+ }
61986
+ const wrappedNested = wrapTextWithAnsi(nestedLine, nestedWidth);
61987
+ for (const nestedWrappedLine of wrappedNested) {
61988
+ target.push(nestedBorder + nestedWrappedLine);
61989
+ }
61990
+ }
61991
+ break;
61992
+ }
61993
+ case "code": {
61994
+ const indent = this.theme.codeBlockIndent ?? " ";
61995
+ target.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
61996
+ if (this.theme.highlightCode) {
61997
+ const highlightedLines = this.theme.highlightCode(token.text, token.lang);
61998
+ for (const hlLine of highlightedLines) {
61999
+ target.push(`${indent}${hlLine}`);
62000
+ }
62001
+ } else {
62002
+ const codeLines = token.text.split("\n");
62003
+ for (const codeLine of codeLines) {
62004
+ target.push(`${indent}${this.theme.codeBlock(codeLine)}`);
62005
+ }
62006
+ }
62007
+ target.push(this.theme.codeBlockBorder("```"));
62008
+ break;
62009
+ }
62010
+ case "table":
62011
+ appendLines(target, this.renderTable(token, width));
62012
+ break;
62013
+ case "hr":
62014
+ target.push(this.theme.hr("\u2500".repeat(Math.min(width, 80))));
62015
+ break;
62016
+ case "heading": {
62017
+ const headingText = this.renderInlineTokens(token.tokens || [], styleContext);
62018
+ target.push(this.theme.bold(headingText));
62019
+ if (nextTokenType !== void 0 && nextTokenType !== "space") {
62020
+ target.push("");
62021
+ }
62022
+ break;
62023
+ }
62024
+ default: {
62025
+ if ("text" in token && typeof token.text === "string") {
62026
+ appendLines(target, this.renderInlineTokens([token], styleContext).split("\n"));
62027
+ } else if ("raw" in token && typeof token.raw === "string") {
62028
+ appendLines(target, token.raw.split("\n"));
62029
+ }
62030
+ }
62031
+ }
62032
+ }
61864
62033
  renderInlineTokens(tokens, styleContext) {
61865
62034
  let result = "";
61866
62035
  const resolvedStyleContext = styleContext ?? this.getDefaultInlineStyleContext();
@@ -61907,6 +62076,14 @@ var Markdown = class {
61907
62076
  case "br":
61908
62077
  result += "\n";
61909
62078
  break;
62079
+ case "checkbox":
62080
+ result += applyText(token.checked ? "[x] " : "[ ] ");
62081
+ break;
62082
+ case "image": {
62083
+ const altText = this.renderInlineTokens(token.tokens || [], resolvedStyleContext) || token.text || "image";
62084
+ result += this.theme.link(this.theme.underline(altText)) + this.theme.linkUrl(` (${token.href})`) + stylePrefix;
62085
+ break;
62086
+ }
61910
62087
  case "del": {
61911
62088
  const delContent = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);
61912
62089
  result += this.theme.strikethrough(delContent) + stylePrefix;
@@ -61926,32 +62103,39 @@ var Markdown = class {
61926
62103
  return result;
61927
62104
  }
61928
62105
  /**
61929
- * Render a list with proper nesting support
62106
+ * Render a list with proper nesting support.
62107
+ * Nested structure is tracked via ListItemFragment provenance metadata
62108
+ * (never inferred from the rendered string / its ANSI colors).
61930
62109
  */
61931
- renderList(token, depth) {
62110
+ renderList(token, depth, styleContext, availableWidth) {
61932
62111
  const lines = [];
61933
62112
  const indent = " ".repeat(depth);
61934
62113
  const startNumber = token.start ?? 1;
61935
62114
  for (let i = 0; i < token.items.length; i++) {
61936
62115
  const item = token.items[i];
61937
62116
  const bullet = token.ordered ? `${startNumber + i}. ` : "- ";
61938
- const itemLines = this.renderListItem(item.tokens || [], depth);
61939
- if (itemLines.length > 0) {
61940
- const firstLine = itemLines[0];
61941
- const isNestedList = /^\s+\x1b\[36m[-\d]/.test(firstLine);
61942
- if (isNestedList) {
61943
- lines.push(firstLine);
61944
- } else {
61945
- lines.push(indent + this.theme.listBullet(bullet) + firstLine);
61946
- }
61947
- for (let j2 = 1; j2 < itemLines.length; j2++) {
61948
- const line = itemLines[j2];
61949
- const isNestedListLine = /^\s+\x1b\[36m[-\d]/.test(line);
61950
- if (isNestedListLine) {
61951
- lines.push(line);
61952
- } else {
61953
- lines.push(`${indent} ${line}`);
62117
+ const fragments = this.renderListItem(item.tokens || [], depth, styleContext, availableWidth);
62118
+ if (fragments.length > 0) {
62119
+ let isFirstFragment = true;
62120
+ for (const fragment of fragments) {
62121
+ switch (fragment.kind) {
62122
+ case "positioned-list":
62123
+ lines.push(fragment.text);
62124
+ break;
62125
+ case "table":
62126
+ if (isFirstFragment) {
62127
+ lines.push(indent + this.theme.listBullet(bullet));
62128
+ }
62129
+ lines.push(indent + fragment.text);
62130
+ break;
62131
+ default:
62132
+ if (isFirstFragment) {
62133
+ lines.push(indent + this.theme.listBullet(bullet) + fragment.text);
62134
+ } else {
62135
+ lines.push(`${indent} ${fragment.text}`);
62136
+ }
61954
62137
  }
62138
+ isFirstFragment = false;
61955
62139
  }
61956
62140
  } else {
61957
62141
  lines.push(indent + this.theme.listBullet(bullet));
@@ -61960,44 +62144,99 @@ var Markdown = class {
61960
62144
  return lines;
61961
62145
  }
61962
62146
  /**
61963
- * Render list item tokens, handling nested lists
61964
- * Returns lines WITHOUT the parent indent (renderList will add it)
62147
+ * Render list item tokens, handling nested lists.
62148
+ * Returns fragments WITHOUT the parent indent (renderList will add it); each
62149
+ * fragment carries layout provenance so the parent never has to guess from
62150
+ * the rendered string.
61965
62151
  */
61966
- renderListItem(tokens, parentDepth) {
61967
- const lines = [];
62152
+ renderListItem(tokens, parentDepth, styleContext, availableWidth) {
62153
+ const fragments = [];
62154
+ let pendingPrefix = "";
62155
+ const push = (text) => {
62156
+ if (text !== "") {
62157
+ fragments.push({ kind: "local-content", text: pendingPrefix + text });
62158
+ pendingPrefix = "";
62159
+ }
62160
+ };
61968
62161
  for (const token of tokens) {
61969
62162
  if (token.type === "list") {
61970
- const nestedLines = this.renderList(token, parentDepth + 1);
61971
- appendLines(lines, nestedLines);
62163
+ const nestedLines = this.renderList(
62164
+ token,
62165
+ parentDepth + 1,
62166
+ styleContext,
62167
+ availableWidth
62168
+ );
62169
+ for (const nestedLine of nestedLines) {
62170
+ fragments.push({ kind: "positioned-list", text: nestedLine });
62171
+ }
61972
62172
  } else if (token.type === "text") {
61973
- const text = token.tokens && token.tokens.length > 0 ? this.renderInlineTokens(token.tokens) : token.text || "";
61974
- lines.push(text);
62173
+ const text = token.tokens && token.tokens.length > 0 ? this.renderInlineTokens(token.tokens, styleContext) : token.text || "";
62174
+ push(text);
61975
62175
  } else if (token.type === "paragraph") {
61976
- const text = this.renderInlineTokens(token.tokens || []);
61977
- lines.push(text);
62176
+ const text = this.renderInlineTokens(token.tokens || [], styleContext);
62177
+ push(text);
61978
62178
  } else if (token.type === "code") {
61979
62179
  const indent = this.theme.codeBlockIndent ?? " ";
61980
- lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
62180
+ push(this.theme.codeBlockBorder(`\`\`\`${token.lang || ""}`));
61981
62181
  if (this.theme.highlightCode) {
61982
62182
  const highlightedLines = this.theme.highlightCode(token.text, token.lang);
61983
62183
  for (const hlLine of highlightedLines) {
61984
- lines.push(`${indent}${hlLine}`);
62184
+ push(`${indent}${hlLine}`);
61985
62185
  }
61986
62186
  } else {
61987
62187
  const codeLines = token.text.split("\n");
61988
62188
  for (const codeLine of codeLines) {
61989
- lines.push(`${indent}${this.theme.codeBlock(codeLine)}`);
62189
+ push(`${indent}${this.theme.codeBlock(codeLine)}`);
61990
62190
  }
61991
62191
  }
61992
- lines.push(this.theme.codeBlockBorder("```"));
62192
+ push(this.theme.codeBlockBorder("```"));
62193
+ } else if (token.type === "table") {
62194
+ if (availableWidth !== void 0) {
62195
+ const tableWidth = Math.max(1, availableWidth - " ".repeat(parentDepth).length);
62196
+ const tableLines = this.renderTable(token, tableWidth);
62197
+ for (const tableLine of tableLines) {
62198
+ if (tableLine !== "") {
62199
+ fragments.push({ kind: "table", text: tableLine });
62200
+ }
62201
+ }
62202
+ } else if ("raw" in token && typeof token.raw === "string") {
62203
+ for (const rawLine of token.raw.split("\n")) {
62204
+ push(rawLine);
62205
+ }
62206
+ }
62207
+ } else if (token.type === "blockquote") {
62208
+ const quoteWidth = availableWidth !== void 0 ? Math.max(1, availableWidth - " ".repeat(parentDepth + 1).length - 2) : void 0;
62209
+ if (quoteWidth !== void 0) {
62210
+ const quoteLines = this.renderBlockquote(token, quoteWidth, styleContext);
62211
+ for (const quoteLine of quoteLines) {
62212
+ if (quoteLine !== "") {
62213
+ fragments.push({ kind: "local-content", text: quoteLine });
62214
+ }
62215
+ }
62216
+ } else if ("text" in token && typeof token.text === "string") {
62217
+ push(token.text);
62218
+ }
62219
+ } else if (token.type === "heading") {
62220
+ const headingText = this.renderInlineTokens(token.tokens || [], styleContext);
62221
+ push(this.theme.bold(headingText));
62222
+ } else if (token.type === "space") {
62223
+ fragments.push({ kind: "local-content", text: "" });
62224
+ } else if (token.type === "hr") {
62225
+ const ruleWidth = availableWidth !== void 0 ? Math.min(availableWidth, 40) : 40;
62226
+ push(this.theme.hr("\u2500".repeat(ruleWidth)));
62227
+ } else if (token.type === "checkbox") {
62228
+ pendingPrefix += token.checked ? "[x] " : "[ ] ";
61993
62229
  } else {
61994
- const text = this.renderInlineTokens([token]);
62230
+ const text = this.renderInlineTokens([token], styleContext);
61995
62231
  if (text) {
61996
- lines.push(text);
62232
+ push(text);
61997
62233
  }
61998
62234
  }
61999
62235
  }
62000
- return lines;
62236
+ if (pendingPrefix !== "") {
62237
+ fragments.push({ kind: "local-content", text: pendingPrefix });
62238
+ }
62239
+ return fragments;
62001
62240
  }
62002
62241
  /**
62003
62242
  * Get the visible width of the longest word in a string.
@@ -63193,16 +63432,16 @@ var ExtensionRunner = class {
63193
63432
  uiContext;
63194
63433
  actions;
63195
63434
  contextActions;
63196
- hasUI;
63435
+ capabilities;
63197
63436
  /** Unregister handles created through this runner, revoked on reload/teardown. */
63198
63437
  unregisterHandles = [];
63199
63438
  disposal;
63200
63439
  resources = new ExtensionResourceScope();
63201
- constructor(extensions, actions, contextActions, hasUI = true) {
63440
+ constructor(extensions, actions, contextActions, capabilities = interactiveHostCapabilities()) {
63202
63441
  this.extensions = extensions;
63203
63442
  this.actions = actions;
63204
63443
  this.contextActions = contextActions;
63205
- this.hasUI = hasUI;
63444
+ this.capabilities = capabilities;
63206
63445
  this.uiContext = this.createNoOpUIContext();
63207
63446
  }
63208
63447
  /**
@@ -63223,11 +63462,11 @@ var ExtensionRunner = class {
63223
63462
  };
63224
63463
  }
63225
63464
  /**
63226
- * Set the UI context for interactive mode. Does NOT change hasUI: the
63227
- * constructor's hasUI argument (host-provided: true for interactive, false
63228
- * for print/json-events no-op contexts) is the single source of truth.
63229
- * Flipping it here used to make headless hosts report ctx.hasUI === true
63230
- * 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.
63231
63470
  */
63232
63471
  setUIContext(uiContext) {
63233
63472
  this.uiContext = uiContext;
@@ -63326,7 +63565,8 @@ var ExtensionRunner = class {
63326
63565
  request: (request) => requestInteraction(request),
63327
63566
  isAvailable: () => hasInteractionHandler()
63328
63567
  },
63329
- hasUI: this.hasUI,
63568
+ capabilities: this.capabilities,
63569
+ hasUI: this.capabilities.interactiveUI,
63330
63570
  cwd: this.actions.cwd,
63331
63571
  log: (message) => {
63332
63572
  if (process.env.PIE_VERBOSE) {
@@ -67571,7 +67811,7 @@ var FFmpegProcessor = class {
67571
67811
  // ============================================================================
67572
67812
  async checkAvailability() {
67573
67813
  return new Promise((resolve8) => {
67574
- const proc = spawn2(this.ffmpegPath, ["-version"]);
67814
+ const proc = spawn2(this.ffmpegPath, ["-version"], { windowsHide: true });
67575
67815
  proc.on("error", () => resolve8(false));
67576
67816
  proc.on("exit", (code) => resolve8(code === 0));
67577
67817
  });
@@ -67592,7 +67832,7 @@ var FFmpegProcessor = class {
67592
67832
  "json",
67593
67833
  videoPath
67594
67834
  ];
67595
- const proc = spawn2(this.ffprobePath, args);
67835
+ const proc = spawn2(this.ffprobePath, args, { windowsHide: true });
67596
67836
  let stdout = "";
67597
67837
  let stderr = "";
67598
67838
  proc.stdout.on("data", (data) => stdout += data);
@@ -67805,7 +68045,7 @@ var FFmpegProcessor = class {
67805
68045
  // ============================================================================
67806
68046
  runFFmpeg(args) {
67807
68047
  return new Promise((resolve8, reject) => {
67808
- const proc = spawn2(this.ffmpegPath, args);
68048
+ const proc = spawn2(this.ffmpegPath, args, { windowsHide: true });
67809
68049
  let stderr = "";
67810
68050
  proc.stderr.on("data", (data) => {
67811
68051
  stderr += data;
@@ -67842,7 +68082,7 @@ var FFmpegProcessor = class {
67842
68082
  "-progress",
67843
68083
  "pipe:1"
67844
68084
  ];
67845
- const proc = spawn2(this.ffmpegPath, progressArgs);
68085
+ const proc = spawn2(this.ffmpegPath, progressArgs, { windowsHide: true });
67846
68086
  let stderr = "";
67847
68087
  let progressData = "";
67848
68088
  proc.stdout.on("data", (data) => {
@@ -70906,6 +71146,98 @@ var TreeSelectorComponent = class {
70906
71146
  };
70907
71147
 
70908
71148
  // src/components/assistant-message.ts
71149
+ var STREAMING_SPLIT_MIN_CHARS = 256;
71150
+ var STREAMING_TAIL_MAX_CHARS = 8192;
71151
+ function matchOpenFence(line) {
71152
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
71153
+ if (!match) return null;
71154
+ const run = match[1];
71155
+ const rest = match[2] ?? "";
71156
+ if (run[0] === "`" && rest.includes("`")) return null;
71157
+ return { char: run[0], length: run.length };
71158
+ }
71159
+ function isCloseFence(line, fence) {
71160
+ const match = /^ {0,3}(`+|~+)[ \t]*$/.exec(line);
71161
+ if (!match) return false;
71162
+ const run = match[1];
71163
+ return run[0] === fence.char && run.length >= fence.length;
71164
+ }
71165
+ function isBoundarySafeSplit(nextLine) {
71166
+ if (nextLine.trim() === "") return false;
71167
+ if (/^(\t| +)/.test(nextLine)) return false;
71168
+ if (/^\s*([-*+]|\d{1,9}[.)])\s/.test(nextLine)) return false;
71169
+ if (/^\s*</.test(nextLine)) return false;
71170
+ return true;
71171
+ }
71172
+ var RAW_HTML_UNTIL_CLOSED = /* @__PURE__ */ new Set(["script", "pre", "style", "textarea"]);
71173
+ function htmlBlockStateAt(line) {
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 };
71178
+ }
71179
+ const match = /^ {0,3}<([a-zA-Z][a-zA-Z0-9-]*)/.exec(line);
71180
+ if (!match) return null;
71181
+ const tag = match[1].toLowerCase();
71182
+ if (!RAW_HTML_UNTIL_CLOSED.has(tag)) return { kind: "blank" };
71183
+ return new RegExp(`</${tag}\\s*>`).test(line) ? null : { kind: "tag", tag };
71184
+ }
71185
+ function closesHtmlBlock(line, state) {
71186
+ if (state.kind === "delimiter") return line.includes(state.close);
71187
+ if (state.kind === "tag") {
71188
+ return new RegExp(`^ {0,3}</${state.tag}\\s*>?(\\s|$)`).test(line);
71189
+ }
71190
+ return false;
71191
+ }
71192
+ function findStablePrefixEnd(text, scanStart) {
71193
+ const rawOffset = scanStart === 0 ? text.length - text.trimStart().length : 0;
71194
+ let fence = null;
71195
+ let html = null;
71196
+ let lastSafe = scanStart - 1;
71197
+ let pos = scanStart || rawOffset;
71198
+ let candidateBlankAt = -1;
71199
+ while (pos < text.length) {
71200
+ const lineEnd = text.indexOf("\n", pos);
71201
+ const line = lineEnd < 0 ? text.slice(pos) : text.slice(pos, lineEnd);
71202
+ const next = lineEnd < 0 ? text.length + 1 : lineEnd + 1;
71203
+ if (fence !== null) {
71204
+ if (isCloseFence(line, fence)) {
71205
+ fence = null;
71206
+ candidateBlankAt = -1;
71207
+ }
71208
+ } else if (html !== null) {
71209
+ if (html.kind === "blank") {
71210
+ if (line.trim() === "") html = null;
71211
+ } else if (closesHtmlBlock(line, html)) {
71212
+ html = null;
71213
+ }
71214
+ candidateBlankAt = -1;
71215
+ } else {
71216
+ const open = /^ {0,3}(`{3,}|~{3,})/.test(line) ? matchOpenFence(line) : null;
71217
+ const htmlState = line.trim() !== "" ? htmlBlockStateAt(line) : null;
71218
+ if (open) {
71219
+ fence = open;
71220
+ candidateBlankAt = -1;
71221
+ } else if (line.trim() === "") {
71222
+ candidateBlankAt = lineEnd >= 0 ? lineEnd : text.length - 1;
71223
+ } else if (htmlState) {
71224
+ html = htmlState;
71225
+ candidateBlankAt = -1;
71226
+ } else if (candidateBlankAt >= 0) {
71227
+ if (lineEnd >= 0 && isBoundarySafeSplit(line)) lastSafe = candidateBlankAt;
71228
+ candidateBlankAt = -1;
71229
+ }
71230
+ }
71231
+ pos = next;
71232
+ }
71233
+ if (lastSafe >= 0 && lastSafe + 1 >= STREAMING_SPLIT_MIN_CHARS) {
71234
+ return lastSafe + 1;
71235
+ }
71236
+ return -1;
71237
+ }
71238
+ function hasVisibleContentAfter(content, index) {
71239
+ return content.slice(index + 1).some((c) => c.type === "text" && c.text.trim() || c.type === "thinking" && c.thinking.trim());
71240
+ }
70909
71241
  var AssistantMessageComponent = class extends Container {
70910
71242
  contentContainer;
70911
71243
  hideThinkingBlock;
@@ -70916,6 +71248,15 @@ var AssistantMessageComponent = class extends Container {
70916
71248
  highlightCache = /* @__PURE__ */ new Map();
70917
71249
  usedHighlightKeys = /* @__PURE__ */ new Set();
70918
71250
  pruneHighlightCache = false;
71251
+ /** Streaming stable-prefix reuse (see tryStreamingSplitRebuild): a chain of
71252
+ * frozen Markdown chunks plus the text they cover. Advancing appends a new
71253
+ * chunk (renders only the NEW text) instead of re-rendering one growing
71254
+ * component, so an advance is O(chunk) at any message size. Text blocks
71255
+ * only: thinking content is usually hidden or restyled and stays on the
71256
+ * full-render path. */
71257
+ stablePrefix = "";
71258
+ stablePrefixChunks = [];
71259
+ stablePrefixKind = null;
70919
71260
  constructor(message, hideThinkingBlock = false, markdownTheme = getMarkdownTheme()) {
70920
71261
  super();
70921
71262
  this.hideThinkingBlock = hideThinkingBlock;
@@ -70945,6 +71286,9 @@ var AssistantMessageComponent = class extends Container {
70945
71286
  invalidate() {
70946
71287
  this.highlightCache.clear();
70947
71288
  this.usedHighlightKeys.clear();
71289
+ this.stablePrefixChunks = [];
71290
+ this.stablePrefix = "";
71291
+ this.stablePrefixKind = null;
70948
71292
  super.invalidate();
70949
71293
  if (this.lastMessage) {
70950
71294
  this.updateContent(this.lastMessage);
@@ -70968,9 +71312,20 @@ var AssistantMessageComponent = class extends Container {
70968
71312
  return this.calmMode;
70969
71313
  }
70970
71314
  /** The final frame may reuse streamed highlights; afterwards only the
70971
- * Markdown line cache is needed, so release the duplicate code strings. */
71315
+ * Markdown line cache is needed, so release the duplicate code strings.
71316
+ * Terminal paths (message_end, hard errors, interrupts) call this at
71317
+ * different points relative to the last updateContent — some BEFORE any
71318
+ * final update, some after one that still carried streaming=true and took
71319
+ * the split path. Always rebuild the full layout here so the committed
71320
+ * frame is byte-identical to the non-streaming renderer. */
70972
71321
  finalizeStreaming() {
70973
71322
  this.streaming = false;
71323
+ this.stablePrefixChunks = [];
71324
+ this.stablePrefix = "";
71325
+ this.stablePrefixKind = null;
71326
+ if (this.lastMessage) {
71327
+ this.updateContent(this.lastMessage);
71328
+ }
70974
71329
  }
70975
71330
  render(width) {
70976
71331
  this.usedHighlightKeys.clear();
@@ -70993,6 +71348,104 @@ var AssistantMessageComponent = class extends Container {
70993
71348
  this.usedHighlightKeys.clear();
70994
71349
  }
70995
71350
  }
71351
+ /** Spacer + frozen leading blocks shared by both streaming paths. */
71352
+ appendFrozenLeadingBlocks(message, lastEditableIndex, hasVisibleContent) {
71353
+ this.contentContainer.clear();
71354
+ if (hasVisibleContent) {
71355
+ this.contentContainer.addChild(new Spacer(1));
71356
+ }
71357
+ for (let i = 0; i < lastEditableIndex; i++) {
71358
+ const content = message.content[i];
71359
+ if (content.type === "text" && content.text.trim()) {
71360
+ this.contentContainer.addChild(new Markdown(content.text.trim(), 1, 0, this.markdownTheme));
71361
+ } else if (content.type === "thinking" && content.thinking.trim() && !this.calmMode) {
71362
+ this.contentContainer.addChild(this.createThinkingComponent(content.thinking, message.content, i));
71363
+ }
71364
+ }
71365
+ }
71366
+ /** Thinking block renderer shared by the streaming fast path and the full
71367
+ * rebuild, so both produce identical spacing and styling. `content`/`index`
71368
+ * only decide the trailing spacer (visible content after the block). */
71369
+ createThinkingComponent(thinking, content, index) {
71370
+ const wrapper = new Container();
71371
+ if (this.hideThinkingBlock) {
71372
+ wrapper.addChild(new Text(theme.italic(theme.fg("thinkingText", "Thinking...")), 1, 0));
71373
+ } else {
71374
+ wrapper.addChild(
71375
+ new Markdown(thinking.trim(), 1, 0, this.markdownTheme, {
71376
+ color: (text) => theme.fg("thinkingText", text),
71377
+ italic: true
71378
+ })
71379
+ );
71380
+ }
71381
+ if (content !== void 0 && index !== void 0 && hasVisibleContentAfter(content, index)) {
71382
+ wrapper.addChild(new Spacer(1));
71383
+ }
71384
+ return wrapper;
71385
+ }
71386
+ /** Streaming fast path: rebuild only the volatile tail each update.
71387
+ * Returns false when the message is final (or text too small to benefit),
71388
+ * in which case the caller falls through to the full rebuild. */
71389
+ tryStreamingSplitRebuild(message, hasVisibleContent) {
71390
+ if (!this.streaming) return false;
71391
+ if (message.stopReason !== void 0) return false;
71392
+ if (message.content.some((c) => c.type === "toolCall")) return false;
71393
+ let lastEditableIndex = -1;
71394
+ for (let i = message.content.length - 1; i >= 0; i--) {
71395
+ const c = message.content[i];
71396
+ if (c.type === "text" || c.type === "thinking") {
71397
+ lastEditableIndex = i;
71398
+ break;
71399
+ }
71400
+ }
71401
+ if (lastEditableIndex < 0) return false;
71402
+ const lastBlock = message.content[lastEditableIndex];
71403
+ if (lastBlock.type !== "text") return false;
71404
+ const fullText = lastBlock.text;
71405
+ if (fullText.length < STREAMING_SPLIT_MIN_CHARS) return false;
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);
71409
+ if (boundary < 0) return false;
71410
+ const prefix = fullText.slice(0, boundary);
71411
+ const tail = fullText.slice(boundary);
71412
+ if (!tail.trim()) return false;
71413
+ const prefixStillValid = chainStillApplies && fullText.length - scanStart <= STREAMING_TAIL_MAX_CHARS;
71414
+ if (prefixStillValid) {
71415
+ this.appendFrozenLeadingBlocks(message, lastEditableIndex, hasVisibleContent);
71416
+ for (const chunk of this.stablePrefixChunks) {
71417
+ this.contentContainer.addChild(chunk);
71418
+ }
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));
71423
+ }
71424
+ return true;
71425
+ }
71426
+ let advanceFrom = 0;
71427
+ if (chainStillApplies) {
71428
+ advanceFrom = this.stablePrefix.length;
71429
+ } else {
71430
+ this.stablePrefixChunks = [];
71431
+ this.stablePrefix = "";
71432
+ }
71433
+ this.appendFrozenLeadingBlocks(message, lastEditableIndex, hasVisibleContent);
71434
+ const newChunkText = advanceFrom === 0 ? prefix.trimStart() : prefix.slice(advanceFrom);
71435
+ if (newChunkText) {
71436
+ this.stablePrefixChunks.push(new Markdown(newChunkText, 1, 0, this.markdownTheme));
71437
+ }
71438
+ this.stablePrefix = prefix;
71439
+ this.stablePrefixKind = "text";
71440
+ for (const chunk of this.stablePrefixChunks) {
71441
+ this.contentContainer.addChild(chunk);
71442
+ }
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));
71446
+ }
71447
+ return true;
71448
+ }
70996
71449
  updateContent(message) {
70997
71450
  this.lastMessage = message;
70998
71451
  this.pruneHighlightCache = true;
@@ -71000,6 +71453,14 @@ var AssistantMessageComponent = class extends Container {
71000
71453
  const hasTextContent = message.content.some((c) => c.type === "text" && c.text.trim());
71001
71454
  const hasThinkingContent = message.content.some((c) => c.type === "thinking" && c.thinking.trim());
71002
71455
  const hasVisibleContent = this.calmMode ? hasTextContent : hasTextContent || hasThinkingContent;
71456
+ if (this.tryStreamingSplitRebuild(message, hasVisibleContent)) {
71457
+ return;
71458
+ }
71459
+ if (!this.streaming) {
71460
+ this.stablePrefixChunks = [];
71461
+ this.stablePrefix = "";
71462
+ this.stablePrefixKind = null;
71463
+ }
71003
71464
  if (hasVisibleContent) {
71004
71465
  this.contentContainer.addChild(new Spacer(1));
71005
71466
  }
@@ -71011,23 +71472,7 @@ var AssistantMessageComponent = class extends Container {
71011
71472
  if (this.calmMode) {
71012
71473
  continue;
71013
71474
  }
71014
- const hasVisibleContentAfter = message.content.slice(i + 1).some((c) => c.type === "text" && c.text.trim() || c.type === "thinking" && c.thinking.trim());
71015
- if (this.hideThinkingBlock) {
71016
- this.contentContainer.addChild(new Text(theme.italic(theme.fg("thinkingText", "Thinking...")), 1, 0));
71017
- if (hasVisibleContentAfter) {
71018
- this.contentContainer.addChild(new Spacer(1));
71019
- }
71020
- } else {
71021
- this.contentContainer.addChild(
71022
- new Markdown(content.thinking.trim(), 1, 0, this.markdownTheme, {
71023
- color: (text) => theme.fg("thinkingText", text),
71024
- italic: true
71025
- })
71026
- );
71027
- if (hasVisibleContentAfter) {
71028
- this.contentContainer.addChild(new Spacer(1));
71029
- }
71030
- }
71475
+ this.contentContainer.addChild(this.createThinkingComponent(content.thinking, message.content, i));
71031
71476
  }
71032
71477
  }
71033
71478
  const hasToolCalls = message.content.some((c) => c.type === "toolCall");
@@ -71930,7 +72375,8 @@ async function handleResumeCommand(host) {
71930
72375
  const child = spawn3(process.execPath, [...process.execArgv, process.argv[1] ?? ".", ...decision.childArgv], {
71931
72376
  cwd: decision.targetCwd,
71932
72377
  stdio: "inherit",
71933
- env: buildChildEnv(decision.childEnv)
72378
+ env: buildChildEnv(decision.childEnv),
72379
+ windowsHide: true
71934
72380
  });
71935
72381
  child.on("spawn", () => announce());
71936
72382
  child.on("exit", (code, signal) => {
@@ -72081,9 +72527,10 @@ function noteToolExecutionEnd(host, toolCallId) {
72081
72527
  function clearRunningToolExecutions(host) {
72082
72528
  runningToolExecutions.get(host)?.clear();
72083
72529
  }
72084
- function hasRunningToolWork(host) {
72085
- const set = runningToolExecutions.get(host);
72086
- return set !== void 0 && set.size > 0;
72530
+ function hasRunningTitleWork(host) {
72531
+ const recovery = host.agentSessionController?.turnRecoveryState;
72532
+ const tools = runningToolExecutions.get(host);
72533
+ return host.agent?.state?.isStreaming === true || host.isCompacting === true || recovery === "retry_pending" || recovery === "retrying" || recovery === "compacting" || tools !== void 0 && tools.size > 0;
72087
72534
  }
72088
72535
  var explicitSubmitLockHosts = /* @__PURE__ */ new WeakSet();
72089
72536
  var controllerBusyHosts = /* @__PURE__ */ new WeakSet();
@@ -72137,7 +72584,7 @@ function startTitleSpinner(host) {
72137
72584
  let stalled = false;
72138
72585
  titleActivityStamps.set(host, Date.now());
72139
72586
  const timer = setInterval(() => {
72140
- if (hasRunningToolWork(host)) titleActivityStamps.set(host, Date.now());
72587
+ if (hasRunningTitleWork(host)) titleActivityStamps.set(host, Date.now());
72141
72588
  const lastActivity = titleActivityStamps.get(host);
72142
72589
  if (lastActivity !== void 0 && Date.now() - lastActivity > TITLE_BUSY_STALL_MS) {
72143
72590
  if (!stalled) {
@@ -75840,6 +76287,7 @@ function createExtensionContextForCommands(host) {
75840
76287
  request: (request) => requestInteraction(request),
75841
76288
  isAvailable: () => hasInteractionHandler()
75842
76289
  },
76290
+ capabilities: interactiveHostCapabilities(),
75843
76291
  hasUI: true,
75844
76292
  cwd: process.cwd(),
75845
76293
  log: (msg) => {
@@ -76583,7 +77031,7 @@ async function handleCompactCommand(host) {
76583
77031
  });
76584
77032
  const compactedMessages = host.sessionManager.getMessages();
76585
77033
  host.replaceAgentMessagesAndMarkSynced(compactedMessages);
76586
- host.resetFileObservationState();
77034
+ host.resetFileObservationState("manual /compact");
76587
77035
  host.resetRuntimeModeBlocks?.();
76588
77036
  host.streamingComponent = void 0;
76589
77037
  host.pendingTools.clear();
@@ -80918,7 +81366,7 @@ function createInteractiveAgentSessionController(host) {
80918
81366
  host.footer.setState({ status: "processing", lifecycleEvent: "auto_compact" });
80919
81367
  host.showStatus(event.reason === "overflow" ? "Context overflow detected, compacting..." : "Auto-compacting context...");
80920
81368
  } else if (event.type === "compaction_committed") {
80921
- host.resetFileObservationState();
81369
+ host.resetFileObservationState(`auto compaction (${event.reason})`);
80922
81370
  host.resetRuntimeModeBlocks?.();
80923
81371
  host.sessionTrace.noteRuntimeEvent("compaction_committed", {
80924
81372
  reason: event.reason,
@@ -81198,7 +81646,8 @@ async function handleDirectBash(host, command) {
81198
81646
  const { spawn: spawn5 } = await import("child_process");
81199
81647
  const child = spawn5(shellCommand.file, shellCommand.args, {
81200
81648
  cwd: process.cwd(),
81201
- env: process.env
81649
+ env: process.env,
81650
+ windowsHide: true
81202
81651
  });
81203
81652
  const output = new DirectBashOutputCollector();
81204
81653
  child.stdout.on("data", (data) => {
@@ -81798,8 +82247,9 @@ function beginUserInput(host, extensionIsCurrent = () => true) {
81798
82247
  const session = host.sessionManager.getActiveSession();
81799
82248
  const controller = host.agentSessionController;
81800
82249
  const runner = host.extensionRunner;
81801
- const handler = host.attachmentMentionHandler?.();
81802
- 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;
81803
82253
  let retired = false;
81804
82254
  let used = false;
81805
82255
  const unsubscribe = controller.subscribe((event) => {
@@ -81809,7 +82259,7 @@ function beginUserInput(host, extensionIsCurrent = () => true) {
81809
82259
  retired = true;
81810
82260
  unsubscribe();
81811
82261
  });
81812
- 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();
81813
82263
  return {
81814
82264
  isCurrent,
81815
82265
  dispose,
@@ -81820,7 +82270,8 @@ function beginUserInput(host, extensionIsCurrent = () => true) {
81820
82270
  const mentions = [];
81821
82271
  for (const file of files) {
81822
82272
  if (!isCurrent()) return false;
81823
- 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);
81824
82275
  if (!mention || !isCurrent()) return false;
81825
82276
  mentions.push(mention.trim());
81826
82277
  }
@@ -81973,7 +82424,7 @@ async function loadInteractiveExtensions(host) {
81973
82424
  host.extensionUIContext,
81974
82425
  () => host.abortAgent(),
81975
82426
  () => !host.isProcessing,
81976
- true,
82427
+ interactiveHostCapabilities(),
81977
82428
  extensionActions,
81978
82429
  buildExtensionLoadOptions(host.options.settingsManager, host.options.extensionFlags)
81979
82430
  );
@@ -81983,7 +82434,7 @@ async function loadInteractiveExtensions(host) {
81983
82434
  extensions,
81984
82435
  extensionActions,
81985
82436
  contextActions,
81986
- true
82437
+ interactiveHostCapabilities()
81987
82438
  );
81988
82439
  host.extensionRunner.setUIContext(host.extensionUIContext);
81989
82440
  await restoreExtensionProviderCredentials(host.options.modelRegistry);
@@ -82350,8 +82801,8 @@ var InteractiveMode = class {
82350
82801
  getPolicyContext: this.getPolicyContext
82351
82802
  };
82352
82803
  }
82353
- resetFileObservationState() {
82354
- this.options.fileObservationState.clear();
82804
+ resetFileObservationState(reason) {
82805
+ this.options.fileObservationState.clear(reason);
82355
82806
  }
82356
82807
  getRuntimeModeState() {
82357
82808
  const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "local";
@@ -82466,7 +82917,7 @@ var InteractiveMode = class {
82466
82917
  async init() {
82467
82918
  const activeSession = this.sessionManager.getActiveSession();
82468
82919
  this.thinkingLevel = resolveInitialThinkingLevel({ session: activeSession, settingsManager: this.options.settingsManager });
82469
- const { Agent } = await import("./chunks/src-YG5M2H44.js");
82920
+ const { Agent } = await import("./chunks/src-ODLT57PQ.js");
82470
82921
  this.agent = new Agent({
82471
82922
  initialState: {
82472
82923
  systemPrompt: this.buildSystemPrompt(),
@@ -83324,7 +83775,7 @@ async function loadPrintModeExtensions(params) {
83324
83775
  uiContext,
83325
83776
  () => params.getAgent()?.abort(),
83326
83777
  () => true,
83327
- false,
83778
+ oneShotHeadlessCapabilities(),
83328
83779
  actions,
83329
83780
  buildExtensionLoadOptions(params.settingsManager, params.extensionFlags, params.cwd)
83330
83781
  );
@@ -83335,7 +83786,7 @@ async function loadPrintModeExtensions(params) {
83335
83786
  isIdle: () => true,
83336
83787
  abort: () => params.getAgent()?.abort()
83337
83788
  },
83338
- false
83789
+ oneShotHeadlessCapabilities()
83339
83790
  );
83340
83791
  runner.setUIContext(uiContext);
83341
83792
  await restoreExtensionProviderCredentials(params.modelRegistry);
@@ -83364,7 +83815,7 @@ async function runPrintMode(params) {
83364
83815
  `);
83365
83816
  console.log("Assistant: ");
83366
83817
  }
83367
- const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
83818
+ const { Agent: AgentClass } = await import("./chunks/src-ODLT57PQ.js");
83368
83819
  let agent;
83369
83820
  const printModeExtensions = await loadPrintModeExtensions({
83370
83821
  cwd: runtime.cwd,
@@ -83474,7 +83925,7 @@ async function runPrintMode(params) {
83474
83925
  } else if (event.type === "auto_compaction_start") {
83475
83926
  console.error(event.reason === "overflow" ? "Context overflow detected, compacting..." : "Auto-compacting context...");
83476
83927
  } else if (event.type === "compaction_committed") {
83477
- runtime.fileObservationState.clear();
83928
+ runtime.fileObservationState.clear(`auto compaction (${event.reason})`);
83478
83929
  } else {
83479
83930
  reportRetryStatus(event);
83480
83931
  }
@@ -83574,7 +84025,16 @@ var FULL_DETAIL = "full";
83574
84025
  var COMPACT_DETAIL = "compact";
83575
84026
  function createNoOpExtensionUIContext2() {
83576
84027
  return {
83577
- 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
+ });
83578
84038
  },
83579
84039
  select: async () => void 0,
83580
84040
  confirm: async () => false,
@@ -83583,6 +84043,10 @@ function createNoOpExtensionUIContext2() {
83583
84043
  custom: async () => void 0
83584
84044
  };
83585
84045
  }
84046
+ process.stdout.on("error", (error) => {
84047
+ if (error.code === "EPIPE") return;
84048
+ throw error;
84049
+ });
83586
84050
  function writeEvent(event) {
83587
84051
  process.stdout.write(`${JSON.stringify(event)}
83588
84052
  `);
@@ -83592,7 +84056,8 @@ function toJsonValue(value, depth = 0, cap = MAX_EVENT_STRING_LENGTH) {
83592
84056
  if (typeof value === "string") {
83593
84057
  return value.length > cap ? value.slice(0, cap) : value;
83594
84058
  }
83595
- if (typeof value === "number") return Number.isFinite(value) ? value : String(value);
84059
+ if (typeof value === "number")
84060
+ return Number.isFinite(value) ? value : String(value);
83596
84061
  if (typeof value === "boolean") return value;
83597
84062
  if (typeof value === "bigint") return value.toString();
83598
84063
  if (typeof value !== "object") return void 0;
@@ -83601,7 +84066,10 @@ function toJsonValue(value, depth = 0, cap = MAX_EVENT_STRING_LENGTH) {
83601
84066
  return value.slice(0, MAX_EVENT_ARRAY_ITEMS).map((item) => toJsonValue(item, depth + 1, cap) ?? null);
83602
84067
  }
83603
84068
  const result = {};
83604
- 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
+ )) {
83605
84073
  result[key] = toJsonValue(item, depth + 1, cap);
83606
84074
  }
83607
84075
  return result;
@@ -83613,7 +84081,11 @@ function truncateForEvent(text, cap) {
83613
84081
  if (text.length <= cap) {
83614
84082
  return { value: text, truncated: false, fullLength: text.length };
83615
84083
  }
83616
- 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
+ };
83617
84089
  }
83618
84090
  function hasOversizedValue(value, cap, depth = 0) {
83619
84091
  if (typeof value === "string") return value.length > cap;
@@ -83634,7 +84106,10 @@ function parseInput(line) {
83634
84106
  }
83635
84107
  if (!isRecord3(parsed) || typeof parsed.type !== "string") return null;
83636
84108
  if (parsed.type === "shutdown") {
83637
- 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
+ };
83638
84113
  }
83639
84114
  if (parsed.type === "turn.interrupt") {
83640
84115
  return {
@@ -83716,7 +84191,8 @@ function assistantErrorFromAgent(agent) {
83716
84191
  const messages = agent?.state.messages ?? [];
83717
84192
  const lastMessage = messages[messages.length - 1];
83718
84193
  if (lastMessage?.role !== "assistant") return "";
83719
- if (lastMessage.stopReason !== "error" && lastMessage.stopReason !== "aborted") return "";
84194
+ if (lastMessage.stopReason !== "error" && lastMessage.stopReason !== "aborted")
84195
+ return "";
83720
84196
  return lastMessage.errorMessage || "assistant response failed";
83721
84197
  }
83722
84198
  function readProgressText(value) {
@@ -83728,7 +84204,9 @@ function extractJsonEventsToolProgressText(partialResult) {
83728
84204
  if (!isRecord3(partialResult)) return "";
83729
84205
  const content = partialResult.content;
83730
84206
  if (Array.isArray(content)) {
83731
- 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();
83732
84210
  }
83733
84211
  const directText = readProgressText(partialResult.text) || readProgressText(partialResult.message);
83734
84212
  if (directText) return directText.trim();
@@ -83738,21 +84216,84 @@ function extractJsonEventsToolProgressText(partialResult) {
83738
84216
  }
83739
84217
  return "";
83740
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
+ }
83741
84250
  async function loadJsonModeExtensions(params) {
83742
84251
  const uiContext = createNoOpExtensionUIContext2();
83743
84252
  const executionState = new ExecutionStateManager();
83744
84253
  const activeSession = params.runtime.sessionManager.getActiveSession();
83745
84254
  executionState.restoreFromMetadata(activeSession?.metadata?.executionState);
83746
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
+ };
83747
84263
  const actions = {
83748
84264
  setActiveTools: (toolNames) => {
83749
84265
  const agent = params.getAgent();
83750
84266
  if (!agent) return;
83751
84267
  const toolList = availableTools.length > 0 ? availableTools : agent.state.tools;
83752
- agent.state.tools = toolList.filter((tool) => toolNames.includes(tool.name));
84268
+ agent.state.tools = toolList.filter(
84269
+ (tool) => toolNames.includes(tool.name)
84270
+ );
83753
84271
  },
83754
84272
  getActiveTools: () => params.getAgent()?.state.tools.map((tool) => tool.name) ?? [],
83755
- 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);
83756
84297
  },
83757
84298
  setPlanMode: () => {
83758
84299
  },
@@ -83789,11 +84330,74 @@ async function loadJsonModeExtensions(params) {
83789
84330
  parameters: tool.parameters
83790
84331
  })),
83791
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
+ },
83792
84382
  resolveModelClass: (modelClass) => params.runtime.modelRegistry.resolveModelClass(modelClass),
83793
84383
  resolveModelRef: (modelRef) => params.runtime.modelRegistry.resolveModelRef(modelRef),
83794
84384
  registerHostEnvelopeProjector: (projector) => registerExternalHostEnvelopeProjector(projector, params.envelopeRegistry),
83795
84385
  getMessages: () => params.getAgent()?.state.messages ?? [],
83796
- 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
+ }),
83797
84401
  setSessionMetadata: (key, value) => {
83798
84402
  const session = params.runtime.sessionManager.getActiveSession();
83799
84403
  if (!session) return;
@@ -83808,9 +84412,13 @@ async function loadJsonModeExtensions(params) {
83808
84412
  uiContext,
83809
84413
  () => params.getAgent()?.abort(),
83810
84414
  () => true,
83811
- false,
84415
+ embeddedHostCapabilities(),
83812
84416
  actions,
83813
- 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
+ )
83814
84422
  );
83815
84423
  const runner = new ExtensionRunner(
83816
84424
  extensions,
@@ -83819,12 +84427,15 @@ async function loadJsonModeExtensions(params) {
83819
84427
  isIdle: () => true,
83820
84428
  abort: () => params.getAgent()?.abort()
83821
84429
  },
83822
- false
84430
+ embeddedHostCapabilities()
83823
84431
  );
84432
+ runnerCell.current = runner;
83824
84433
  runner.setUIContext(uiContext);
83825
84434
  if (errors.length) {
83826
84435
  await runner.dispose("shutdown");
83827
- 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
+ );
83828
84439
  }
83829
84440
  try {
83830
84441
  await restoreExtensionProviderCredentials(params.runtime.modelRegistry);
@@ -83849,10 +84460,25 @@ async function runJsonEventsMode(params) {
83849
84460
  let agent;
83850
84461
  let controller;
83851
84462
  let disposeAgentSubscription;
84463
+ let disposeAgentRawSubscription;
83852
84464
  let disposeSemanticSubscription;
83853
84465
  let trace;
83854
84466
  let extensionRunner;
83855
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
+ }
83856
84482
  let mockActiveEntryId;
83857
84483
  let thinkingLevel = DEFAULT_THINKING_LEVEL;
83858
84484
  let thinkingLevelInitialized = false;
@@ -83861,16 +84487,47 @@ async function runJsonEventsMode(params) {
83861
84487
  let publishRecoveryDone = false;
83862
84488
  const completedSessionControlRequests = /* @__PURE__ */ new Map();
83863
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
+ });
83864
84512
  const ensureRuntimeInFlight = /* @__PURE__ */ new Map();
83865
84513
  let compositionChain = Promise.resolve();
83866
84514
  let runtimeClosing = false;
84515
+ let compositionGeneration = 0;
83867
84516
  let activeSidechat = null;
83868
84517
  let activeSidechatPromise = null;
83869
84518
  let sidechatChainStopped = false;
83870
- const noProgressTimeoutMs = Number(process.env.PIE_JSON_EVENTS_NO_PROGRESS_MS || 6e5);
83871
- const mockResponseDelayMs = Number(process.env.PIE_TEST_MOCK_RESPONSE_DELAY_MS || 0);
83872
- const prewarmTimeoutMs = Number(process.env.PIE_JSON_EVENTS_PREWARM_TIMEOUT_MS || 1e4);
83873
- 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
+ );
83874
84531
  await prewarmRuntime();
83875
84532
  writeEvent({
83876
84533
  type: "agent.ready",
@@ -83932,7 +84589,15 @@ async function runJsonEventsMode(params) {
83932
84589
  const metadata = {};
83933
84590
  if (existing) {
83934
84591
  for (const [key, value] of Object.entries(existing)) {
83935
- 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)) {
83936
84601
  continue;
83937
84602
  }
83938
84603
  metadata[key] = value;
@@ -83955,13 +84620,23 @@ async function runJsonEventsMode(params) {
83955
84620
  const targetSessionId = message.sessionId ?? sessionId;
83956
84621
  const status = store.headStatus(targetSessionId);
83957
84622
  if (status === "legacy") {
83958
- 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
+ );
83959
84627
  }
83960
84628
  if (status === "corrupt") {
83961
- 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
+ );
83962
84633
  }
83963
84634
  const existing = store.readHead(targetSessionId);
83964
- 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
+ });
83965
84640
  const startedAt = activeTurn?.startedAt ?? Date.now();
83966
84641
  const baseSeq = existing?.committedSeq ?? store.readHead(targetSessionId)?.committedSeq ?? 0;
83967
84642
  const userEntryId = generateEntryId(baseSeq + 1);
@@ -84010,7 +84685,12 @@ async function runJsonEventsMode(params) {
84010
84685
  targetSessionId,
84011
84686
  [userEntry, assistantEntry],
84012
84687
  assistantEntryId,
84013
- 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
+ )
84014
84694
  );
84015
84695
  return assistantEntryId;
84016
84696
  }
@@ -84061,13 +84741,26 @@ async function runJsonEventsMode(params) {
84061
84741
  return normalized;
84062
84742
  }
84063
84743
  function requireSessionControlBase(message) {
84064
- const requestedSessionId = requireSessionControlString(message.sessionId, "sessionId");
84065
- 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
+ );
84066
84752
  if (requestedSessionId !== sessionId) {
84067
- throw new SessionControlError("session_mismatch", sessionMismatchError(requestedSessionId), false);
84753
+ throw new SessionControlError(
84754
+ "session_mismatch",
84755
+ sessionMismatchError(requestedSessionId),
84756
+ false
84757
+ );
84068
84758
  }
84069
84759
  if (activeTurn && !activeTurn.finalized) {
84070
- 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
+ );
84071
84764
  }
84072
84765
  return { sessionId: requestedSessionId, requestId };
84073
84766
  }
@@ -84079,7 +84772,10 @@ async function runJsonEventsMode(params) {
84079
84772
  return entryId;
84080
84773
  }
84081
84774
  function writeSessionControlFailure(message, operation, error) {
84082
- 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
+ );
84083
84779
  writeEvent({
84084
84780
  type: "session.failed",
84085
84781
  sessionId: message.sessionId || sessionId,
@@ -84095,13 +84791,19 @@ async function runJsonEventsMode(params) {
84095
84791
  try {
84096
84792
  await runtime.sessionManager.save();
84097
84793
  } catch (error) {
84098
- 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
+ );
84099
84798
  }
84100
84799
  }
84101
84800
  async function syncRuntimeAfterRewind(controlSessionId) {
84102
84801
  if (params.mockResponse !== void 0) return;
84103
- if (runtime?.sessionManager.getActiveSessionId() !== controlSessionId) return;
84104
- 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
+ });
84105
84807
  if (!loaded) {
84106
84808
  const exists = await runtime.sessionManager.hasSession(controlSessionId);
84107
84809
  throw new SessionControlError(
@@ -84145,8 +84847,14 @@ async function runJsonEventsMode(params) {
84145
84847
  async function handleSessionFork(message) {
84146
84848
  try {
84147
84849
  const { sessionId: controlSessionId, requestId } = requireSessionControlBase(message);
84148
- const sourceEntryId = requireSessionControlString(message.fromEntryId, "fromEntryId");
84149
- 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
+ );
84150
84858
  const name = requireSessionControlString(message.name, "name");
84151
84859
  const forkCwd = message.cwd?.trim() || void 0;
84152
84860
  const cached = completedSessionControlRequests.get(requestId);
@@ -84191,7 +84899,11 @@ async function runJsonEventsMode(params) {
84191
84899
  }
84192
84900
  async function handleSidechat(message) {
84193
84901
  if (isSessionMismatch(message)) {
84194
- writeSidechatFailure(message, sessionMismatchError(message.sessionId), "session_mismatch");
84902
+ writeSidechatFailure(
84903
+ message,
84904
+ sessionMismatchError(message.sessionId),
84905
+ "session_mismatch"
84906
+ );
84195
84907
  return;
84196
84908
  }
84197
84909
  const requestId = message.requestId.trim();
@@ -84205,14 +84917,22 @@ async function runJsonEventsMode(params) {
84205
84917
  return;
84206
84918
  }
84207
84919
  if (activeTurn && !activeTurn.finalized) {
84208
- 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
+ );
84209
84925
  return;
84210
84926
  }
84211
84927
  const startedAt = Date.now();
84212
84928
  if (params.mockResponse !== void 0) {
84213
84929
  const hostContextFailure = validateIntakeHostContext(message);
84214
84930
  if (hostContextFailure) {
84215
- writeSidechatFailure(message, hostContextFailure.message, hostContextFailure.code);
84931
+ writeSidechatFailure(
84932
+ message,
84933
+ hostContextFailure.message,
84934
+ hostContextFailure.code
84935
+ );
84216
84936
  return;
84217
84937
  }
84218
84938
  writeEvent({ type: "sidechat.started", sessionId, requestId });
@@ -84240,18 +84960,29 @@ async function runJsonEventsMode(params) {
84240
84960
  await ensureRuntime(runtime?.cwd);
84241
84961
  const hostContextFailure = validateIntakeHostContext(message);
84242
84962
  if (hostContextFailure) {
84243
- writeSidechatFailure(message, hostContextFailure.message, hostContextFailure.code);
84963
+ writeSidechatFailure(
84964
+ message,
84965
+ hostContextFailure.message,
84966
+ hostContextFailure.code
84967
+ );
84244
84968
  return;
84245
84969
  }
84246
84970
  if (!agent || !runtime) {
84247
84971
  throw new Error("JSON events runtime was not initialized");
84248
84972
  }
84249
84973
  if (runtime.initialModel.unconfigured) {
84250
- writeSidechatFailure(message, runtime.initialModel.warning || "No models are configured.");
84974
+ writeSidechatFailure(
84975
+ message,
84976
+ runtime.initialModel.warning || "No models are configured."
84977
+ );
84251
84978
  return;
84252
84979
  }
84253
84980
  if (sidechatController.signal.aborted) {
84254
- writeSidechatFailure(message, "sidechat aborted before dispatch", "sidechat_interrupted");
84981
+ writeSidechatFailure(
84982
+ message,
84983
+ "sidechat aborted before dispatch",
84984
+ "sidechat_interrupted"
84985
+ );
84255
84986
  return;
84256
84987
  }
84257
84988
  const parent = agent;
@@ -84259,7 +84990,7 @@ async function runJsonEventsMode(params) {
84259
84990
  const sideTrace = trace;
84260
84991
  const sideApiKey = runtime.apiKey;
84261
84992
  const snapshot = structuredClone(parent.state.messages);
84262
- const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
84993
+ const { Agent: AgentClass } = await import("./chunks/src-ODLT57PQ.js");
84263
84994
  const sideAgent = new AgentClass({
84264
84995
  initialState: {
84265
84996
  systemPrompt: parent.state.systemPrompt,
@@ -84271,17 +85002,25 @@ async function runJsonEventsMode(params) {
84271
85002
  apiKey: sideApiKey,
84272
85003
  // The sidechat snapshot clones the parent's stored history, including
84273
85004
  // persisted hostContext facts; project them like the main agent does.
84274
- transformContext: async (messages) => projectCliHostEnvelopes(messages, (outcome) => sideTrace?.noteRuntimeEvent(
84275
- outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
84276
- outcome.audit
84277
- ), 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
+ ),
84278
85013
  // Same body-free transport timeline as the main agent: a sidechat is
84279
85014
  // an independent Responses request and previously had no record at all
84280
85015
  // when it stalled. `streamSimple` matches the host default when the
84281
85016
  // caller injected no stream function.
84282
85017
  streamFn: createJsonEventsTransportStreamFn(params.streamFn)
84283
85018
  });
84284
- sidechatController.signal.addEventListener("abort", () => sideAgent.abort(), { once: true });
85019
+ sidechatController.signal.addEventListener(
85020
+ "abort",
85021
+ () => sideAgent.abort(),
85022
+ { once: true }
85023
+ );
84285
85024
  const timer = setTimeout(() => {
84286
85025
  if (!abortKind) abortKind = "timeout";
84287
85026
  sidechatController.abort();
@@ -84294,7 +85033,11 @@ async function runJsonEventsMode(params) {
84294
85033
  }
84295
85034
  if (abortKind) {
84296
85035
  const code = abortKind === "timeout" ? "sidechat_timeout" : "sidechat_interrupted";
84297
- writeSidechatFailure(message, sideAgent.state.error || "sidechat aborted", code);
85036
+ writeSidechatFailure(
85037
+ message,
85038
+ sideAgent.state.error || "sidechat aborted",
85039
+ code
85040
+ );
84298
85041
  return;
84299
85042
  }
84300
85043
  const failure = sideAgent.state.error;
@@ -84353,10 +85096,18 @@ async function runJsonEventsMode(params) {
84353
85096
  writeEvent({ type: "turn.failed", ...base, ...failureDetail(detail) });
84354
85097
  break;
84355
85098
  case "cancelled":
84356
- writeEvent({ type: "turn.cancelled", ...base, reason: detail || "interrupted" });
85099
+ writeEvent({
85100
+ type: "turn.cancelled",
85101
+ ...base,
85102
+ reason: detail || "interrupted"
85103
+ });
84357
85104
  break;
84358
85105
  case "stalled":
84359
- 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
+ });
84360
85111
  break;
84361
85112
  }
84362
85113
  }
@@ -84397,20 +85148,29 @@ async function runJsonEventsMode(params) {
84397
85148
  turnId: activeTurn.turnId,
84398
85149
  toolCallId: event.toolCallId,
84399
85150
  name: event.toolName,
84400
- data: toJsonValue({
84401
- args: event.args,
84402
- ...argsOversized ? { truncated: true } : {}
84403
- }, 0, eventStringCap)
85151
+ data: toJsonValue(
85152
+ {
85153
+ args: event.args,
85154
+ ...argsOversized ? { truncated: true } : {}
85155
+ },
85156
+ 0,
85157
+ eventStringCap
85158
+ )
84404
85159
  });
84405
85160
  }
84406
85161
  break;
84407
85162
  case "tool_progressed":
84408
85163
  touch();
84409
85164
  {
84410
- const progressText = extractJsonEventsToolProgressText(event.partialResult);
85165
+ const progressText = extractJsonEventsToolProgressText(
85166
+ event.partialResult
85167
+ );
84411
85168
  if (progressText) {
84412
- display(progressText.endsWith("\n") ? progressText : `${progressText}
84413
- `, { appendToSummary: false });
85169
+ display(
85170
+ progressText.endsWith("\n") ? progressText : `${progressText}
85171
+ `,
85172
+ { appendToSummary: false }
85173
+ );
84414
85174
  }
84415
85175
  }
84416
85176
  break;
@@ -84426,20 +85186,138 @@ async function runJsonEventsMode(params) {
84426
85186
  toolCallId: event.toolCallId,
84427
85187
  name: event.toolName,
84428
85188
  status: event.isError ? "error" : "ok",
84429
- data: toJsonValue({
84430
- resultText: capped?.value,
84431
- isError: event.isError,
84432
- ...capped?.truncated ? { truncated: true, fullLength: capped.fullLength } : {}
84433
- }, 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
+ )
84434
85198
  });
84435
85199
  }
84436
85200
  break;
84437
85201
  }
84438
85202
  }
84439
- function handleControllerEvent(event) {
85203
+ async function handleControllerEvent(event) {
84440
85204
  trace?.noteRuntimeEvent(event.type, event);
84441
85205
  if (event.type === "compaction_committed") {
84442
- 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;
84443
85321
  }
84444
85322
  if (event.type === "turn_settled" && activeTurn) {
84445
85323
  touch();
@@ -84447,6 +85325,7 @@ async function runJsonEventsMode(params) {
84447
85325
  }
84448
85326
  if (!activeTurn || activeTurn.finalized) return;
84449
85327
  if (event.type === "turn_recovery_pending" && event.recovery === "retry") {
85328
+ recoveryPending = true;
84450
85329
  lastRetryEvent = {
84451
85330
  attempt: event.attempt ?? 0,
84452
85331
  maxRetries: event.maxRetries ?? CLI_RETRY_MAX_RETRIES,
@@ -84465,6 +85344,7 @@ async function runJsonEventsMode(params) {
84465
85344
  error: event.failure.message
84466
85345
  });
84467
85346
  } else if (event.type === "turn_recovery_pending" && event.recovery === "compaction") {
85347
+ recoveryPending = true;
84468
85348
  activeTurn.summary = "";
84469
85349
  clearPendingAssistantOutput();
84470
85350
  touch();
@@ -84495,6 +85375,7 @@ async function runJsonEventsMode(params) {
84495
85375
  error: lastRetryEvent.error
84496
85376
  });
84497
85377
  } else if (event.type === "turn_retry_succeeded") {
85378
+ recoveryPending = false;
84498
85379
  touch();
84499
85380
  writeEvent({
84500
85381
  type: "turn.retry.succeeded",
@@ -84520,8 +85401,12 @@ async function runJsonEventsMode(params) {
84520
85401
  willRetry: event.willRetry
84521
85402
  });
84522
85403
  } else if (event.type === "turn_completed") {
85404
+ recoveryPending = false;
84523
85405
  const text = assistantTextFromMessage(event.message);
84524
85406
  flushAssistantOutput(text);
85407
+ await enqueueBridgeEmission(
85408
+ () => extensionRunner?.emit({ type: "turn:completed" }) ?? Promise.resolve()
85409
+ );
84525
85410
  rememberTerminal("completed", text || activeTurn.summary.trim());
84526
85411
  } else if (event.type === "turn_failed_terminal") {
84527
85412
  touch();
@@ -84537,12 +85422,37 @@ async function runJsonEventsMode(params) {
84537
85422
  });
84538
85423
  lastRetryEvent = void 0;
84539
85424
  }
85425
+ recoveryPending = false;
84540
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
+ );
84541
85441
  } else if (event.type === "turn_cancelled") {
85442
+ recoveryPending = false;
85443
+ lastRetryEvent = void 0;
84542
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
+ );
84543
85452
  }
84544
85453
  }
84545
85454
  async function disposeRuntime(reason = "runtime_switch") {
85455
+ externalTurn = null;
84546
85456
  const runner = extensionRunner;
84547
85457
  extensionRunner = void 0;
84548
85458
  try {
@@ -84553,6 +85463,8 @@ async function runJsonEventsMode(params) {
84553
85463
  }
84554
85464
  disposeAgentSubscription?.();
84555
85465
  disposeAgentSubscription = void 0;
85466
+ disposeAgentRawSubscription?.();
85467
+ disposeAgentRawSubscription = void 0;
84556
85468
  disposeSemanticSubscription?.();
84557
85469
  disposeSemanticSubscription = void 0;
84558
85470
  controller?.dispose();
@@ -84577,7 +85489,10 @@ async function runJsonEventsMode(params) {
84577
85489
  if (!params.createRuntime && !params.runtime) return;
84578
85490
  try {
84579
85491
  await new Promise((resolve8, reject) => {
84580
- const timer = setTimeout(() => reject(new Error("prewarm timeout")), prewarmTimeoutMs);
85492
+ const timer = setTimeout(
85493
+ () => reject(new Error("prewarm timeout")),
85494
+ prewarmTimeoutMs
85495
+ );
84581
85496
  timer.unref?.();
84582
85497
  void ensureRuntime().then(resolve8, reject).finally(() => clearTimeout(timer));
84583
85498
  });
@@ -84600,6 +85515,8 @@ async function runJsonEventsMode(params) {
84600
85515
  }
84601
85516
  async function composeRuntime(effectiveCwd) {
84602
85517
  if (params.createRuntime && (!runtime || runtime.cwd !== effectiveCwd)) {
85518
+ compositionGeneration += 1;
85519
+ externalTurn = null;
84603
85520
  await disposeRuntime();
84604
85521
  runtime = await params.createRuntime({ cwd: effectiveCwd, sessionId });
84605
85522
  }
@@ -84623,15 +85540,44 @@ async function runJsonEventsMode(params) {
84623
85540
  if (runtime.initialModel.unconfigured || controller) {
84624
85541
  return;
84625
85542
  }
84626
- const { Agent: AgentClass } = await import("./chunks/src-YG5M2H44.js");
85543
+ const { Agent: AgentClass } = await import("./chunks/src-ODLT57PQ.js");
84627
85544
  if (runtimeClosing) return;
84628
85545
  const compositionRegistry = createCliHostEnvelopeRegistry();
84629
- 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
+ });
84630
85564
  if (runtimeClosing) {
84631
85565
  await jsonModeExtensions.runner.dispose("shutdown");
84632
85566
  return;
84633
85567
  }
84634
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
+ }
84635
85581
  envelopeRegistry = compositionRegistry;
84636
85582
  const tools = [...runtime.tools, ...jsonModeExtensions.extensionTools];
84637
85583
  const restoredApiKey = runtime.modelRegistry.getApiKey(runtime.model);
@@ -84665,10 +85611,14 @@ async function runJsonEventsMode(params) {
84665
85611
  // Restored interactive sessions carry persisted hostContext facts; project
84666
85612
  // them to model-visible text at the request boundary or the provider
84667
85613
  // converters reject the request (`Unprojected hostContext block`).
84668
- transformContext: async (messages) => projectCliHostEnvelopes(messages, (outcome) => trace?.noteRuntimeEvent(
84669
- outcome.degraded ? "host_envelope_degraded" : "host_envelope_projected",
84670
- outcome.audit
84671
- ), 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
+ ),
84672
85622
  // Body-free transport timeline for the main (JSON-events) agent.
84673
85623
  streamFn: createJsonEventsTransportStreamFn(params.streamFn)
84674
85624
  });
@@ -84691,7 +85641,31 @@ async function runJsonEventsMode(params) {
84691
85641
  },
84692
85642
  retry: createCliRetryPolicy(),
84693
85643
  onExecutionEnd: async ({ messages }) => {
84694
- 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
+ );
84695
85669
  },
84696
85670
  getAutoCompactDecision: ({ message, messages }) => createCliAutoCompactDecision({
84697
85671
  message,
@@ -84723,14 +85697,40 @@ async function runJsonEventsMode(params) {
84723
85697
  classifyFailure: (context) => classifyCliFailure(context),
84724
85698
  onEvent: handleControllerEvent
84725
85699
  });
84726
- trace = new SessionTraceWriter(runtime.paths.sessionsDir, runtime.sessionManager);
85700
+ trace = new SessionTraceWriter(
85701
+ runtime.paths.sessionsDir,
85702
+ runtime.sessionManager
85703
+ );
84727
85704
  attachAgentEventsToSessionTrace({ agent, trace });
84728
- agent.setTools(wrapToolsWithExtensions(agent.state.tools, jsonModeExtensions.runner));
85705
+ agent.setTools(
85706
+ wrapToolsWithExtensions(agent.state.tools, jsonModeExtensions.runner)
85707
+ );
84729
85708
  controller.updateRuntimeContext({ tools: agent.state.tools });
84730
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
+ });
84731
85728
  if (!thinkingLevelInitialized) {
84732
85729
  thinkingLevelInitialized = true;
84733
- thinkingLevel = resolveInitialThinkingLevel({ session: runtime.sessionManager.getActiveSession(), settingsManager: runtime.settingsManager });
85730
+ thinkingLevel = resolveInitialThinkingLevel({
85731
+ session: runtime.sessionManager.getActiveSession(),
85732
+ settingsManager: runtime.settingsManager
85733
+ });
84734
85734
  agent.setThinkingLevel(thinkingLevel);
84735
85735
  }
84736
85736
  }
@@ -84738,7 +85738,8 @@ async function runJsonEventsMode(params) {
84738
85738
  if (!metadata || !(key in metadata)) return void 0;
84739
85739
  const value = metadata[key];
84740
85740
  if (value === null) return null;
84741
- 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`);
84742
85743
  const normalized = value.trim();
84743
85744
  return normalized && normalized !== "default" ? normalized : null;
84744
85745
  }
@@ -84763,7 +85764,10 @@ async function runJsonEventsMode(params) {
84763
85764
  function applyRuntimeSelection(message) {
84764
85765
  if (!runtime || !agent) return;
84765
85766
  const requestedModel = metadataSelection(message.metadata, "model");
84766
- const requestedThinkingLevel = metadataSelection(message.metadata, "thinkingLevel");
85767
+ const requestedThinkingLevel = metadataSelection(
85768
+ message.metadata,
85769
+ "thinkingLevel"
85770
+ );
84767
85771
  if (requestedModel !== void 0) {
84768
85772
  if (requestedModel === null) {
84769
85773
  const defaults = defaultModelState;
@@ -84777,7 +85781,10 @@ async function runJsonEventsMode(params) {
84777
85781
  }
84778
85782
  } else {
84779
85783
  const parsed = parseRequestedModel(requestedModel);
84780
- 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
+ );
84781
85788
  const { provider, modelId } = parsed;
84782
85789
  const model = runtime.modelRegistry.find(provider, modelId);
84783
85790
  if (!model) throw new Error(`Model "${requestedModel}" not found`);
@@ -84792,7 +85799,8 @@ async function runJsonEventsMode(params) {
84792
85799
  }
84793
85800
  if (requestedThinkingLevel !== void 0) {
84794
85801
  const nextLevel = requestedThinkingLevel === null ? "off" : requestedThinkingLevel;
84795
- if (!isThinkingLevel(nextLevel)) throw new Error(`Unsupported thinkingLevel: ${nextLevel}`);
85802
+ if (!isThinkingLevel(nextLevel))
85803
+ throw new Error(`Unsupported thinkingLevel: ${nextLevel}`);
84796
85804
  thinkingLevel = nextLevel;
84797
85805
  thinkingLevelInitialized = true;
84798
85806
  applyThinkingLevel({
@@ -84808,12 +85816,21 @@ async function runJsonEventsMode(params) {
84808
85816
  persist: false
84809
85817
  });
84810
85818
  } else {
84811
- syncSessionModelMetadata(runtime.sessionManager, runtime.model, thinkingLevel);
85819
+ syncSessionModelMetadata(
85820
+ runtime.sessionManager,
85821
+ runtime.model,
85822
+ thinkingLevel
85823
+ );
84812
85824
  }
84813
85825
  }
84814
85826
  function promptInputFor(message) {
84815
85827
  return message.hostContext ? [message.hostContext, { type: "text", text: message.prompt }] : message.prompt;
84816
85828
  }
85829
+ let turnCounter = 0;
85830
+ function promptAgentMessage(message) {
85831
+ const content = promptInputFor(message);
85832
+ return { role: "user", content, timestamp: Date.now() };
85833
+ }
84817
85834
  function sidechatPromptBlocks(message) {
84818
85835
  return message.hostContext ? [message.hostContext, { type: "text", text: message.prompt }] : [{ type: "text", text: message.prompt }];
84819
85836
  }
@@ -84832,7 +85849,9 @@ async function runJsonEventsMode(params) {
84832
85849
  }
84833
85850
  if (activeTurn && !activeTurn.finalized) {
84834
85851
  const owner = activeTurn;
84835
- owner.queue = owner.queue.then(() => queueActiveTurnInput(message, owner));
85852
+ owner.queue = owner.queue.then(
85853
+ () => queueActiveTurnInput(message, owner)
85854
+ );
84836
85855
  await owner.queue;
84837
85856
  return;
84838
85857
  }
@@ -84857,7 +85876,13 @@ async function runJsonEventsMode(params) {
84857
85876
  pendingAssistantOutput: ""
84858
85877
  };
84859
85878
  const turn = activeTurn;
84860
- 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
+ });
84861
85886
  if (params.mockResponse !== void 0) {
84862
85887
  const mockHostContextFailure = validateIntakeHostContext(message);
84863
85888
  if (mockHostContextFailure) {
@@ -84905,7 +85930,8 @@ async function runJsonEventsMode(params) {
84905
85930
  return;
84906
85931
  }
84907
85932
  if (activeTurn !== turn || turn.finalized || turn.interrupted) {
84908
- if (activeTurn === turn && !turn.finalized) finalize("cancelled", "user_interrupt");
85933
+ if (activeTurn === turn && !turn.finalized)
85934
+ finalize("cancelled", "user_interrupt");
84909
85935
  turn.releaseReady();
84910
85936
  if (activeTurn === turn) {
84911
85937
  emitSettled(turn);
@@ -84926,7 +85952,10 @@ async function runJsonEventsMode(params) {
84926
85952
  }
84927
85953
  const activeRuntime = runtime;
84928
85954
  if (activeRuntime?.initialModel.unconfigured) {
84929
- finalize("failed", activeRuntime.initialModel.warning || "No models are configured.");
85955
+ finalize(
85956
+ "failed",
85957
+ activeRuntime.initialModel.warning || "No models are configured."
85958
+ );
84930
85959
  if (activeTurn === turn) emitSettled(turn);
84931
85960
  if (activeTurn === turn) activeTurn = null;
84932
85961
  return;
@@ -84940,25 +85969,34 @@ async function runJsonEventsMode(params) {
84940
85969
  try {
84941
85970
  applyRuntimeSelection(message);
84942
85971
  } catch (error) {
84943
- finalize("failed", error instanceof Error ? error.message : String(error));
85972
+ finalize(
85973
+ "failed",
85974
+ error instanceof Error ? error.message : String(error)
85975
+ );
84944
85976
  if (activeTurn === turn) emitSettled(turn);
84945
85977
  if (activeTurn === turn) activeTurn = null;
84946
85978
  return;
84947
85979
  }
84948
- const progressTimer = setInterval(() => {
84949
- const turn2 = activeTurn;
84950
- if (!turn2 || turn2.finalized) return;
84951
- if (Date.now() - turn2.lastActivityAt >= noProgressTimeoutMs) {
84952
- turn2.stalled = true;
84953
- controller?.abort();
84954
- finalize("stalled", "no_progress_timeout");
84955
- }
84956
- }, 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
+ );
84957
85992
  progressTimer.unref?.();
84958
85993
  try {
84959
85994
  trace?.notePendingUserText(message.prompt);
84960
85995
  trace?.noteDispatchStart({ mode: "json-events" });
84961
- 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
+ });
84962
86000
  turn.releaseReady();
84963
86001
  await dispatched;
84964
86002
  trace?.noteDispatchSettled({ mode: "json-events" });
@@ -84988,7 +86026,30 @@ async function runJsonEventsMode(params) {
84988
86026
  } catch {
84989
86027
  }
84990
86028
  if (!activeTurn?.finalized) {
84991
- 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
+ );
84992
86053
  }
84993
86054
  if (activeTurn === turn) emitSettled(turn);
84994
86055
  } finally {
@@ -85114,12 +86175,73 @@ async function runJsonEventsMode(params) {
85114
86175
  }
85115
86176
  const input = readline.createInterface({ input: process.stdin });
85116
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
+ }
85117
86234
  try {
85118
86235
  for await (const line of input) {
85119
86236
  if (!line.trim()) continue;
85120
86237
  const message = parseInput(line);
85121
86238
  if (!message) {
85122
- 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
+ });
85123
86245
  continue;
85124
86246
  }
85125
86247
  if (message.type === "shutdown") {
@@ -85143,20 +86265,31 @@ async function runJsonEventsMode(params) {
85143
86265
  }
85144
86266
  if (message.type === "sidechat.request") {
85145
86267
  const prior = activeSidechatPromise ?? Promise.resolve();
85146
- trackSidechatPromise(prior.then(async () => {
85147
- if (sidechatChainStopped) {
85148
- const cached = completedSidechatRequests.get(message.requestId.trim());
85149
- if (cached) {
85150
- writeEvent(cached);
85151
- } else {
85152
- 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;
85153
86284
  }
85154
- return;
85155
- }
85156
- await handleSidechat(message).catch((error) => {
85157
- writeSidechatFailure(message, error instanceof Error ? error.message : String(error));
85158
- });
85159
- }));
86285
+ await handleSidechat(message).catch((error) => {
86286
+ writeSidechatFailure(
86287
+ message,
86288
+ error instanceof Error ? error.message : String(error)
86289
+ );
86290
+ });
86291
+ })
86292
+ );
85160
86293
  continue;
85161
86294
  }
85162
86295
  const shouldTrackTurn = !activeTurn || activeTurn.finalized;
@@ -85263,6 +86396,7 @@ Print Mode Options:
85263
86396
  --raw-output Print assistant text only in non-interactive mode
85264
86397
  --json-output Print structured JSON in non-interactive mode
85265
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
85266
86400
  --session-id Reuse or create a specific session in non-interactive mode
85267
86401
  --resume-required In JSON-events mode, fail if --session-id cannot be resumed
85268
86402
  --no-cd Resume without restarting in the session's project directory
@@ -85274,6 +86408,42 @@ Print Mode Options:
85274
86408
  `);
85275
86409
  }
85276
86410
 
86411
+ // src/runtime/supervisor-anchor.ts
86412
+ import { execFileSync } from "node:child_process";
86413
+ function selfStartTime() {
86414
+ if (process.platform === "win32") {
86415
+ try {
86416
+ return execFileSync(
86417
+ "powershell",
86418
+ [
86419
+ "-NoProfile",
86420
+ "-NonInteractive",
86421
+ "-Command",
86422
+ `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${process.pid}"; if ($p) { $p.CreationDate.ToString('o') }`
86423
+ ],
86424
+ { timeout: 5e3, encoding: "utf8", windowsHide: true }
86425
+ ).trim() || void 0;
86426
+ } catch {
86427
+ return void 0;
86428
+ }
86429
+ }
86430
+ try {
86431
+ return execFileSync("ps", ["-p", String(process.pid), "-o", "lstart="], {
86432
+ timeout: 5e3,
86433
+ env: { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC0" },
86434
+ encoding: "utf8"
86435
+ }).trim() || void 0;
86436
+ } catch {
86437
+ return void 0;
86438
+ }
86439
+ }
86440
+ function injectSupervisorAnchor(env = process.env) {
86441
+ env[SUPERVISOR_PID_ENV] = String(process.pid);
86442
+ const startTime = selfStartTime();
86443
+ if (startTime !== void 0) env[SUPERVISOR_START_TIME_ENV] = startTime;
86444
+ else delete env[SUPERVISOR_START_TIME_ENV];
86445
+ }
86446
+
85277
86447
  // src/cli.ts
85278
86448
  enableEarlyLogBuffer();
85279
86449
  var logError = (msg, err) => {
@@ -85295,7 +86465,8 @@ var STABLE_CLI_COMMANDS = {
85295
86465
  models: "models",
85296
86466
  sessions: "sessions",
85297
86467
  extensions: "extensions",
85298
- permissions: "permissions"
86468
+ permissions: "permissions",
86469
+ concierge: "concierge"
85299
86470
  };
85300
86471
  async function runWithJsonEventsConsoleIsolation(fn) {
85301
86472
  const originalLog = console.log;
@@ -85315,7 +86486,7 @@ async function runWithJsonEventsConsoleIsolation(fn) {
85315
86486
  }
85316
86487
  async function createCliTestStreamFnFromEnv() {
85317
86488
  if (!process.env.PIE_TEST_MOCK_STREAM_SEQUENCE) return void 0;
85318
- return (await import("./chunks/test-stream-JBWXKOQA.js")).createTestStreamFnFromSequenceEnv();
86489
+ return (await import("./chunks/test-stream-GIUD5JWS.js")).createTestStreamFnFromSequenceEnv();
85319
86490
  }
85320
86491
  function resolveJsonEventsDetailFlag() {
85321
86492
  for (let index = 0; index < process.argv.length; index += 1) {
@@ -85339,6 +86510,11 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
85339
86510
  const extensionPaths = parseRepeatedFlag(process.argv, "--extension-path");
85340
86511
  const extensionFlags = parseExtensionFlags(process.argv);
85341
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
+ }
85342
86518
  const detailFlag = resolveJsonEventsDetailFlag();
85343
86519
  if ("error" in detailFlag) {
85344
86520
  console.error(`Invalid --event-detail value: ${detailFlag.error}. Use compact or full.`);
@@ -85368,6 +86544,7 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
85368
86544
  resumeRequired,
85369
86545
  developerInstructions,
85370
86546
  eventDetail,
86547
+ idle: process.argv.includes("--idle"),
85371
86548
  streamFn: await createCliTestStreamFnFromEnv(),
85372
86549
  createRuntime: async ({ cwd, sessionId }) => composeCliRuntime({
85373
86550
  explicitSessionId: explicitSessionId ?? sessionId,
@@ -85396,6 +86573,10 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
85396
86573
  return;
85397
86574
  }
85398
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
+ }
85399
86580
  try {
85400
86581
  runtime = await composeCliRuntime({ explicitSessionId, extensionPaths, extensionFlags });
85401
86582
  } catch (error) {
@@ -85450,10 +86631,17 @@ async function startChat(initialPrompt, testCommand, explicitSessionId) {
85450
86631
  }
85451
86632
  async function main() {
85452
86633
  const args = process.argv.slice(2);
86634
+ injectSupervisorAnchor();
85453
86635
  if (args[0] === "--version" || args[0] === "-v") {
85454
86636
  console.log(VERSION);
85455
86637
  return;
85456
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
+ }
85457
86645
  if (args.length === 0 && !process.stdin.isTTY) {
85458
86646
  console.error("pie: no arguments and stdin is not a terminal; refusing to start interactive mode.");
85459
86647
  showHelp();
@@ -85493,6 +86681,16 @@ async function main() {
85493
86681
  await runMemoryCommand(args.slice(1));
85494
86682
  return;
85495
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
+ }
85496
86694
  const parsed = parseCliInvocation(args);
85497
86695
  if (parsed.showHelp) {
85498
86696
  showHelp();