@adhdev/daemon-standalone 0.9.82-rc.551 → 0.9.82-rc.553

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.
package/dist/index.js CHANGED
@@ -29898,6 +29898,15 @@ var require_dist3 = __commonJS({
29898
29898
  }
29899
29899
  return true;
29900
29900
  }
29901
+ function resolveAllowSendKeysDestructive(meshPolicy, nodePolicy) {
29902
+ if (typeof nodePolicy?.allowSendKeysDestructive === "boolean") {
29903
+ return nodePolicy.allowSendKeysDestructive;
29904
+ }
29905
+ if (typeof meshPolicy?.allowSendKeysDestructive === "boolean") {
29906
+ return meshPolicy.allowSendKeysDestructive;
29907
+ }
29908
+ return false;
29909
+ }
29901
29910
  function resolveProviderMaxParallel(slots, providerType) {
29902
29911
  const wanted = typeof providerType === "string" ? providerType.trim().toLowerCase() : "";
29903
29912
  if (!wanted) return void 0;
@@ -30208,10 +30217,10 @@ var require_dist3 = __commonJS({
30208
30217
  }
30209
30218
  function getDaemonBuildInfo() {
30210
30219
  if (cached2) return cached2;
30211
- const commit = readInjected(true ? "178a437592e2f9544675a54768b48281804bdddb" : void 0) ?? "unknown";
30212
- const commitShort = readInjected(true ? "178a4375" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30213
- const version2 = readInjected(true ? "0.9.82-rc.551" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30214
- const builtAt = readInjected(true ? "2026-07-16T19:22:22.887Z" : void 0);
30220
+ const commit = readInjected(true ? "3fc4f272513b6f628ec1732ef57d9ed94e08b8ff" : void 0) ?? "unknown";
30221
+ const commitShort = readInjected(true ? "3fc4f272" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30222
+ const version2 = readInjected(true ? "0.9.82-rc.553" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30223
+ const builtAt = readInjected(true ? "2026-07-17T06:05:28.497Z" : void 0);
30215
30224
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
30216
30225
  return cached2;
30217
30226
  }
@@ -32799,6 +32808,8 @@ ${error48.message || ""}`;
32799
32808
  "mesh_send_task",
32800
32809
  "mesh_read_chat",
32801
32810
  "mesh_read_debug",
32811
+ "mesh_read_terminal",
32812
+ "mesh_send_keys",
32802
32813
  "mesh_launch_session",
32803
32814
  "mesh_git_status",
32804
32815
  "mesh_read_node_logs",
@@ -33951,6 +33962,8 @@ When you compose the task message you dispatch to a node, include these requirem
33951
33962
  | \`mesh_launch_session\` | Start a new agent session on a node |
33952
33963
  | \`mesh_read_chat\` | Read recent chat messages from a delegated agent session |
33953
33964
  | \`mesh_read_debug\` | Collect a daemon-side chat/parser debug bundle for a session |
33965
+ | \`mesh_read_terminal\` | Read a worker session's CURRENT raw terminal screen (the live rendered PTY viewport \u2014 prompt/modal/spinner/unparsed output), not the parsed chat. Byte-bounded (32KiB default, 64KiB max; bottom of screen kept). Use to see exactly what a worker is showing when mesh_read_chat is not enough (e.g. after a stall alert). Screen text may contain secrets \u2014 treat as sensitive |
33966
+ | \`mesh_send_keys\` | Inject a STRUCTURED key sequence into a worker's live PTY (text + named keys ENTER/ESC/CTRL_C/UP/DOWN/LEFT/RIGHT/TAB/BACKSPACE). For interactions mesh_send_task can't express \u2014 answer a non-approval prompt, navigate a picker, submit a typed line, or interrupt (CTRL_C). Use mesh_approve for approval modals (send_keys is refused on one). Destructive keys (CTRL_C/ESC) need confirm_destructive=true AND mesh policy allowSendKeysDestructive. Refused on a pending submit/echo race. Audited (key enums only) |
33954
33967
  | \`mesh_task_history\` | Read the task ledger \u2014 dispatches, completions, failures. Use to understand what has been done before deciding next steps |
33955
33968
  | \`mesh_ledger_query\` | Read-only ledger query along the kind/time/node axes (complement to task-axis mesh_task_history): filter by kind, since, node, tail \u2014 answer "what happened on node X / what failed since T" without scanning transcripts |
33956
33969
  | \`mesh_reconcile_ledger\` | Reconcile daemon-local ledgers over P2P \u2014 import missing entries from remote nodes into the coordinator local ledger |
@@ -38661,6 +38674,13 @@ Do NOT retry on this node. Consider reassigning to a different node or asking th
38661
38674
  return `[System] ${args.nodeLabel} has stopped${metadata}. Use mesh_read_chat once if you need to inspect its last output.`;
38662
38675
  }
38663
38676
  if (args.event === "monitor:no_progress") {
38677
+ if (args.metadataEvent.meshWorkerStall === true) {
38678
+ const observedStatus = readNonEmptyString2(args.metadataEvent.observedStatus);
38679
+ const stalledMs = typeof args.metadataEvent.stalledMs === "number" ? args.metadataEvent.stalledMs : void 0;
38680
+ const stalledSuffix = stalledMs !== void 0 ? ` for ${Math.round(stalledMs / 1e3)}s` : "";
38681
+ const statusSuffix = observedStatus ? ` (observed status: ${observedStatus})` : "";
38682
+ return `[System] ${args.nodeLabel}: PTY output unchanged${stalledSuffix}${statusSuffix}${metadata}. This is an informational stall \u2014 the worker's screen has been static regardless of its reported status; it may be genuinely idle, waiting, or wedged, so this is NOT a failure or auto-restart. Judge whether to inspect it: wait for pendingCoordinatorEvents/a completion event, or make one bounded mesh_read_chat check if you need to see its current screen, then wait again.`;
38683
+ }
38664
38684
  return `[System] ${args.nodeLabel} is still reported as generating after a long interval${metadata}. Wait for pendingCoordinatorEvents or a completion/status event; if the user explicitly asks for status, make one bounded status check and then wait again.`;
38665
38685
  }
38666
38686
  if (args.event === "worktree_bootstrap_complete") {
@@ -42486,6 +42506,82 @@ ${rendered}`, "utf-8");
42486
42506
  const accumulator = new TerminalTranscriptAccumulator();
42487
42507
  return stripTerminalNoise(stripAnsi(accumulator.append(str)));
42488
42508
  }
42509
+ function encodeMeshSendKeys(items) {
42510
+ if (!Array.isArray(items) || items.length === 0) {
42511
+ throw new Error("send_keys: sequence must be a non-empty array");
42512
+ }
42513
+ if (items.length > MESH_SEND_KEYS_MAX_ITEMS) {
42514
+ throw new Error(`send_keys: sequence exceeds ${MESH_SEND_KEYS_MAX_ITEMS} items`);
42515
+ }
42516
+ const parts = [];
42517
+ const keys = [];
42518
+ let hasDestructive = false;
42519
+ let submits = false;
42520
+ let textBytes = 0;
42521
+ for (const item of items) {
42522
+ if (item && typeof item.text === "string") {
42523
+ const text = item.text;
42524
+ textBytes += Buffer.byteLength(text, "utf8");
42525
+ if (textBytes > MESH_SEND_KEYS_MAX_TEXT_BYTES) {
42526
+ throw new Error(`send_keys: total literal text exceeds ${MESH_SEND_KEYS_MAX_TEXT_BYTES} bytes`);
42527
+ }
42528
+ parts.push(text);
42529
+ submits = false;
42530
+ continue;
42531
+ }
42532
+ const keyName = item && typeof item.key === "string" ? item.key : "";
42533
+ if (!(keyName in MESH_SEND_KEY_ENCODING)) {
42534
+ throw new Error(`send_keys: unknown key '${keyName}'`);
42535
+ }
42536
+ const key2 = keyName;
42537
+ parts.push(MESH_SEND_KEY_ENCODING[key2]);
42538
+ keys.push(key2);
42539
+ if (MESH_DESTRUCTIVE_KEYS.has(key2)) hasDestructive = true;
42540
+ submits = key2 === "ENTER";
42541
+ }
42542
+ return { sequence: parts.join(""), keys, hasDestructive, submits };
42543
+ }
42544
+ function truncateToByteTailByLine(text, maxBytes) {
42545
+ const input = String(text ?? "");
42546
+ const originalBytes = Buffer.byteLength(input, "utf8");
42547
+ if (originalBytes <= maxBytes) {
42548
+ return { text: input, truncated: false, originalBytes, returnedBytes: originalBytes };
42549
+ }
42550
+ const lines = input.split("\n");
42551
+ const kept = [];
42552
+ let bytes = 0;
42553
+ for (let i = lines.length - 1; i >= 0; i--) {
42554
+ const line = lines[i];
42555
+ const lineBytes = Buffer.byteLength(line, "utf8");
42556
+ const joinCost = kept.length > 0 ? 1 : 0;
42557
+ if (bytes + lineBytes + joinCost > maxBytes) break;
42558
+ bytes += lineBytes + joinCost;
42559
+ kept.unshift(line);
42560
+ }
42561
+ if (kept.length > 0) {
42562
+ const out = kept.join("\n");
42563
+ return {
42564
+ text: out,
42565
+ truncated: true,
42566
+ originalBytes,
42567
+ returnedBytes: Buffer.byteLength(out, "utf8")
42568
+ };
42569
+ }
42570
+ const lastLine = lines[lines.length - 1] ?? "";
42571
+ const buf = Buffer.from(lastLine, "utf8");
42572
+ let slice = buf.subarray(Math.max(0, buf.length - maxBytes));
42573
+ let decoded = slice.toString("utf8");
42574
+ while (decoded.length > 0 && decoded.charCodeAt(0) === 65533 && slice.length > 0) {
42575
+ slice = slice.subarray(1);
42576
+ decoded = slice.toString("utf8");
42577
+ }
42578
+ return {
42579
+ text: decoded,
42580
+ truncated: true,
42581
+ originalBytes,
42582
+ returnedBytes: Buffer.byteLength(decoded, "utf8")
42583
+ };
42584
+ }
42489
42585
  function listCliScriptNames(scripts) {
42490
42586
  if (!scripts) return [];
42491
42587
  return Object.entries(scripts).filter(([, fn]) => typeof fn === "function").map(([name]) => name);
@@ -42690,6 +42786,10 @@ ${rendered}`, "utf-8");
42690
42786
  var os52;
42691
42787
  var path11;
42692
42788
  var TerminalTranscriptAccumulator;
42789
+ var MESH_SEND_KEY_ENCODING;
42790
+ var MESH_DESTRUCTIVE_KEYS;
42791
+ var MESH_SEND_KEYS_MAX_ITEMS;
42792
+ var MESH_SEND_KEYS_MAX_TEXT_BYTES;
42693
42793
  var buildCliSpawnEnv;
42694
42794
  var init_provider_cli_shared = __esm2({
42695
42795
  "src/cli-adapters/provider-cli-shared.ts"() {
@@ -42853,6 +42953,20 @@ ${rendered}`, "utf-8");
42853
42953
  this.ensureRow();
42854
42954
  }
42855
42955
  };
42956
+ MESH_SEND_KEY_ENCODING = {
42957
+ ENTER: "\r",
42958
+ ESC: "\x1B",
42959
+ CTRL_C: "",
42960
+ UP: "\x1B[A",
42961
+ DOWN: "\x1B[B",
42962
+ RIGHT: "\x1B[C",
42963
+ LEFT: "\x1B[D",
42964
+ TAB: " ",
42965
+ BACKSPACE: "\x7F"
42966
+ };
42967
+ MESH_DESTRUCTIVE_KEYS = /* @__PURE__ */ new Set(["CTRL_C", "ESC"]);
42968
+ MESH_SEND_KEYS_MAX_ITEMS = 64;
42969
+ MESH_SEND_KEYS_MAX_TEXT_BYTES = 4096;
42856
42970
  buildCliSpawnEnv = import_session_host_core22.sanitizeSpawnEnv;
42857
42971
  }
42858
42972
  });
@@ -48014,6 +48128,10 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
48014
48128
  getCursorPosition() {
48015
48129
  return this.terminal.getCursorPosition();
48016
48130
  }
48131
+ /** Current viewport dimensions (cols × rows). */
48132
+ getSize() {
48133
+ return { cols: this.cols, rows: this.rows };
48134
+ }
48017
48135
  dispose() {
48018
48136
  this.terminal.dispose();
48019
48137
  }
@@ -56766,6 +56884,7 @@ ${cont}` : cont;
56766
56884
  return current.slice(-keepFromCurrent) + chunk;
56767
56885
  }
56768
56886
  var os16;
56887
+ var import_crypto10;
56769
56888
  var import_session_host_core6;
56770
56889
  var FORCE_SUBMIT_SETTLE_MS;
56771
56890
  var ProviderCliAdapter;
@@ -56773,6 +56892,7 @@ ${cont}` : cont;
56773
56892
  "src/cli-adapters/provider-cli-adapter.ts"() {
56774
56893
  "use strict";
56775
56894
  os16 = __toESM2(require("os"));
56895
+ import_crypto10 = require("crypto");
56776
56896
  init_logger();
56777
56897
  init_debug_config();
56778
56898
  init_terminal_screen();
@@ -56974,6 +57094,11 @@ ${cont}` : cont;
56974
57094
  static MAX_ACCUMULATED_BUFFER = 262144;
56975
57095
  parsedStatusCache = null;
56976
57096
  static SCREEN_SNAPSHOT_MIN_INTERVAL_MS = 250;
57097
+ // MESH-READ-TERMINAL (feature 2): byte caps for getTerminalScreenSnapshot.
57098
+ // Byte, not char — a multi-byte-glyph screen can exceed an MCP payload cap
57099
+ // while the char count still looks safe. 32KiB default, 64KiB absolute hard cap.
57100
+ static TERMINAL_SNAPSHOT_DEFAULT_MAX_BYTES = 32 * 1024;
57101
+ static TERMINAL_SNAPSHOT_ABSOLUTE_MAX_BYTES = 64 * 1024;
56977
57102
  // (FALSEIDLE Path-C) Consecutive gate-eligible getStatus polls a mesh/autonomous
56978
57103
  // session must show before the poll-static-idle confirm fires. 2 = one extra
56979
57104
  // status tick of hysteresis: enough to reject a single momentary-silence
@@ -58552,6 +58677,103 @@ ${lastSnapshot}`;
58552
58677
  isAlive() {
58553
58678
  return this.ptyProcess !== null;
58554
58679
  }
58680
+ /**
58681
+ * MESH-READ-TERMINAL (feature 2: RAW terminal read). Narrow, least-privilege
58682
+ * read of the CURRENT rendered viewport for mesh_read_terminal. Deliberately
58683
+ * NARROWER than getSnapshot()/getDebugSnapshot():
58684
+ * - It returns ONLY the terminal's current rendered viewport (what a human
58685
+ * would see on screen right now), the cursor position and the viewport
58686
+ * size. NO debug buffers, NO parser/FSM state, NO scrollback/history.
58687
+ * - It does NOT call getParseScreenText() (which may graft an older snapshot
58688
+ * onto the current frame for parse accuracy) — the caller asked for the
58689
+ * live viewport, not a parse-optimized composite.
58690
+ * - The payload is bounded in BYTES (UTF-8) with bottom-tail preservation so
58691
+ * a screen of multi-byte glyphs can never exceed the MCP payload cap. See
58692
+ * truncateToByteTailByLine.
58693
+ *
58694
+ * SECURITY NOTE: the raw viewport can contain tokens / command args / env
58695
+ * values / user data. Callers MUST gate this on mesh ownership and MUST NOT
58696
+ * log the returned text. Opt-in redaction is intentionally out of scope for
58697
+ * this feature and left as a future enhancement.
58698
+ *
58699
+ * `maxBytes` is clamped to [1KiB, ABSOLUTE_MAX] (default 32KiB, hard cap 64KiB).
58700
+ */
58701
+ getTerminalScreenSnapshot(maxBytes = _ProviderCliAdapter.TERMINAL_SNAPSHOT_DEFAULT_MAX_BYTES) {
58702
+ const cap = Math.min(
58703
+ _ProviderCliAdapter.TERMINAL_SNAPSHOT_ABSOLUTE_MAX_BYTES,
58704
+ Math.max(1024, Math.floor(maxBytes) || _ProviderCliAdapter.TERMINAL_SNAPSHOT_DEFAULT_MAX_BYTES)
58705
+ );
58706
+ const rawViewport = this.terminalScreen.getText() || "";
58707
+ const size = this.terminalScreen.getSize();
58708
+ const cursor = this.terminalScreen.getCursorPosition();
58709
+ const truncation = truncateToByteTailByLine(rawViewport, cap);
58710
+ const hash2 = (0, import_crypto10.createHash)("sha256").update(rawViewport, "utf8").digest("hex").slice(0, 16);
58711
+ return {
58712
+ text: truncation.text,
58713
+ cursor,
58714
+ cols: size.cols,
58715
+ rows: size.rows,
58716
+ truncated: truncation.truncated,
58717
+ originalBytes: truncation.originalBytes,
58718
+ returnedBytes: truncation.returnedBytes,
58719
+ hash: hash2
58720
+ };
58721
+ }
58722
+ /**
58723
+ * MESH-SEND-KEYS (feature 3: key injection). Inject a STRUCTURED key sequence
58724
+ * into the PTY for the mesh_send_keys tool. Reuses the same serialized write
58725
+ * path as sends (writeToPty via writeRaw semantics) so the injection FIFO-
58726
+ * orders behind any in-flight write.
58727
+ *
58728
+ * Two guards run INSIDE this method, immediately before the write, so they see
58729
+ * a consistent snapshot of the adapter's submit/echo/queue state (no async gap
58730
+ * between check and write — the encode is synchronous and the write is chained
58731
+ * atomically after it):
58732
+ *
58733
+ * 1. submit-race recheck (echo-gate): even though writeToPty is FIFO, an
58734
+ * already-SCHEDULED echo-gated Enter (engine.submitPendingUntil in the
58735
+ * future), an armed stuck-submit retry (submitRetryTimer), or an in-flight
58736
+ * pending-outbound flush can submit at a DIFFERENT tick than our write —
58737
+ * so an injected literal could be submitted by a pending Enter, or our
58738
+ * ENTER could submit a half-typed pending body. When any of those is live
58739
+ * we REFUSE the injection rather than interleave.
58740
+ *
58741
+ * 2. modal fail-closed: if the session is parked on an actionable approval
58742
+ * modal, refuse a NON-destructive injection (ENTER/text/arrows) and direct
58743
+ * the caller to mesh_approve — so a modal choice can't be confirmed via
58744
+ * send_keys to bypass the approval policy. (A destructive ESC/CTRL_C, which
58745
+ * dismisses rather than confirms, is allowed to proceed past this gate; it
58746
+ * is separately gated by confirm_destructive + policy at the tool layer.)
58747
+ *
58748
+ * The caller (tool layer) owns the destructive-key double gate and the audit
58749
+ * ledger. This method NEVER logs the literal text (only key enums / byte len).
58750
+ */
58751
+ async injectKeys(items, opts = {}) {
58752
+ if (!this.ptyProcess) throw new Error(`${this.cliName} is not running`);
58753
+ const encoded = encodeMeshSendKeys(items);
58754
+ const now = Date.now();
58755
+ const submitPending = this.engine.submitPendingUntil > now;
58756
+ const submitRetryArmed = this.submitRetryTimer !== null;
58757
+ const outboundBusy = this.pendingOutboundFlushInFlight || this.pendingOutboundQueue.length > 0;
58758
+ if (submitPending || submitRetryArmed || outboundBusy) {
58759
+ LOG2.warn("CLI", `[${this.cliType}] send_keys refused (submit_race): submitPending=${submitPending} submitRetry=${submitRetryArmed} outboundBusy=${outboundBusy} keys=${encoded.keys.join(",")}`);
58760
+ return { ok: false, refused: "submit_race", keys: encoded.keys, hasDestructive: encoded.hasDestructive };
58761
+ }
58762
+ const modalActive = this.engine.hasActionableApproval();
58763
+ if (modalActive && !encoded.hasDestructive && !opts.allowModalOverride) {
58764
+ LOG2.warn("CLI", `[${this.cliType}] send_keys refused (actionable_modal): keys=${encoded.keys.join(",")} \u2014 use mesh_approve`);
58765
+ return { ok: false, refused: "actionable_modal", keys: encoded.keys, hasDestructive: encoded.hasDestructive };
58766
+ }
58767
+ await this.writeToPty(encoded.sequence);
58768
+ LOG2.info("CLI", `[${this.cliType}] send_keys injected keys=${encoded.keys.join(",") || "(text-only)"} bytes=${Buffer.byteLength(encoded.sequence, "utf8")} destructive=${encoded.hasDestructive}`);
58769
+ return {
58770
+ ok: true,
58771
+ keys: encoded.keys,
58772
+ hasDestructive: encoded.hasDestructive,
58773
+ submits: encoded.submits,
58774
+ bytes: Buffer.byteLength(encoded.sequence, "utf8")
58775
+ };
58776
+ }
58555
58777
  flushOutboundQueue() {
58556
58778
  this.schedulePendingOutboundFlush();
58557
58779
  }
@@ -59390,6 +59612,7 @@ ${lastSnapshot}`;
59390
59612
  resetConfig: () => resetConfig,
59391
59613
  resetDebugRuntimeConfig: () => resetDebugRuntimeConfig,
59392
59614
  resetState: () => resetState,
59615
+ resolveAllowSendKeysDestructive: () => resolveAllowSendKeysDestructive,
59393
59616
  resolveAutoConvergeCodeChange: () => resolveAutoConvergeCodeChange,
59394
59617
  resolveChatMessageKind: () => resolveChatMessageKind,
59395
59618
  resolveConvergeRequiredTags: () => resolveConvergeRequiredTags,
@@ -69670,6 +69893,63 @@ ${effect.notification.body || ""}`.trim();
69670
69893
  if (!cols || !rows) return { success: false, error: "cols and rows required" };
69671
69894
  return { success: false, error: "PTY resize temporarily disabled", code: "PTY_RESIZE_DISABLED" };
69672
69895
  }
69896
+ function handleReadTerminal(h, args) {
69897
+ const targetSessionId = typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : "";
69898
+ const sessionId = targetSessionId || h.currentSession?.sessionId || "";
69899
+ if (!sessionId) return { success: false, error: "targetSessionId required" };
69900
+ const session = h.ctx.sessionRegistry?.get(sessionId);
69901
+ const instanceKey = session?.adapterKey || session?.instanceKey || sessionId;
69902
+ const instance = h.ctx.instanceManager?.getInstance(instanceKey);
69903
+ if (!instance) return { success: false, error: `Session not found: ${sessionId.split("_")[0]}` };
69904
+ if (instance.category !== "cli" || typeof instance.getTerminalScreenSnapshot !== "function") {
69905
+ return { success: false, error: "read_terminal is only supported for CLI (PTY) sessions" };
69906
+ }
69907
+ const requestedMaxBytes = typeof args?.maxBytes === "number" && Number.isFinite(args.maxBytes) ? args.maxBytes : void 0;
69908
+ const snapshot = instance.getTerminalScreenSnapshot(requestedMaxBytes);
69909
+ if (!snapshot) {
69910
+ return { success: false, error: "read_terminal is only available for coordinator-spawned mesh worker sessions" };
69911
+ }
69912
+ LOG2.info("Command", `[readTerminal] session=${sessionId.split("_")[0]} bytes=${snapshot.returnedBytes}/${snapshot.originalBytes} truncated=${snapshot.truncated} cols=${snapshot.cols} rows=${snapshot.rows}`);
69913
+ return { success: true, ...snapshot };
69914
+ }
69915
+ async function handleSendKeys(h, args) {
69916
+ const targetSessionId = typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : "";
69917
+ const sessionId = targetSessionId || h.currentSession?.sessionId || "";
69918
+ if (!sessionId) return { success: false, error: "targetSessionId required" };
69919
+ const items = Array.isArray(args?.sequence) ? args.sequence : null;
69920
+ if (!items || items.length === 0) {
69921
+ return { success: false, error: "sequence (non-empty array of {text}|{key}) required" };
69922
+ }
69923
+ const session = h.ctx.sessionRegistry?.get(sessionId);
69924
+ const instanceKey = session?.adapterKey || session?.instanceKey || sessionId;
69925
+ const instance = h.ctx.instanceManager?.getInstance(instanceKey);
69926
+ if (!instance) return { success: false, error: `Session not found: ${sessionId.split("_")[0]}` };
69927
+ if (instance.category !== "cli" || typeof instance.injectKeys !== "function") {
69928
+ return { success: false, error: "send_keys is only supported for CLI (PTY) sessions" };
69929
+ }
69930
+ const DESTRUCTIVE = /* @__PURE__ */ new Set(["CTRL_C", "ESC"]);
69931
+ const hasDestructiveRequested = items.some((it) => it && typeof it.key === "string" && DESTRUCTIVE.has(it.key));
69932
+ if (hasDestructiveRequested && args?.confirm_destructive !== true) {
69933
+ return {
69934
+ success: false,
69935
+ error: "destructive key (CTRL_C/ESC) requires confirm_destructive=true",
69936
+ refused: "destructive_unconfirmed"
69937
+ };
69938
+ }
69939
+ try {
69940
+ const result = await instance.injectKeys(items, {
69941
+ allowModalOverride: args?.allow_modal_override === true
69942
+ });
69943
+ if (!result.ok) {
69944
+ LOG2.info("Command", `[sendKeys] session=${sessionId.split("_")[0]} refused=${result.refused} keys=${result.keys.join(",")} destructive=${result.hasDestructive}`);
69945
+ return { success: false, error: `send_keys refused: ${result.refused}`, refused: result.refused, keys: result.keys, hasDestructive: result.hasDestructive };
69946
+ }
69947
+ LOG2.info("Command", `[sendKeys] session=${sessionId.split("_")[0]} injected keys=${result.keys.join(",") || "(text-only)"} bytes=${result.bytes} destructive=${result.hasDestructive} submits=${result.submits}`);
69948
+ return { success: true, keys: result.keys, hasDestructive: result.hasDestructive, submits: result.submits, bytes: result.bytes };
69949
+ } catch (e) {
69950
+ return { success: false, error: `send_keys: ${e?.message || String(e)}` };
69951
+ }
69952
+ }
69673
69953
  function handleGetProviderSettings(h, args) {
69674
69954
  const loader = h.ctx.providerLoader;
69675
69955
  const { providerType } = args || {};
@@ -70523,6 +70803,12 @@ ${effect.notification.body || ""}`.trim();
70523
70803
  return handlePtyInput(this, args);
70524
70804
  case "pty_resize":
70525
70805
  return handlePtyResize(this, args);
70806
+ // ─── MESH-READ-TERMINAL (feature 2): raw viewport read ──────────
70807
+ case "read_terminal":
70808
+ return handleReadTerminal(this, args);
70809
+ // ─── MESH-SEND-KEYS (feature 3): structured key injection ────────
70810
+ case "send_keys":
70811
+ return handleSendKeys(this, args);
70526
70812
  // ─── Provider Settings (stream-commands.ts) ──────────
70527
70813
  case "get_provider_settings":
70528
70814
  return handleGetProviderSettings(this, args);
@@ -77049,6 +77335,15 @@ ${body}
77049
77335
  * with no approval never carries recency and is never held (no regression).
77050
77336
  */
77051
77337
  static APPROVAL_RESUME_GRACE_MS = 18e3;
77338
+ // MESH-STALL-WATCH (feature 1: STALL detection): how long a coordinator-spawned
77339
+ // mesh worker's raw PTY output (lastOutputAt) may stay unchanged before the
77340
+ // status-agnostic stall watchdog fires ONE informational monitor:no_progress
77341
+ // event. Unlike the StatusMonitor no-progress watchdog (which only runs while a
77342
+ // turn is generating), this observes pure screen stasis regardless of the
77343
+ // reported status — a worker parked idle, wedged mid-turn, or spawned with no
77344
+ // output at all. 180s matches DEFAULT_MONITOR_CONFIG.noProgressThresholdSec so
77345
+ // the two watchdogs agree on the same "long interval" bound.
77346
+ static MESH_WORKER_STALL_THRESHOLD_MS = 18e4;
77052
77347
  adapter;
77053
77348
  context = null;
77054
77349
  events = [];
@@ -77062,6 +77357,16 @@ ${body}
77062
77357
  // first sets it; the other becomes a no-op.
77063
77358
  agentReadyEmitted = false;
77064
77359
  generatingStartedAt = 0;
77360
+ // MESH-STALL-WATCH (feature 1): the lastOutputAt value the stall episode is
77361
+ // currently armed against. A stall episode is "the raw PTY output has not
77362
+ // advanced past this anchor". When the adapter has never emitted output
77363
+ // (lastOutputAt === 0) the anchor is the spawn time (this.startedAt) so a
77364
+ // worker that produced NOTHING is still caught. On any new output the anchor
77365
+ // re-arms to the fresh lastOutputAt and meshStallEmittedForAnchor resets, so a
77366
+ // single continuous stall fires AT MOST ONCE and a later stall re-arms cleanly.
77367
+ // -1 = not yet initialised for this session.
77368
+ meshStallAnchorAt = -1;
77369
+ meshStallEmittedForAnchor = false;
77065
77370
  // FALSE-IDLE continuity epoch: monotonically bumped on EVERY entry into a busy
77066
77371
  // phase (→generating or →waiting_approval). The completedDebouncePending snapshots
77067
77372
  // this value at arm time (busyEpochAtArm); the flush guard requires it UNCHANGED
@@ -78240,6 +78545,124 @@ ${body}
78240
78545
  isMeshWorkerSession() {
78241
78546
  return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.meshNodeId || this.settings.launchedByCoordinator);
78242
78547
  }
78548
+ /**
78549
+ * MESH-READ-TERMINAL (feature 2: RAW terminal read). Public read of the
78550
+ * CURRENT rendered PTY viewport for the mesh_read_terminal tool, delegating to
78551
+ * the adapter's narrow getTerminalScreenSnapshot() (viewport + cursor + size
78552
+ * only; no debug buffers / parser state / history; byte-bounded, bottom-tail
78553
+ * preserved).
78554
+ *
78555
+ * Gated on isMeshWorkerSession(): this raw viewport can expose tokens /
78556
+ * command args / env / user data, so only a coordinator-spawned worker session
78557
+ * is readable. The MCP layer ALSO cross-checks mesh/session/node ownership
78558
+ * (isMeshOwnedDelegateSession) — isMeshWorkerSession alone is a broad
78559
+ * "delegated" gate, so the two together block cross-mesh access. Returns null
78560
+ * for a non-mesh session so the daemon command surfaces a clean refusal.
78561
+ */
78562
+ getTerminalScreenSnapshot(maxBytes) {
78563
+ if (!this.isMeshWorkerSession()) return null;
78564
+ return this.adapter.getTerminalScreenSnapshot(maxBytes);
78565
+ }
78566
+ /**
78567
+ * MESH-SEND-KEYS (feature 3: key injection). Public entry for the
78568
+ * mesh_send_keys tool, delegating to the adapter's injectKeys() (structured
78569
+ * key encoding + atomic write + submit-race recheck + modal fail-closed).
78570
+ *
78571
+ * Gated on isMeshWorkerSession(): PTY input into a worker is a
78572
+ * coordinator-only capability. The MCP layer ALSO cross-checks mesh/session/
78573
+ * node ownership (isMeshOwnedDelegateSession) and owns the destructive-key
78574
+ * double gate (confirm_destructive + policy) and the audit ledger. Returns a
78575
+ * refusal object for a non-mesh session so the daemon command surfaces a clean
78576
+ * error (never silently writes to a non-worker PTY).
78577
+ */
78578
+ async injectKeys(items, opts = {}) {
78579
+ if (!this.isMeshWorkerSession()) {
78580
+ return { ok: false, refused: "not_mesh_worker", keys: [], hasDestructive: false };
78581
+ }
78582
+ return this.adapter.injectKeys(items, opts);
78583
+ }
78584
+ /**
78585
+ * MESH-STALL-WATCH (feature 1: STALL detection). Status-agnostic stall
78586
+ * watchdog for coordinator-spawned mesh worker sessions. Driven by the
78587
+ * ProviderInstanceManager's existing 5s onTick loop (NO new timer) — see
78588
+ * ProviderInstanceManager.startTicking. Reuses the adapter's raw-PTY-output
78589
+ * clock (lastOutputAt, bumped on every output chunk) as the sole signal: if a
78590
+ * live worker's screen has been byte-for-byte unchanged for
78591
+ * MESH_WORKER_STALL_THRESHOLD_MS (180s), fire ONE informational
78592
+ * monitor:no_progress event down the existing task_stalled ledger +
78593
+ * pendingCoordinatorEvent path.
78594
+ *
78595
+ * Deliberately status-agnostic: it does NOT read getStatus()'s reported status
78596
+ * (which would couple it to the generating-only StatusMonitor and the
78597
+ * idle-timeout FSM). A normally-idle worker CAN trip this after 3 quiet
78598
+ * minutes; that is accepted and surfaced as an informational stall (NOT a
78599
+ * failure/auto-restart) so the coordinator judges. getStatus/getState are NOT
78600
+ * called here, so status heartbeats never move the stall anchor.
78601
+ *
78602
+ * Anchoring: the episode arms against the current lastOutputAt; a worker that
78603
+ * has emitted nothing yet (lastOutputAt === 0) anchors on this.startedAt (spawn
78604
+ * time) so a silent spawn is still caught. Any new output re-arms the anchor
78605
+ * and clears the emitted flag, so one continuous stall emits at most once and a
78606
+ * later stall re-arms cleanly.
78607
+ */
78608
+ checkMeshWorkerStall(now = Date.now()) {
78609
+ if (!this.isMeshWorkerSession()) {
78610
+ this.meshStallAnchorAt = -1;
78611
+ this.meshStallEmittedForAnchor = false;
78612
+ return;
78613
+ }
78614
+ if (!this.adapter.isAlive()) {
78615
+ this.meshStallAnchorAt = -1;
78616
+ this.meshStallEmittedForAnchor = false;
78617
+ return;
78618
+ }
78619
+ let lastOutputAt;
78620
+ try {
78621
+ const status = this.adapter.getStatus({ allowParse: false });
78622
+ lastOutputAt = typeof status?.lastOutputAt === "number" && Number.isFinite(status.lastOutputAt) ? status.lastOutputAt : 0;
78623
+ } catch {
78624
+ return;
78625
+ }
78626
+ const anchor = lastOutputAt > 0 ? lastOutputAt : this.startedAt;
78627
+ if (this.meshStallAnchorAt === -1) {
78628
+ this.meshStallAnchorAt = anchor;
78629
+ this.meshStallEmittedForAnchor = false;
78630
+ return;
78631
+ }
78632
+ if (anchor > this.meshStallAnchorAt) {
78633
+ this.meshStallAnchorAt = anchor;
78634
+ this.meshStallEmittedForAnchor = false;
78635
+ return;
78636
+ }
78637
+ if (this.meshStallEmittedForAnchor) return;
78638
+ const stalledMs = now - this.meshStallAnchorAt;
78639
+ if (stalledMs < _CliProviderInstance.MESH_WORKER_STALL_THRESHOLD_MS) return;
78640
+ this.meshStallEmittedForAnchor = true;
78641
+ let observedStatus = "unknown";
78642
+ try {
78643
+ const s2 = this.adapter.getStatus({ allowParse: false })?.status;
78644
+ if (typeof s2 === "string" && s2) observedStatus = s2;
78645
+ } catch {
78646
+ }
78647
+ if (this.isMeshWorkerSession()) {
78648
+ traceMeshEventStage("fired", this.meshTraceCtx("monitor:no_progress"), "mesh_worker_stall_watchdog");
78649
+ }
78650
+ const stalledSec = Math.round(stalledMs / 1e3);
78651
+ this.pushEvent({
78652
+ event: "monitor:no_progress",
78653
+ agentKey: `${this.type}:cli`,
78654
+ elapsedSec: stalledSec,
78655
+ timestamp: now,
78656
+ // MESH-STALL-WATCH marker: buildMeshSystemMessage generalizes the
78657
+ // coordinator message (generating-specific → "PTY output unchanged")
78658
+ // when this is set, since this watchdog fires status-agnostically.
78659
+ meshWorkerStall: true,
78660
+ lastOutputAt: this.meshStallAnchorAt,
78661
+ stalledMs,
78662
+ observedStatus,
78663
+ taskId: this.completingTurnTaskId()
78664
+ });
78665
+ }
78243
78666
  /**
78244
78667
  * AUTOAPPROVE-FLAP-RECUR (Fix A+B): how long a busy blip / modal scroll-out may
78245
78668
  * persist before the in-progress settle gate is torn down. For a delegated
@@ -79201,6 +79624,10 @@ ${buttons.join("\n")}`;
79201
79624
  this.completedDebouncePending = null;
79202
79625
  continue;
79203
79626
  }
79627
+ if (me.type === "monitor:no_progress" && this.isMeshWorkerSession()) {
79628
+ traceMeshEventDrop("mesh_worker_stall_watchdog_owns_no_progress", this.meshTraceCtx("monitor:no_progress"));
79629
+ continue;
79630
+ }
79204
79631
  this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
79205
79632
  }
79206
79633
  }
@@ -93704,7 +94131,22 @@ ${e?.stderr || ""}`;
93704
94131
  // worker session that reaches the wrong daemon used to fuzzy-inject the task body into that
93705
94132
  // daemon's own CLI session (TASKECHO coordinator self-echo). Forwarding to the owning daemon
93706
94133
  // delivers it to the real worker instead. (findAdapter is also fail-closed as the backstop.)
93707
- "agent_command"
94134
+ "agent_command",
94135
+ // read_terminal (MESH-READ-TERMINAL feature 2): mesh_read_terminal reads the CURRENT
94136
+ // rendered PTY viewport of a specific worker session. The live viewport lives ONLY on the
94137
+ // OWNING session's adapter, so when the target is a REMOTE worker the coordinator has no
94138
+ // local instance and the handler would return 'Session not found' — the exact
94139
+ // remote-worker forwarding gap of mission 6938892f. Forward it to the owning worker daemon
94140
+ // so it reads its own live screen. (It is read-only; unlike the mutations above it makes no
94141
+ // state change, but it is session-scoped identically and must reach the owning daemon.)
94142
+ "read_terminal",
94143
+ // send_keys (MESH-SEND-KEYS feature 3): mesh_send_keys injects a structured key sequence
94144
+ // into a specific worker session's PTY. The live PTY lives ONLY on the OWNING session's
94145
+ // adapter, so a remote-worker target must be forwarded to the owning daemon or the handler
94146
+ // returns 'Session not found' (same class as mission 6938892f). Unlike read_terminal this
94147
+ // MUTATES the worker PTY, so forwarding to the real owner (not a wrong local session) is
94148
+ // doubly important. The daemon re-enforces the destructive-key confirm gate after the forward.
94149
+ "send_keys"
93708
94150
  ]);
93709
94151
  function normalizeCommandSource(source) {
93710
94152
  switch (source) {
@@ -95827,7 +96269,13 @@ ${e?.stderr || ""}`;
95827
96269
  if (this.tickTimer) return;
95828
96270
  this.tickInterval = intervalMs || this.tickInterval;
95829
96271
  this.tickTimer = setInterval(async () => {
96272
+ const now = Date.now();
95830
96273
  for (const [id, instance] of this.instances) {
96274
+ try {
96275
+ instance.checkMeshWorkerStall?.(now);
96276
+ } catch (e) {
96277
+ LOG2.warn("InstanceMgr", `[InstanceManager] Mesh stall check failed for ${id}: ${e.message}`);
96278
+ }
95831
96279
  try {
95832
96280
  await instance.onTick();
95833
96281
  } catch (e) {
@@ -101276,7 +101724,7 @@ data: ${JSON.stringify(msg.data)}
101276
101724
  });
101277
101725
  }
101278
101726
  };
101279
- var import_crypto10 = require("crypto");
101727
+ var import_crypto11 = require("crypto");
101280
101728
  var import_session_host_core11 = require_dist();
101281
101729
  var BASE_KEY_SEQUENCES = {
101282
101730
  enter: "\r",
@@ -101374,7 +101822,7 @@ data: ${JSON.stringify(msg.data)}
101374
101822
  const sessionId = String(options.sessionId || "").trim();
101375
101823
  if (!sessionId) throw new Error("sessionId is required");
101376
101824
  const mode = options.mode || "read";
101377
- const clientId = options.clientId || `raw-terminal-${process.pid}-${(0, import_crypto10.randomUUID)().slice(0, 8)}`;
101825
+ const clientId = options.clientId || `raw-terminal-${process.pid}-${(0, import_crypto11.randomUUID)().slice(0, 8)}`;
101378
101826
  const client = options.client || new import_session_host_core11.SessionHostClient({ endpoint: options.endpoint });
101379
101827
  await client.connect();
101380
101828
  const attachResponse = await client.request({