@adhdev/daemon-core 0.9.82-rc.552 → 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.mjs CHANGED
@@ -119,6 +119,15 @@ function resolveDelegatedWorkerAutoApprove(meshPolicy, nodePolicy) {
119
119
  }
120
120
  return true;
121
121
  }
122
+ function resolveAllowSendKeysDestructive(meshPolicy, nodePolicy) {
123
+ if (typeof nodePolicy?.allowSendKeysDestructive === "boolean") {
124
+ return nodePolicy.allowSendKeysDestructive;
125
+ }
126
+ if (typeof meshPolicy?.allowSendKeysDestructive === "boolean") {
127
+ return meshPolicy.allowSendKeysDestructive;
128
+ }
129
+ return false;
130
+ }
122
131
  function resolveProviderMaxParallel(slots, providerType) {
123
132
  const wanted = typeof providerType === "string" ? providerType.trim().toLowerCase() : "";
124
133
  if (!wanted) return void 0;
@@ -414,10 +423,10 @@ function readInjected(value) {
414
423
  }
415
424
  function getDaemonBuildInfo() {
416
425
  if (cached) return cached;
417
- const commit = readInjected(true ? "178a437592e2f9544675a54768b48281804bdddb" : void 0) ?? "unknown";
418
- const commitShort = readInjected(true ? "178a4375" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
419
- const version = readInjected(true ? "0.9.82-rc.552" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
420
- const builtAt = readInjected(true ? "2026-07-17T04:25:41.391Z" : void 0);
426
+ const commit = readInjected(true ? "3fc4f272513b6f628ec1732ef57d9ed94e08b8ff" : void 0) ?? "unknown";
427
+ const commitShort = readInjected(true ? "3fc4f272" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
428
+ const version = readInjected(true ? "0.9.82-rc.553" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
429
+ const builtAt = readInjected(true ? "2026-07-17T06:04:22.090Z" : void 0);
421
430
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
422
431
  return cached;
423
432
  }
@@ -2982,6 +2991,8 @@ var init_dist = __esm({
2982
2991
  "mesh_send_task",
2983
2992
  "mesh_read_chat",
2984
2993
  "mesh_read_debug",
2994
+ "mesh_read_terminal",
2995
+ "mesh_send_keys",
2985
2996
  "mesh_launch_session",
2986
2997
  "mesh_git_status",
2987
2998
  "mesh_read_node_logs",
@@ -4128,6 +4139,8 @@ var init_coordinator_prompt = __esm({
4128
4139
  | \`mesh_launch_session\` | Start a new agent session on a node |
4129
4140
  | \`mesh_read_chat\` | Read recent chat messages from a delegated agent session |
4130
4141
  | \`mesh_read_debug\` | Collect a daemon-side chat/parser debug bundle for a session |
4142
+ | \`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 |
4143
+ | \`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) |
4131
4144
  | \`mesh_task_history\` | Read the task ledger \u2014 dispatches, completions, failures. Use to understand what has been done before deciding next steps |
4132
4145
  | \`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 |
4133
4146
  | \`mesh_reconcile_ledger\` | Reconcile daemon-local ledgers over P2P \u2014 import missing entries from remote nodes into the coordinator local ledger |
@@ -8785,6 +8798,13 @@ Do NOT retry on this node. Consider reassigning to a different node or asking th
8785
8798
  return `[System] ${args.nodeLabel} has stopped${metadata}. Use mesh_read_chat once if you need to inspect its last output.`;
8786
8799
  }
8787
8800
  if (args.event === "monitor:no_progress") {
8801
+ if (args.metadataEvent.meshWorkerStall === true) {
8802
+ const observedStatus = readNonEmptyString2(args.metadataEvent.observedStatus);
8803
+ const stalledMs = typeof args.metadataEvent.stalledMs === "number" ? args.metadataEvent.stalledMs : void 0;
8804
+ const stalledSuffix = stalledMs !== void 0 ? ` for ${Math.round(stalledMs / 1e3)}s` : "";
8805
+ const statusSuffix = observedStatus ? ` (observed status: ${observedStatus})` : "";
8806
+ 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.`;
8807
+ }
8788
8808
  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.`;
8789
8809
  }
8790
8810
  if (args.event === "worktree_bootstrap_complete") {
@@ -12582,6 +12602,82 @@ function sanitizeTerminalText(str) {
12582
12602
  const accumulator = new TerminalTranscriptAccumulator();
12583
12603
  return stripTerminalNoise(stripAnsi(accumulator.append(str)));
12584
12604
  }
12605
+ function encodeMeshSendKeys(items) {
12606
+ if (!Array.isArray(items) || items.length === 0) {
12607
+ throw new Error("send_keys: sequence must be a non-empty array");
12608
+ }
12609
+ if (items.length > MESH_SEND_KEYS_MAX_ITEMS) {
12610
+ throw new Error(`send_keys: sequence exceeds ${MESH_SEND_KEYS_MAX_ITEMS} items`);
12611
+ }
12612
+ const parts = [];
12613
+ const keys = [];
12614
+ let hasDestructive = false;
12615
+ let submits = false;
12616
+ let textBytes = 0;
12617
+ for (const item of items) {
12618
+ if (item && typeof item.text === "string") {
12619
+ const text = item.text;
12620
+ textBytes += Buffer.byteLength(text, "utf8");
12621
+ if (textBytes > MESH_SEND_KEYS_MAX_TEXT_BYTES) {
12622
+ throw new Error(`send_keys: total literal text exceeds ${MESH_SEND_KEYS_MAX_TEXT_BYTES} bytes`);
12623
+ }
12624
+ parts.push(text);
12625
+ submits = false;
12626
+ continue;
12627
+ }
12628
+ const keyName = item && typeof item.key === "string" ? item.key : "";
12629
+ if (!(keyName in MESH_SEND_KEY_ENCODING)) {
12630
+ throw new Error(`send_keys: unknown key '${keyName}'`);
12631
+ }
12632
+ const key2 = keyName;
12633
+ parts.push(MESH_SEND_KEY_ENCODING[key2]);
12634
+ keys.push(key2);
12635
+ if (MESH_DESTRUCTIVE_KEYS.has(key2)) hasDestructive = true;
12636
+ submits = key2 === "ENTER";
12637
+ }
12638
+ return { sequence: parts.join(""), keys, hasDestructive, submits };
12639
+ }
12640
+ function truncateToByteTailByLine(text, maxBytes) {
12641
+ const input = String(text ?? "");
12642
+ const originalBytes = Buffer.byteLength(input, "utf8");
12643
+ if (originalBytes <= maxBytes) {
12644
+ return { text: input, truncated: false, originalBytes, returnedBytes: originalBytes };
12645
+ }
12646
+ const lines = input.split("\n");
12647
+ const kept = [];
12648
+ let bytes = 0;
12649
+ for (let i = lines.length - 1; i >= 0; i--) {
12650
+ const line = lines[i];
12651
+ const lineBytes = Buffer.byteLength(line, "utf8");
12652
+ const joinCost = kept.length > 0 ? 1 : 0;
12653
+ if (bytes + lineBytes + joinCost > maxBytes) break;
12654
+ bytes += lineBytes + joinCost;
12655
+ kept.unshift(line);
12656
+ }
12657
+ if (kept.length > 0) {
12658
+ const out = kept.join("\n");
12659
+ return {
12660
+ text: out,
12661
+ truncated: true,
12662
+ originalBytes,
12663
+ returnedBytes: Buffer.byteLength(out, "utf8")
12664
+ };
12665
+ }
12666
+ const lastLine = lines[lines.length - 1] ?? "";
12667
+ const buf = Buffer.from(lastLine, "utf8");
12668
+ let slice = buf.subarray(Math.max(0, buf.length - maxBytes));
12669
+ let decoded = slice.toString("utf8");
12670
+ while (decoded.length > 0 && decoded.charCodeAt(0) === 65533 && slice.length > 0) {
12671
+ slice = slice.subarray(1);
12672
+ decoded = slice.toString("utf8");
12673
+ }
12674
+ return {
12675
+ text: decoded,
12676
+ truncated: true,
12677
+ originalBytes,
12678
+ returnedBytes: Buffer.byteLength(decoded, "utf8")
12679
+ };
12680
+ }
12585
12681
  function listCliScriptNames(scripts) {
12586
12682
  if (!scripts) return [];
12587
12683
  return Object.entries(scripts).filter(([, fn]) => typeof fn === "function").map(([name]) => name);
@@ -12783,7 +12879,7 @@ function normalizeCliProviderForRuntime(raw) {
12783
12879
  }
12784
12880
  };
12785
12881
  }
12786
- var TerminalTranscriptAccumulator, buildCliSpawnEnv;
12882
+ var TerminalTranscriptAccumulator, MESH_SEND_KEY_ENCODING, MESH_DESTRUCTIVE_KEYS, MESH_SEND_KEYS_MAX_ITEMS, MESH_SEND_KEYS_MAX_TEXT_BYTES, buildCliSpawnEnv;
12787
12883
  var init_provider_cli_shared = __esm({
12788
12884
  "src/cli-adapters/provider-cli-shared.ts"() {
12789
12885
  "use strict";
@@ -12944,6 +13040,20 @@ var init_provider_cli_shared = __esm({
12944
13040
  this.ensureRow();
12945
13041
  }
12946
13042
  };
13043
+ MESH_SEND_KEY_ENCODING = {
13044
+ ENTER: "\r",
13045
+ ESC: "\x1B",
13046
+ CTRL_C: "",
13047
+ UP: "\x1B[A",
13048
+ DOWN: "\x1B[B",
13049
+ RIGHT: "\x1B[C",
13050
+ LEFT: "\x1B[D",
13051
+ TAB: " ",
13052
+ BACKSPACE: "\x7F"
13053
+ };
13054
+ MESH_DESTRUCTIVE_KEYS = /* @__PURE__ */ new Set(["CTRL_C", "ESC"]);
13055
+ MESH_SEND_KEYS_MAX_ITEMS = 64;
13056
+ MESH_SEND_KEYS_MAX_TEXT_BYTES = 4096;
12947
13057
  buildCliSpawnEnv = sanitizeSpawnEnv;
12948
13058
  }
12949
13059
  });
@@ -18074,6 +18184,10 @@ var init_terminal_screen = __esm({
18074
18184
  getCursorPosition() {
18075
18185
  return this.terminal.getCursorPosition();
18076
18186
  }
18187
+ /** Current viewport dimensions (cols × rows). */
18188
+ getSize() {
18189
+ return { cols: this.cols, rows: this.rows };
18190
+ }
18077
18191
  dispose() {
18078
18192
  this.terminal.dispose();
18079
18193
  }
@@ -26820,6 +26934,7 @@ __export(provider_cli_adapter_exports, {
26820
26934
  normalizeCliProviderForRuntime: () => normalizeCliProviderForRuntime
26821
26935
  });
26822
26936
  import * as os16 from "os";
26937
+ import { createHash as createHash4 } from "crypto";
26823
26938
  import { DEFAULT_SESSION_HOST_COLS as DEFAULT_SESSION_HOST_COLS4, DEFAULT_SESSION_HOST_ROWS as DEFAULT_SESSION_HOST_ROWS4 } from "@adhdev/session-host-core";
26824
26939
  function appendBoundedText(current, chunk, maxChars) {
26825
26940
  if (!chunk) return current.length <= maxChars ? current : current.slice(-maxChars);
@@ -27033,6 +27148,11 @@ var init_provider_cli_adapter = __esm({
27033
27148
  static MAX_ACCUMULATED_BUFFER = 262144;
27034
27149
  parsedStatusCache = null;
27035
27150
  static SCREEN_SNAPSHOT_MIN_INTERVAL_MS = 250;
27151
+ // MESH-READ-TERMINAL (feature 2): byte caps for getTerminalScreenSnapshot.
27152
+ // Byte, not char — a multi-byte-glyph screen can exceed an MCP payload cap
27153
+ // while the char count still looks safe. 32KiB default, 64KiB absolute hard cap.
27154
+ static TERMINAL_SNAPSHOT_DEFAULT_MAX_BYTES = 32 * 1024;
27155
+ static TERMINAL_SNAPSHOT_ABSOLUTE_MAX_BYTES = 64 * 1024;
27036
27156
  // (FALSEIDLE Path-C) Consecutive gate-eligible getStatus polls a mesh/autonomous
27037
27157
  // session must show before the poll-static-idle confirm fires. 2 = one extra
27038
27158
  // status tick of hysteresis: enough to reject a single momentary-silence
@@ -28611,6 +28731,103 @@ ${lastSnapshot}`;
28611
28731
  isAlive() {
28612
28732
  return this.ptyProcess !== null;
28613
28733
  }
28734
+ /**
28735
+ * MESH-READ-TERMINAL (feature 2: RAW terminal read). Narrow, least-privilege
28736
+ * read of the CURRENT rendered viewport for mesh_read_terminal. Deliberately
28737
+ * NARROWER than getSnapshot()/getDebugSnapshot():
28738
+ * - It returns ONLY the terminal's current rendered viewport (what a human
28739
+ * would see on screen right now), the cursor position and the viewport
28740
+ * size. NO debug buffers, NO parser/FSM state, NO scrollback/history.
28741
+ * - It does NOT call getParseScreenText() (which may graft an older snapshot
28742
+ * onto the current frame for parse accuracy) — the caller asked for the
28743
+ * live viewport, not a parse-optimized composite.
28744
+ * - The payload is bounded in BYTES (UTF-8) with bottom-tail preservation so
28745
+ * a screen of multi-byte glyphs can never exceed the MCP payload cap. See
28746
+ * truncateToByteTailByLine.
28747
+ *
28748
+ * SECURITY NOTE: the raw viewport can contain tokens / command args / env
28749
+ * values / user data. Callers MUST gate this on mesh ownership and MUST NOT
28750
+ * log the returned text. Opt-in redaction is intentionally out of scope for
28751
+ * this feature and left as a future enhancement.
28752
+ *
28753
+ * `maxBytes` is clamped to [1KiB, ABSOLUTE_MAX] (default 32KiB, hard cap 64KiB).
28754
+ */
28755
+ getTerminalScreenSnapshot(maxBytes = _ProviderCliAdapter.TERMINAL_SNAPSHOT_DEFAULT_MAX_BYTES) {
28756
+ const cap = Math.min(
28757
+ _ProviderCliAdapter.TERMINAL_SNAPSHOT_ABSOLUTE_MAX_BYTES,
28758
+ Math.max(1024, Math.floor(maxBytes) || _ProviderCliAdapter.TERMINAL_SNAPSHOT_DEFAULT_MAX_BYTES)
28759
+ );
28760
+ const rawViewport = this.terminalScreen.getText() || "";
28761
+ const size = this.terminalScreen.getSize();
28762
+ const cursor = this.terminalScreen.getCursorPosition();
28763
+ const truncation = truncateToByteTailByLine(rawViewport, cap);
28764
+ const hash = createHash4("sha256").update(rawViewport, "utf8").digest("hex").slice(0, 16);
28765
+ return {
28766
+ text: truncation.text,
28767
+ cursor,
28768
+ cols: size.cols,
28769
+ rows: size.rows,
28770
+ truncated: truncation.truncated,
28771
+ originalBytes: truncation.originalBytes,
28772
+ returnedBytes: truncation.returnedBytes,
28773
+ hash
28774
+ };
28775
+ }
28776
+ /**
28777
+ * MESH-SEND-KEYS (feature 3: key injection). Inject a STRUCTURED key sequence
28778
+ * into the PTY for the mesh_send_keys tool. Reuses the same serialized write
28779
+ * path as sends (writeToPty via writeRaw semantics) so the injection FIFO-
28780
+ * orders behind any in-flight write.
28781
+ *
28782
+ * Two guards run INSIDE this method, immediately before the write, so they see
28783
+ * a consistent snapshot of the adapter's submit/echo/queue state (no async gap
28784
+ * between check and write — the encode is synchronous and the write is chained
28785
+ * atomically after it):
28786
+ *
28787
+ * 1. submit-race recheck (echo-gate): even though writeToPty is FIFO, an
28788
+ * already-SCHEDULED echo-gated Enter (engine.submitPendingUntil in the
28789
+ * future), an armed stuck-submit retry (submitRetryTimer), or an in-flight
28790
+ * pending-outbound flush can submit at a DIFFERENT tick than our write —
28791
+ * so an injected literal could be submitted by a pending Enter, or our
28792
+ * ENTER could submit a half-typed pending body. When any of those is live
28793
+ * we REFUSE the injection rather than interleave.
28794
+ *
28795
+ * 2. modal fail-closed: if the session is parked on an actionable approval
28796
+ * modal, refuse a NON-destructive injection (ENTER/text/arrows) and direct
28797
+ * the caller to mesh_approve — so a modal choice can't be confirmed via
28798
+ * send_keys to bypass the approval policy. (A destructive ESC/CTRL_C, which
28799
+ * dismisses rather than confirms, is allowed to proceed past this gate; it
28800
+ * is separately gated by confirm_destructive + policy at the tool layer.)
28801
+ *
28802
+ * The caller (tool layer) owns the destructive-key double gate and the audit
28803
+ * ledger. This method NEVER logs the literal text (only key enums / byte len).
28804
+ */
28805
+ async injectKeys(items, opts = {}) {
28806
+ if (!this.ptyProcess) throw new Error(`${this.cliName} is not running`);
28807
+ const encoded = encodeMeshSendKeys(items);
28808
+ const now = Date.now();
28809
+ const submitPending = this.engine.submitPendingUntil > now;
28810
+ const submitRetryArmed = this.submitRetryTimer !== null;
28811
+ const outboundBusy = this.pendingOutboundFlushInFlight || this.pendingOutboundQueue.length > 0;
28812
+ if (submitPending || submitRetryArmed || outboundBusy) {
28813
+ LOG.warn("CLI", `[${this.cliType}] send_keys refused (submit_race): submitPending=${submitPending} submitRetry=${submitRetryArmed} outboundBusy=${outboundBusy} keys=${encoded.keys.join(",")}`);
28814
+ return { ok: false, refused: "submit_race", keys: encoded.keys, hasDestructive: encoded.hasDestructive };
28815
+ }
28816
+ const modalActive = this.engine.hasActionableApproval();
28817
+ if (modalActive && !encoded.hasDestructive && !opts.allowModalOverride) {
28818
+ LOG.warn("CLI", `[${this.cliType}] send_keys refused (actionable_modal): keys=${encoded.keys.join(",")} \u2014 use mesh_approve`);
28819
+ return { ok: false, refused: "actionable_modal", keys: encoded.keys, hasDestructive: encoded.hasDestructive };
28820
+ }
28821
+ await this.writeToPty(encoded.sequence);
28822
+ LOG.info("CLI", `[${this.cliType}] send_keys injected keys=${encoded.keys.join(",") || "(text-only)"} bytes=${Buffer.byteLength(encoded.sequence, "utf8")} destructive=${encoded.hasDestructive}`);
28823
+ return {
28824
+ ok: true,
28825
+ keys: encoded.keys,
28826
+ hasDestructive: encoded.hasDestructive,
28827
+ submits: encoded.submits,
28828
+ bytes: Buffer.byteLength(encoded.sequence, "utf8")
28829
+ };
28830
+ }
28614
28831
  flushOutboundQueue() {
28615
28832
  this.schedulePendingOutboundFlush();
28616
28833
  }
@@ -39406,6 +39623,63 @@ function handlePtyResize(_h, args) {
39406
39623
  if (!cols || !rows) return { success: false, error: "cols and rows required" };
39407
39624
  return { success: false, error: "PTY resize temporarily disabled", code: "PTY_RESIZE_DISABLED" };
39408
39625
  }
39626
+ function handleReadTerminal(h, args) {
39627
+ const targetSessionId = typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : "";
39628
+ const sessionId = targetSessionId || h.currentSession?.sessionId || "";
39629
+ if (!sessionId) return { success: false, error: "targetSessionId required" };
39630
+ const session = h.ctx.sessionRegistry?.get(sessionId);
39631
+ const instanceKey = session?.adapterKey || session?.instanceKey || sessionId;
39632
+ const instance = h.ctx.instanceManager?.getInstance(instanceKey);
39633
+ if (!instance) return { success: false, error: `Session not found: ${sessionId.split("_")[0]}` };
39634
+ if (instance.category !== "cli" || typeof instance.getTerminalScreenSnapshot !== "function") {
39635
+ return { success: false, error: "read_terminal is only supported for CLI (PTY) sessions" };
39636
+ }
39637
+ const requestedMaxBytes = typeof args?.maxBytes === "number" && Number.isFinite(args.maxBytes) ? args.maxBytes : void 0;
39638
+ const snapshot = instance.getTerminalScreenSnapshot(requestedMaxBytes);
39639
+ if (!snapshot) {
39640
+ return { success: false, error: "read_terminal is only available for coordinator-spawned mesh worker sessions" };
39641
+ }
39642
+ LOG.info("Command", `[readTerminal] session=${sessionId.split("_")[0]} bytes=${snapshot.returnedBytes}/${snapshot.originalBytes} truncated=${snapshot.truncated} cols=${snapshot.cols} rows=${snapshot.rows}`);
39643
+ return { success: true, ...snapshot };
39644
+ }
39645
+ async function handleSendKeys(h, args) {
39646
+ const targetSessionId = typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : "";
39647
+ const sessionId = targetSessionId || h.currentSession?.sessionId || "";
39648
+ if (!sessionId) return { success: false, error: "targetSessionId required" };
39649
+ const items = Array.isArray(args?.sequence) ? args.sequence : null;
39650
+ if (!items || items.length === 0) {
39651
+ return { success: false, error: "sequence (non-empty array of {text}|{key}) required" };
39652
+ }
39653
+ const session = h.ctx.sessionRegistry?.get(sessionId);
39654
+ const instanceKey = session?.adapterKey || session?.instanceKey || sessionId;
39655
+ const instance = h.ctx.instanceManager?.getInstance(instanceKey);
39656
+ if (!instance) return { success: false, error: `Session not found: ${sessionId.split("_")[0]}` };
39657
+ if (instance.category !== "cli" || typeof instance.injectKeys !== "function") {
39658
+ return { success: false, error: "send_keys is only supported for CLI (PTY) sessions" };
39659
+ }
39660
+ const DESTRUCTIVE = /* @__PURE__ */ new Set(["CTRL_C", "ESC"]);
39661
+ const hasDestructiveRequested = items.some((it) => it && typeof it.key === "string" && DESTRUCTIVE.has(it.key));
39662
+ if (hasDestructiveRequested && args?.confirm_destructive !== true) {
39663
+ return {
39664
+ success: false,
39665
+ error: "destructive key (CTRL_C/ESC) requires confirm_destructive=true",
39666
+ refused: "destructive_unconfirmed"
39667
+ };
39668
+ }
39669
+ try {
39670
+ const result = await instance.injectKeys(items, {
39671
+ allowModalOverride: args?.allow_modal_override === true
39672
+ });
39673
+ if (!result.ok) {
39674
+ LOG.info("Command", `[sendKeys] session=${sessionId.split("_")[0]} refused=${result.refused} keys=${result.keys.join(",")} destructive=${result.hasDestructive}`);
39675
+ return { success: false, error: `send_keys refused: ${result.refused}`, refused: result.refused, keys: result.keys, hasDestructive: result.hasDestructive };
39676
+ }
39677
+ LOG.info("Command", `[sendKeys] session=${sessionId.split("_")[0]} injected keys=${result.keys.join(",") || "(text-only)"} bytes=${result.bytes} destructive=${result.hasDestructive} submits=${result.submits}`);
39678
+ return { success: true, keys: result.keys, hasDestructive: result.hasDestructive, submits: result.submits, bytes: result.bytes };
39679
+ } catch (e) {
39680
+ return { success: false, error: `send_keys: ${e?.message || String(e)}` };
39681
+ }
39682
+ }
39409
39683
  function handleGetProviderSettings(h, args) {
39410
39684
  const loader = h.ctx.providerLoader;
39411
39685
  const { providerType } = args || {};
@@ -40263,6 +40537,12 @@ var DaemonCommandHandler = class {
40263
40537
  return handlePtyInput(this, args);
40264
40538
  case "pty_resize":
40265
40539
  return handlePtyResize(this, args);
40540
+ // ─── MESH-READ-TERMINAL (feature 2): raw viewport read ──────────
40541
+ case "read_terminal":
40542
+ return handleReadTerminal(this, args);
40543
+ // ─── MESH-SEND-KEYS (feature 3): structured key injection ────────
40544
+ case "send_keys":
40545
+ return handleSendKeys(this, args);
40266
40546
  // ─── Provider Settings (stream-commands.ts) ──────────
40267
40547
  case "get_provider_settings":
40268
40548
  return handleGetProviderSettings(this, args);
@@ -46875,6 +47155,15 @@ var CliProviderInstance = class _CliProviderInstance {
46875
47155
  * with no approval never carries recency and is never held (no regression).
46876
47156
  */
46877
47157
  static APPROVAL_RESUME_GRACE_MS = 18e3;
47158
+ // MESH-STALL-WATCH (feature 1: STALL detection): how long a coordinator-spawned
47159
+ // mesh worker's raw PTY output (lastOutputAt) may stay unchanged before the
47160
+ // status-agnostic stall watchdog fires ONE informational monitor:no_progress
47161
+ // event. Unlike the StatusMonitor no-progress watchdog (which only runs while a
47162
+ // turn is generating), this observes pure screen stasis regardless of the
47163
+ // reported status — a worker parked idle, wedged mid-turn, or spawned with no
47164
+ // output at all. 180s matches DEFAULT_MONITOR_CONFIG.noProgressThresholdSec so
47165
+ // the two watchdogs agree on the same "long interval" bound.
47166
+ static MESH_WORKER_STALL_THRESHOLD_MS = 18e4;
46878
47167
  adapter;
46879
47168
  context = null;
46880
47169
  events = [];
@@ -46888,6 +47177,16 @@ var CliProviderInstance = class _CliProviderInstance {
46888
47177
  // first sets it; the other becomes a no-op.
46889
47178
  agentReadyEmitted = false;
46890
47179
  generatingStartedAt = 0;
47180
+ // MESH-STALL-WATCH (feature 1): the lastOutputAt value the stall episode is
47181
+ // currently armed against. A stall episode is "the raw PTY output has not
47182
+ // advanced past this anchor". When the adapter has never emitted output
47183
+ // (lastOutputAt === 0) the anchor is the spawn time (this.startedAt) so a
47184
+ // worker that produced NOTHING is still caught. On any new output the anchor
47185
+ // re-arms to the fresh lastOutputAt and meshStallEmittedForAnchor resets, so a
47186
+ // single continuous stall fires AT MOST ONCE and a later stall re-arms cleanly.
47187
+ // -1 = not yet initialised for this session.
47188
+ meshStallAnchorAt = -1;
47189
+ meshStallEmittedForAnchor = false;
46891
47190
  // FALSE-IDLE continuity epoch: monotonically bumped on EVERY entry into a busy
46892
47191
  // phase (→generating or →waiting_approval). The completedDebouncePending snapshots
46893
47192
  // this value at arm time (busyEpochAtArm); the flush guard requires it UNCHANGED
@@ -48066,6 +48365,124 @@ var CliProviderInstance = class _CliProviderInstance {
48066
48365
  isMeshWorkerSession() {
48067
48366
  return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.meshNodeId || this.settings.launchedByCoordinator);
48068
48367
  }
48368
+ /**
48369
+ * MESH-READ-TERMINAL (feature 2: RAW terminal read). Public read of the
48370
+ * CURRENT rendered PTY viewport for the mesh_read_terminal tool, delegating to
48371
+ * the adapter's narrow getTerminalScreenSnapshot() (viewport + cursor + size
48372
+ * only; no debug buffers / parser state / history; byte-bounded, bottom-tail
48373
+ * preserved).
48374
+ *
48375
+ * Gated on isMeshWorkerSession(): this raw viewport can expose tokens /
48376
+ * command args / env / user data, so only a coordinator-spawned worker session
48377
+ * is readable. The MCP layer ALSO cross-checks mesh/session/node ownership
48378
+ * (isMeshOwnedDelegateSession) — isMeshWorkerSession alone is a broad
48379
+ * "delegated" gate, so the two together block cross-mesh access. Returns null
48380
+ * for a non-mesh session so the daemon command surfaces a clean refusal.
48381
+ */
48382
+ getTerminalScreenSnapshot(maxBytes) {
48383
+ if (!this.isMeshWorkerSession()) return null;
48384
+ return this.adapter.getTerminalScreenSnapshot(maxBytes);
48385
+ }
48386
+ /**
48387
+ * MESH-SEND-KEYS (feature 3: key injection). Public entry for the
48388
+ * mesh_send_keys tool, delegating to the adapter's injectKeys() (structured
48389
+ * key encoding + atomic write + submit-race recheck + modal fail-closed).
48390
+ *
48391
+ * Gated on isMeshWorkerSession(): PTY input into a worker is a
48392
+ * coordinator-only capability. The MCP layer ALSO cross-checks mesh/session/
48393
+ * node ownership (isMeshOwnedDelegateSession) and owns the destructive-key
48394
+ * double gate (confirm_destructive + policy) and the audit ledger. Returns a
48395
+ * refusal object for a non-mesh session so the daemon command surfaces a clean
48396
+ * error (never silently writes to a non-worker PTY).
48397
+ */
48398
+ async injectKeys(items, opts = {}) {
48399
+ if (!this.isMeshWorkerSession()) {
48400
+ return { ok: false, refused: "not_mesh_worker", keys: [], hasDestructive: false };
48401
+ }
48402
+ return this.adapter.injectKeys(items, opts);
48403
+ }
48404
+ /**
48405
+ * MESH-STALL-WATCH (feature 1: STALL detection). Status-agnostic stall
48406
+ * watchdog for coordinator-spawned mesh worker sessions. Driven by the
48407
+ * ProviderInstanceManager's existing 5s onTick loop (NO new timer) — see
48408
+ * ProviderInstanceManager.startTicking. Reuses the adapter's raw-PTY-output
48409
+ * clock (lastOutputAt, bumped on every output chunk) as the sole signal: if a
48410
+ * live worker's screen has been byte-for-byte unchanged for
48411
+ * MESH_WORKER_STALL_THRESHOLD_MS (180s), fire ONE informational
48412
+ * monitor:no_progress event down the existing task_stalled ledger +
48413
+ * pendingCoordinatorEvent path.
48414
+ *
48415
+ * Deliberately status-agnostic: it does NOT read getStatus()'s reported status
48416
+ * (which would couple it to the generating-only StatusMonitor and the
48417
+ * idle-timeout FSM). A normally-idle worker CAN trip this after 3 quiet
48418
+ * minutes; that is accepted and surfaced as an informational stall (NOT a
48419
+ * failure/auto-restart) so the coordinator judges. getStatus/getState are NOT
48420
+ * called here, so status heartbeats never move the stall anchor.
48421
+ *
48422
+ * Anchoring: the episode arms against the current lastOutputAt; a worker that
48423
+ * has emitted nothing yet (lastOutputAt === 0) anchors on this.startedAt (spawn
48424
+ * time) so a silent spawn is still caught. Any new output re-arms the anchor
48425
+ * and clears the emitted flag, so one continuous stall emits at most once and a
48426
+ * later stall re-arms cleanly.
48427
+ */
48428
+ checkMeshWorkerStall(now = Date.now()) {
48429
+ if (!this.isMeshWorkerSession()) {
48430
+ this.meshStallAnchorAt = -1;
48431
+ this.meshStallEmittedForAnchor = false;
48432
+ return;
48433
+ }
48434
+ if (!this.adapter.isAlive()) {
48435
+ this.meshStallAnchorAt = -1;
48436
+ this.meshStallEmittedForAnchor = false;
48437
+ return;
48438
+ }
48439
+ let lastOutputAt;
48440
+ try {
48441
+ const status = this.adapter.getStatus({ allowParse: false });
48442
+ lastOutputAt = typeof status?.lastOutputAt === "number" && Number.isFinite(status.lastOutputAt) ? status.lastOutputAt : 0;
48443
+ } catch {
48444
+ return;
48445
+ }
48446
+ const anchor = lastOutputAt > 0 ? lastOutputAt : this.startedAt;
48447
+ if (this.meshStallAnchorAt === -1) {
48448
+ this.meshStallAnchorAt = anchor;
48449
+ this.meshStallEmittedForAnchor = false;
48450
+ return;
48451
+ }
48452
+ if (anchor > this.meshStallAnchorAt) {
48453
+ this.meshStallAnchorAt = anchor;
48454
+ this.meshStallEmittedForAnchor = false;
48455
+ return;
48456
+ }
48457
+ if (this.meshStallEmittedForAnchor) return;
48458
+ const stalledMs = now - this.meshStallAnchorAt;
48459
+ if (stalledMs < _CliProviderInstance.MESH_WORKER_STALL_THRESHOLD_MS) return;
48460
+ this.meshStallEmittedForAnchor = true;
48461
+ let observedStatus = "unknown";
48462
+ try {
48463
+ const s2 = this.adapter.getStatus({ allowParse: false })?.status;
48464
+ if (typeof s2 === "string" && s2) observedStatus = s2;
48465
+ } catch {
48466
+ }
48467
+ if (this.isMeshWorkerSession()) {
48468
+ traceMeshEventStage("fired", this.meshTraceCtx("monitor:no_progress"), "mesh_worker_stall_watchdog");
48469
+ }
48470
+ const stalledSec = Math.round(stalledMs / 1e3);
48471
+ this.pushEvent({
48472
+ event: "monitor:no_progress",
48473
+ agentKey: `${this.type}:cli`,
48474
+ elapsedSec: stalledSec,
48475
+ timestamp: now,
48476
+ // MESH-STALL-WATCH marker: buildMeshSystemMessage generalizes the
48477
+ // coordinator message (generating-specific → "PTY output unchanged")
48478
+ // when this is set, since this watchdog fires status-agnostically.
48479
+ meshWorkerStall: true,
48480
+ lastOutputAt: this.meshStallAnchorAt,
48481
+ stalledMs,
48482
+ observedStatus,
48483
+ taskId: this.completingTurnTaskId()
48484
+ });
48485
+ }
48069
48486
  /**
48070
48487
  * AUTOAPPROVE-FLAP-RECUR (Fix A+B): how long a busy blip / modal scroll-out may
48071
48488
  * persist before the in-progress settle gate is torn down. For a delegated
@@ -49027,6 +49444,10 @@ ${buttons.join("\n")}`;
49027
49444
  this.completedDebouncePending = null;
49028
49445
  continue;
49029
49446
  }
49447
+ if (me.type === "monitor:no_progress" && this.isMeshWorkerSession()) {
49448
+ traceMeshEventDrop("mesh_worker_stall_watchdog_owns_no_progress", this.meshTraceCtx("monitor:no_progress"));
49449
+ continue;
49450
+ }
49030
49451
  this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
49031
49452
  }
49032
49453
  }
@@ -63629,7 +64050,22 @@ var MESH_FORWARDABLE_SESSION_COMMANDS = /* @__PURE__ */ new Set([
63629
64050
  // worker session that reaches the wrong daemon used to fuzzy-inject the task body into that
63630
64051
  // daemon's own CLI session (TASKECHO coordinator self-echo). Forwarding to the owning daemon
63631
64052
  // delivers it to the real worker instead. (findAdapter is also fail-closed as the backstop.)
63632
- "agent_command"
64053
+ "agent_command",
64054
+ // read_terminal (MESH-READ-TERMINAL feature 2): mesh_read_terminal reads the CURRENT
64055
+ // rendered PTY viewport of a specific worker session. The live viewport lives ONLY on the
64056
+ // OWNING session's adapter, so when the target is a REMOTE worker the coordinator has no
64057
+ // local instance and the handler would return 'Session not found' — the exact
64058
+ // remote-worker forwarding gap of mission 6938892f. Forward it to the owning worker daemon
64059
+ // so it reads its own live screen. (It is read-only; unlike the mutations above it makes no
64060
+ // state change, but it is session-scoped identically and must reach the owning daemon.)
64061
+ "read_terminal",
64062
+ // send_keys (MESH-SEND-KEYS feature 3): mesh_send_keys injects a structured key sequence
64063
+ // into a specific worker session's PTY. The live PTY lives ONLY on the OWNING session's
64064
+ // adapter, so a remote-worker target must be forwarded to the owning daemon or the handler
64065
+ // returns 'Session not found' (same class as mission 6938892f). Unlike read_terminal this
64066
+ // MUTATES the worker PTY, so forwarding to the real owner (not a wrong local session) is
64067
+ // doubly important. The daemon re-enforces the destructive-key confirm gate after the forward.
64068
+ "send_keys"
63633
64069
  ]);
63634
64070
  function normalizeCommandSource(source) {
63635
64071
  switch (source) {
@@ -65774,7 +66210,13 @@ var ProviderInstanceManager = class {
65774
66210
  if (this.tickTimer) return;
65775
66211
  this.tickInterval = intervalMs || this.tickInterval;
65776
66212
  this.tickTimer = setInterval(async () => {
66213
+ const now = Date.now();
65777
66214
  for (const [id, instance] of this.instances) {
66215
+ try {
66216
+ instance.checkMeshWorkerStall?.(now);
66217
+ } catch (e) {
66218
+ LOG.warn("InstanceMgr", `[InstanceManager] Mesh stall check failed for ${id}: ${e.message}`);
66219
+ }
65778
66220
  try {
65779
66221
  await instance.onTick();
65780
66222
  } catch (e) {
@@ -72920,6 +73362,7 @@ export {
72920
73362
  resetConfig,
72921
73363
  resetDebugRuntimeConfig,
72922
73364
  resetState,
73365
+ resolveAllowSendKeysDestructive,
72923
73366
  resolveAutoConvergeCodeChange,
72924
73367
  resolveChatMessageKind,
72925
73368
  resolveConvergeRequiredTags,