@cydm/pie 4.7.0 → 4.8.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.
@@ -20,11 +20,12 @@ import {
20
20
  parseStatusFile,
21
21
  peerHealth,
22
22
  peerLabel,
23
+ registerIpcRuntime,
23
24
  resolveIpcConfig,
24
25
  takeDispatchFrame,
25
26
  wrapInboundText,
26
27
  wrappedMessageMarker
27
- } from "../../../chunks/chunk-7UAUDXZW.js";
28
+ } from "../../../chunks/chunk-EGZ5TZRM.js";
28
29
  import "../../../chunks/chunk-ZPJ3BNQB.js";
29
30
  import {
30
31
  Type
@@ -912,6 +913,15 @@ var Runtime = class {
912
913
  results = new RequestResultStore();
913
914
  executionFailure;
914
915
  active = false;
916
+ /** Bounded, memory-only display projection for worker Peek. It deliberately
917
+ * stores only assistant text blocks and tool names/status — never thinking,
918
+ * args, results, user input, or session-log data. */
919
+ peekTurn = 0;
920
+ peekStartedAt;
921
+ peekItems = [];
922
+ peekAssistantIndex;
923
+ peekLastVisible;
924
+ peekPendingVisible;
915
925
  polledInputs = /* @__PURE__ */ new Map();
916
926
  /** Server readiness gate: no status writes before the listener is up. */
917
927
  serverReady = false;
@@ -967,6 +977,8 @@ var Runtime = class {
967
977
  ...displaySessionName ? { displaySessionName } : {},
968
978
  ...typeof model === "string" && model ? { model } : {},
969
979
  isManager: this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager",
980
+ sessionControls: this.ctx.capabilities?.interactiveUI === false && this.ctx.capabilities.editorInjection === true,
981
+ workerPeek: this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME !== "manager",
970
982
  imBinding: currentImBinding()
971
983
  });
972
984
  return { ...snapshot, allowPeers: [...this.allowPolicy.snapshot()], undeliveredInjections: this.delivery?.undeliveredInjections ?? snapshot.undeliveredInjections ?? 0 };
@@ -976,18 +988,17 @@ var Runtime = class {
976
988
  return writeStatusFile(this.discoveryDir, { ...this.currentStatus(), updatedAt: Date.now() }, (message) => this.ctx.log(message));
977
989
  }
978
990
  async handleEnvelope(envelope, respond, signal) {
979
- const reply = (kind, text) => {
980
- respond({
981
- v: IPC_PROTOCOL_VERSION,
982
- id: `${envelope.id}:r`,
983
- from: this.instanceId,
984
- to: envelope.from,
985
- kind,
986
- createdAt: Date.now(),
987
- replyTo: envelope.id,
988
- ...text !== void 0 ? { text } : {}
989
- });
990
- };
991
+ const replyEnvelope = (kind, text) => ({
992
+ v: IPC_PROTOCOL_VERSION,
993
+ id: `${envelope.id}:r`,
994
+ from: this.instanceId,
995
+ to: envelope.from,
996
+ kind,
997
+ createdAt: Date.now(),
998
+ replyTo: envelope.id,
999
+ ...text !== void 0 ? { text } : {}
1000
+ });
1001
+ const reply = (kind, text) => respond(replyEnvelope(kind, text));
991
1002
  switch (envelope.kind) {
992
1003
  case "control": {
993
1004
  if (this.sessionId === null) {
@@ -1008,6 +1019,16 @@ var Runtime = class {
1008
1019
  reply("ack", JSON.stringify({ ok: false, message: "invalid control frame" }));
1009
1020
  return;
1010
1021
  }
1022
+ if (parsed.control === "session.peek") {
1023
+ if (!(this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME !== "manager")) {
1024
+ reply("ack", JSON.stringify({ ok: false, message: "host does not advertise worker Peek" }));
1025
+ return;
1026
+ }
1027
+ const base = replyEnvelope("ack");
1028
+ const text = this.boundedPeekAckText((candidate) => Buffer.byteLength(JSON.stringify({ ...base, text: candidate, auth: "0".repeat(64) }) + "\n"));
1029
+ respond({ ...base, text });
1030
+ return;
1031
+ }
1011
1032
  const applier = this.ctx.applyIpcControl;
1012
1033
  if (!applier) {
1013
1034
  reply("ack", JSON.stringify({ ok: false, message: "host does not support control frames" }));
@@ -1137,16 +1158,119 @@ var Runtime = class {
1137
1158
  return readStatusFile(this.discoveryDir, peerInstanceId)?.displayName;
1138
1159
  }
1139
1160
  // ---- lifecycle events ----
1161
+ trimPeek() {
1162
+ while (this.peekItems.length > 40 || this.peekItems.reduce((n, item) => n + item.text.length + (item.progress?.length ?? 0), 0) > 8e3) {
1163
+ if (this.peekItems.length === 1) {
1164
+ const item = this.peekItems[0];
1165
+ item.text = item.text.slice(-4e3);
1166
+ if (item.progress) item.progress = item.progress.slice(-500);
1167
+ break;
1168
+ }
1169
+ this.peekItems.shift();
1170
+ if (this.peekAssistantIndex !== void 0) this.peekAssistantIndex = this.peekAssistantIndex === 0 ? void 0 : this.peekAssistantIndex - 1;
1171
+ }
1172
+ }
1173
+ addPeekAssistant(text, delta = false) {
1174
+ const clean = text.replace(/\u0000/g, "");
1175
+ if (!clean || !delta && !clean.trim()) return;
1176
+ if (delta && this.peekAssistantIndex !== void 0 && this.peekItems[this.peekAssistantIndex]?.kind === "assistant") {
1177
+ const item = this.peekItems[this.peekAssistantIndex];
1178
+ item.text = (item.text + clean).slice(-4e3);
1179
+ item.at = Date.now();
1180
+ } else {
1181
+ const display = delta ? clean : clean.trim();
1182
+ this.peekItems.push({ at: Date.now(), kind: "assistant", text: display.slice(-4e3) });
1183
+ this.peekAssistantIndex = this.peekItems.length - 1;
1184
+ }
1185
+ const visible = { at: Date.now(), text: this.peekItems[this.peekAssistantIndex].text };
1186
+ if (this.active) this.peekPendingVisible = visible;
1187
+ else this.peekLastVisible = visible;
1188
+ this.trimPeek();
1189
+ }
1190
+ safeProgress(partial) {
1191
+ if (!partial || typeof partial !== "object") return void 0;
1192
+ const p = partial;
1193
+ if (!p.details || typeof p.details !== "object" || !("increment" in p.details) || !Array.isArray(p.content)) return void 0;
1194
+ const text = p.content.map((block) => block && typeof block === "object" && block.type === "text" && typeof block.text === "string" ? block.text : "").filter(Boolean).at(-1)?.replace(/\u0000/g, "").trim();
1195
+ return text ? text.slice(0, 500) : void 0;
1196
+ }
1197
+ peekSnapshot() {
1198
+ const now = Date.now();
1199
+ const items = this.peekItems.map(({ toolCallId: _id, startedAt, done, progress, ...item }) => item.kind === "tool" && startedAt !== void 0 ? { ...item, text: `${done ? "Finished" : "Running"} ${item.text} \xB7 ${Math.max(0, Math.floor(((done ? item.at : now) - startedAt) / 1e3))}s${progress ? ` \xB7 ${progress}` : ""}` } : item);
1200
+ return {
1201
+ active: this.active,
1202
+ turn: this.peekTurn,
1203
+ ...this.peekStartedAt ? { startedAt: this.peekStartedAt } : {},
1204
+ generatedAt: now,
1205
+ items,
1206
+ ...this.peekLastVisible ? { lastVisible: { ...this.peekLastVisible } } : {}
1207
+ };
1208
+ }
1209
+ boundedPeekAckText(frameBytes) {
1210
+ const snapshot = this.peekSnapshot();
1211
+ const encode = () => JSON.stringify({ ok: true, message: JSON.stringify(snapshot) });
1212
+ const newest = snapshot.items.at(-1);
1213
+ if (!snapshot.active && newest?.kind === "assistant" && snapshot.lastVisible?.text === newest.text) delete snapshot.lastVisible;
1214
+ let text = encode();
1215
+ while (frameBytes(text) > 8e3) {
1216
+ if (snapshot.items.length > 1) {
1217
+ snapshot.items.shift();
1218
+ } else {
1219
+ const item = snapshot.items[0];
1220
+ const visible = snapshot.lastVisible;
1221
+ if (visible && visible.text.length > 128 && (snapshot.active || !item || visible.text.length >= item.text.length)) {
1222
+ visible.text = visible.text.slice(-Math.max(128, visible.text.length - 256));
1223
+ } else if (item?.text.length) {
1224
+ if (item.text.length <= 128) snapshot.items.shift();
1225
+ else item.text = item.text.slice(-Math.max(128, item.text.length - 256));
1226
+ } else if (visible) {
1227
+ delete snapshot.lastVisible;
1228
+ } else break;
1229
+ }
1230
+ text = encode();
1231
+ }
1232
+ return text;
1233
+ }
1140
1234
  onEvent(event) {
1141
1235
  switch (event.type) {
1142
1236
  case "turn:start": {
1237
+ this.peekTurn++;
1238
+ this.peekStartedAt = Date.now();
1239
+ this.peekItems = [];
1240
+ this.peekAssistantIndex = void 0;
1241
+ this.peekPendingVisible = void 0;
1143
1242
  this.executionFailure = void 0;
1144
1243
  this.active = true;
1145
1244
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1146
1245
  return;
1147
1246
  }
1148
- case "tool:execution:start":
1247
+ case "assistant:display-delta": {
1248
+ if (typeof event.delta === "string") this.addPeekAssistant(event.delta, true);
1249
+ return;
1250
+ }
1251
+ case "tool:execution:start": {
1252
+ this.peekAssistantIndex = void 0;
1253
+ if (event.toolName && event.toolCallId) this.peekItems.push({ at: Date.now(), kind: "tool", text: event.toolName.slice(0, 120), toolCallId: event.toolCallId, startedAt: Date.now() });
1254
+ this.trimPeek();
1255
+ if (this.projection.updateFromEvent(event)) this.writeStatus();
1256
+ return;
1257
+ }
1258
+ case "tool:execution:update": {
1259
+ const item = event.toolCallId ? this.peekItems.find((i) => i.toolCallId === event.toolCallId) : void 0;
1260
+ const progress = this.safeProgress(event.partialResult);
1261
+ if (item && !item.done && progress) {
1262
+ item.progress = progress;
1263
+ item.at = Date.now();
1264
+ this.trimPeek();
1265
+ }
1266
+ return;
1267
+ }
1149
1268
  case "tool:execution:end": {
1269
+ const item = event.toolCallId ? this.peekItems.find((i) => i.toolCallId === event.toolCallId) : void 0;
1270
+ if (item && !item.done) {
1271
+ item.done = true;
1272
+ item.at = Date.now();
1273
+ }
1150
1274
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1151
1275
  return;
1152
1276
  }
@@ -1156,6 +1280,8 @@ var Runtime = class {
1156
1280
  case "agent:end":
1157
1281
  case "turn:failed":
1158
1282
  case "turn:cancelled": {
1283
+ if (event.type === "agent:end" && !this.executionFailure && this.peekPendingVisible) this.peekLastVisible = this.peekPendingVisible;
1284
+ this.peekPendingVisible = void 0;
1159
1285
  if (this.projection.updateFromEvent(event)) this.writeStatus();
1160
1286
  this.answerAwaitingPeers(event.type !== "agent:end" || Boolean(this.executionFailure));
1161
1287
  this.active = false;
@@ -1171,6 +1297,11 @@ var Runtime = class {
1171
1297
  this.clearNotifyFallbacks();
1172
1298
  this.notifyGeneration++;
1173
1299
  this.projection.resetSessionState();
1300
+ this.peekTurn = 0;
1301
+ this.peekStartedAt = void 0;
1302
+ this.peekItems = [];
1303
+ this.peekLastVisible = void 0;
1304
+ this.peekPendingVisible = void 0;
1174
1305
  this.executionFailure = void 0;
1175
1306
  this.active = false;
1176
1307
  this.writeStatus();
@@ -1189,6 +1320,13 @@ var Runtime = class {
1189
1320
  }
1190
1321
  }
1191
1322
  } else {
1323
+ if (message?.role === "assistant" && Array.isArray(message.content)) {
1324
+ const visible = message.content.map((block) => block && typeof block === "object" && block.type === "text" && typeof block.text === "string" ? String(block.text) : "").join("");
1325
+ if (visible) {
1326
+ const streamed = this.peekAssistantIndex !== void 0 ? this.peekItems[this.peekAssistantIndex]?.text : void 0;
1327
+ if (streamed !== visible) this.addPeekAssistant(visible);
1328
+ }
1329
+ }
1192
1330
  if (message?.role === "assistant") {
1193
1331
  const outcome = message;
1194
1332
  if (outcome.stopReason === "error" || outcome.stopReason === "aborted") this.executionFailure = outcome.stopReason;
@@ -1562,6 +1700,34 @@ ${outcome.text}`
1562
1700
  return ` ${label} [${file.state}]${sid}`;
1563
1701
  }).join("\n");
1564
1702
  }
1703
+ /** Panel controls must originate from this process's real advertised IPC
1704
+ * identity. Besides the authenticated target gate, enforce both advertised
1705
+ * directions before exposing transcript-like data. */
1706
+ async sendBoundControl(peerRef, control, payload, expected, waitMs = 6e3) {
1707
+ const target = expected ? readStatusFile(this.discoveryDir, expected.instanceId) : this.resolvePeer(peerRef);
1708
+ if (!target || !target.port) return { ok: false, detail: `Session not found: ${peerRef}` };
1709
+ if (expected && (target.instanceId !== expected.instanceId || target.sessionId !== expected.sessionId))
1710
+ return { ok: false, detail: "Worker instance or session no longer matches the issued card. Reopen it from /panel." };
1711
+ if (!this.allowPolicy.allows(target.instanceId)) return { ok: false, detail: "Denied by manager sender allow policy." };
1712
+ if (!(target.allowPeers?.includes("*") || target.allowPeers?.includes(this.instanceId)))
1713
+ return { ok: false, detail: "Denied by worker recipient allow policy." };
1714
+ if (!this.transport) return { ok: false, unknown: true, detail: "Manager IPC transport is unavailable." };
1715
+ try {
1716
+ const reply = await this.transport.send(target.instanceId, target.port, "control", {
1717
+ sessionId: target.sessionId ?? "",
1718
+ text: JSON.stringify({ control, payload }),
1719
+ awaitAck: true,
1720
+ waitMs,
1721
+ replyKinds: /* @__PURE__ */ new Set(["ack"])
1722
+ });
1723
+ if (reply?.text) {
1724
+ const ack = JSON.parse(reply.text);
1725
+ if (typeof ack?.ok === "boolean") return { ok: ack.ok, detail: `Peer receipt: ${reply.text}` };
1726
+ }
1727
+ } catch {
1728
+ }
1729
+ return { ok: false, unknown: true, detail: "No verified receipt. The request may already have been applied." };
1730
+ }
1565
1731
  /** MULTI-AGENT IM v2 Phase 2.3 — send an enumerated CONTROL frame to a
1566
1732
  * peer (first control: model.set). Returns the peer's receipt (the ack
1567
1733
  * envelope text, a small JSON object). The frame bypasses the target's
@@ -1585,7 +1751,7 @@ ${outcome.text}`
1585
1751
  waitMs,
1586
1752
  replyKinds: /* @__PURE__ */ new Set(["ack"])
1587
1753
  });
1588
- if (!reply) return { content: [{ type: "text", text: `No receipt from ${peerLabel(target.instanceId, target.displayName)} within ${waitMs}ms \u2014 the control may or may not have landed; re-send is safe (controls are idempotent by contract).` }], isError: true };
1754
+ if (!reply) return { content: [{ type: "text", text: `No receipt from ${peerLabel(target.instanceId, target.displayName)} within ${waitMs}ms \u2014 the control may or may not have landed. ${control === "session.compact" ? "Check session.context before submitting again." : "Check the target state before retrying."}` }], isError: true };
1589
1755
  return { content: [{ type: "text", text: reply.text ?? "(empty receipt)" }] };
1590
1756
  }
1591
1757
  async sendToPeer(peerRef, text, _wait, _waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
@@ -1814,6 +1980,7 @@ function pieIpcExtension(ctx) {
1814
1980
  }
1815
1981
  }
1816
1982
  const runtime = new Runtime(ctx, config, discoveryDir);
1983
+ const unregisterRuntime = registerIpcRuntime(discoveryDir, runtime);
1817
1984
  const serverEligible = ctx.capabilities.eventSink && ctx.capabilities.longLived;
1818
1985
  ctx.log(`pie-ipc: enabled as ${runtime.instanceId} (${serverEligible ? "server+client (starting listener)" : "client-only"})`);
1819
1986
  if (serverEligible) {
@@ -1856,7 +2023,9 @@ function pieIpcExtension(ctx) {
1856
2023
  "turn:completed",
1857
2024
  "turn:failed",
1858
2025
  "turn:cancelled",
2026
+ "assistant:display-delta",
1859
2027
  "tool:execution:start",
2028
+ "tool:execution:update",
1860
2029
  "tool:execution:end",
1861
2030
  "session:changed",
1862
2031
  "message:end"
@@ -1923,7 +2092,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1923
2092
  ctx.registerTool({
1924
2093
  name: "ipc_control_notify",
1925
2094
  label: "Send a control frame to a Pie peer",
1926
- description: "Send an enumerated CONTROL frame to another Pie process (multi-agent IM v2). The frame is applied by the peer's host DIRECTLY \u2014 it never enters the peer's turn or session history. Controls: 'model.set' with payload {model: 'provider/modelId'} switches the peer's model; 'thinking.set' with payload {level: '...'} switches the peer's thinking level; 'session.context' (payload {}) reads the peer's context estimate (headless hosts only \u2014 the receipt message is JSON with estimatedTokens/contextWindow/percent/autoCompact figures); 'session.compact' (payload {}) requests a MANUAL compaction on the peer (headless hosts only; accepted means started \u2014 observe the result via session.context). Receipt (success or structured refusal) returns as this tool's result. Controls are idempotent: re-sending after an uncertain outcome is safe.",
2095
+ description: "Send an enumerated CONTROL frame to another Pie process (multi-agent IM v2). The frame is applied by the peer's host DIRECTLY \u2014 it never enters the peer's turn or session history. Controls: 'model.set' with payload {model: 'provider/modelId'} switches the peer's model; 'thinking.set' with payload {level: '...'} switches the peer's thinking level; 'session.context' (payload {}) reads the peer's context estimate (headless hosts only \u2014 the receipt message is JSON with estimatedTokens/contextWindow/percent/autoCompact figures); 'session.compact' (payload {}) requests a MANUAL compaction on the peer (headless hosts only; accepted confirms submission, not that compaction started or completed \u2014 read compactionRunning and lastCompactOutcome via session.context). Receipt (success or structured refusal) returns as this tool's result. If the session.compact receipt is uncertain, do not replay it: check session.context before submitting again.",
1927
2096
  parameters: Type.Object({
1928
2097
  to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1929
2098
  control: Type.Union([Type.Literal("model.set"), Type.Literal("thinking.set"), Type.Literal("session.context"), Type.Literal("session.compact")], { description: "Control to apply (enumerated whitelist)" }),
@@ -1956,7 +2125,7 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1956
2125
  ctx.registerTool({
1957
2126
  name: "self_control",
1958
2127
  label: "Send a control frame to this session's host",
1959
- description: "Send an enumerated CONTROL frame to THIS session's own host (the process running you). The host applies it directly \u2014 it never enters the turn pipeline or session history. Controls: 'model.set' with payload {model: 'provider/modelId'} switches YOUR model (same validation as the user's /model); 'thinking.set' with payload {level: 'off|minimal|low|medium|high|xhigh'} switches YOUR thinking level (same path as the user's /think; a sensible self-tuning knob \u2014 low for cheap lookups, high for hard reasoning). Both apply from the host's NEXT agent execution \u2014 the current execution (including tool-continuation rounds) finishes on the settings it started with. 'session.context' (payload {}) reads YOUR host's context estimate (headless hosts; receipt message is JSON); 'session.compact' (payload {}) requests a MANUAL compaction of THIS session \u2014 **refused while a turn is streaming (you are always mid-turn when you call this, so expect a refusal; the IM panel is the intended entry)**. Receipt (success or structured refusal) returns as this tool's result. Controls are idempotent: re-sending after an uncertain outcome is safe.",
2128
+ description: "Send an enumerated CONTROL frame to THIS session's own host (the process running you). The host applies it directly \u2014 it never enters the turn pipeline or session history. Controls: 'model.set' with payload {model: 'provider/modelId'} switches YOUR model (same validation as the user's /model); 'thinking.set' with payload {level: 'off|minimal|low|medium|high|xhigh'} switches YOUR thinking level (same path as the user's /think; a sensible self-tuning knob \u2014 low for cheap lookups, high for hard reasoning). Both apply from the host's NEXT agent execution \u2014 the current execution (including tool-continuation rounds) finishes on the settings it started with. 'session.context' (payload {}) reads YOUR host's context estimate (headless hosts; receipt message is JSON); 'session.compact' (payload {}) requests a MANUAL compaction of THIS session \u2014 **refused while a turn is streaming (you are always mid-turn when you call this, so expect a refusal; the IM panel is the intended entry)**. Receipt (success or structured refusal) returns as this tool's result. If the session.compact receipt is uncertain, do not replay it: check session.context before submitting again.",
1960
2129
  parameters: Type.Object({
1961
2130
  control: Type.Union([Type.Literal("model.set"), Type.Literal("thinking.set"), Type.Literal("session.context"), Type.Literal("session.compact")], { description: "Control to apply (enumerated host whitelist)" }),
1962
2131
  payload: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Control payload. model.set requires {model: 'provider/modelId'}; thinking.set requires {level: 'off|minimal|low|medium|high|xhigh'}" })),
@@ -2110,6 +2279,7 @@ Usage: /tools/ipc name <new-name>`;
2110
2279
  }
2111
2280
  });
2112
2281
  ctx.registerCleanup?.(() => {
2282
+ unregisterRuntime();
2113
2283
  runtime.dispose();
2114
2284
  });
2115
2285
  }
@@ -13,7 +13,7 @@ import {
13
13
  import "../../../chunks/chunk-LZQXQOPJ.js";
14
14
 
15
15
  // builtin/extensions/pie-proc/index.ts
16
- import { spawn } from "node:child_process";
16
+ import { execFileSync, spawn } from "node:child_process";
17
17
  import { createRequire } from "node:module";
18
18
  import { fileURLToPath } from "node:url";
19
19
  import * as fs from "node:fs";
@@ -38,6 +38,7 @@ var DEFAULT_MAX_WORKERS = 50;
38
38
  var DEFAULT_CONFIG = { allowCwd: [], maxWorkers: DEFAULT_MAX_WORKERS, killGraceMs: 15e3, defaultTtlMs: 0 };
39
39
  var IM_FORWARD_ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "chatId", "openId", "allowUsers", "retryBackoffMs", "larkCliProfile"]);
40
40
  var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
41
+ var LAUNCH_TOKEN_ENV = "PIE_PROC_LAUNCH_TOKEN";
41
42
  function configDirRoot() {
42
43
  const env = process.env.PIE_CODING_AGENT_DIR;
43
44
  if (!env) return path.join(os.homedir(), ".pie");
@@ -189,17 +190,157 @@ function casRegistry(mutate) {
189
190
  function updateRegistry(mutate) {
190
191
  return casRegistry(mutate);
191
192
  }
192
- function workerLiveness(record) {
193
- if (record.pid === 0) return "dead";
193
+ function processExists(pid) {
194
+ if (!Number.isSafeInteger(pid) || pid <= 1) return false;
194
195
  try {
195
- process.kill(record.pid, 0);
196
+ process.kill(pid, 0);
197
+ return true;
198
+ } catch (error) {
199
+ return error.code === "EPERM";
200
+ }
201
+ }
202
+ function probeProcessGroup(pgid) {
203
+ if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 1) return "dead";
204
+ try {
205
+ process.kill(-pgid, 0);
206
+ return "alive";
207
+ } catch (error) {
208
+ return error.code === "EPERM" ? "eperm" : "dead";
209
+ }
210
+ }
211
+ function isZombieProcess(pid) {
212
+ if (process.platform === "win32") return false;
213
+ try {
214
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "stat="], {
215
+ encoding: "utf8",
216
+ timeout: 3e3,
217
+ stdio: ["ignore", "pipe", "pipe"],
218
+ env: { ...process.env, LC_ALL: "C", LANG: "C" }
219
+ }).trim();
220
+ if (!out) return false;
221
+ return out.startsWith("Z");
222
+ } catch {
223
+ return "unknown";
224
+ }
225
+ }
226
+ function readProcessGroupMembers(pgid) {
227
+ if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 1) return [];
228
+ try {
229
+ const out = execFileSync("ps", ["-e", "-o", "pid=,pgid=,uid=,stat=,lstart="], {
230
+ encoding: "utf8",
231
+ timeout: 3e3,
232
+ stdio: ["ignore", "pipe", "pipe"],
233
+ env: { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC" }
234
+ });
235
+ const members = [];
236
+ for (const rawLine of out.split(/\r?\n/)) {
237
+ const line = rawLine.trim();
238
+ if (!line) continue;
239
+ const match = /^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/.exec(line);
240
+ if (!match) continue;
241
+ const pid = Number(match[1]);
242
+ const memberPgid = Number(match[2]);
243
+ const uid = Number(match[3]);
244
+ const stat = match[4];
245
+ if (memberPgid !== pgid) continue;
246
+ if (stat.startsWith("Z")) continue;
247
+ const normalized = match[5].replace(/\s+/g, " ").trim();
248
+ const parsedStart = Date.parse(`${normalized} UTC`);
249
+ members.push({
250
+ pid,
251
+ uid,
252
+ stat,
253
+ startedAtMs: Number.isFinite(parsedStart) ? parsedStart : void 0
254
+ });
255
+ }
256
+ return members;
257
+ } catch {
258
+ return void 0;
259
+ }
260
+ }
261
+ function hasBoundedToken(haystack, needle) {
262
+ let idx = haystack.indexOf(needle);
263
+ while (idx !== -1) {
264
+ const beforeOk = idx === 0 || /\s/.test(haystack[idx - 1]);
265
+ const afterIdx = idx + needle.length;
266
+ const afterOk = afterIdx === haystack.length || /\s/.test(haystack[afterIdx]);
267
+ if (beforeOk && afterOk) return true;
268
+ idx = haystack.indexOf(needle, idx + 1);
269
+ }
270
+ return false;
271
+ }
272
+ function verifyProcessEnvOwnership(pid, marker, pieDir) {
273
+ if (process.platform === "linux") {
274
+ let raw2;
275
+ try {
276
+ raw2 = fs.readFileSync(`/proc/${pid}/environ`, "utf8");
277
+ } catch {
278
+ return "unverified";
279
+ }
280
+ let sawOtherToken = false;
281
+ for (const entry of raw2.split("\0")) {
282
+ if (entry === `${LAUNCH_TOKEN_ENV}=${marker}`) return "matched";
283
+ if (pieDir && entry === `PIE_CODING_AGENT_DIR=${pieDir}`) return "matched";
284
+ if (entry.startsWith(`${LAUNCH_TOKEN_ENV}=`)) sawOtherToken = true;
285
+ }
286
+ return sawOtherToken ? "foreign" : "unverified";
287
+ }
288
+ let raw;
289
+ try {
290
+ raw = execFileSync("ps", ["eww", "-p", String(pid), "-o", "command="], {
291
+ encoding: "utf8",
292
+ timeout: 3e3,
293
+ stdio: ["ignore", "pipe", "pipe"],
294
+ env: { ...process.env, LC_ALL: "C", LANG: "C" }
295
+ });
196
296
  } catch {
197
- return "dead";
297
+ return "unverified";
198
298
  }
299
+ if (!raw) return "unverified";
300
+ if (hasBoundedToken(raw, `${LAUNCH_TOKEN_ENV}=${marker}`)) return "matched";
301
+ if (pieDir && hasBoundedToken(raw, `PIE_CODING_AGENT_DIR=${pieDir}`)) return "matched";
302
+ if (raw.includes(`${LAUNCH_TOKEN_ENV}=`)) return "foreign";
303
+ return "unverified";
304
+ }
305
+ function workerLiveness(record, opts = {}) {
306
+ if (record.pid === 0 || !Number.isSafeInteger(record.pid) || record.pid <= 1) return "dead";
199
307
  const marker = record.launchToken ?? record.sessionId;
200
- const cmd = readProcessCommandLine(record.pid);
201
- if (cmd === void 0) return "unknown";
202
- return cmd.includes(marker) ? "alive" : "dead";
308
+ if (processExists(record.pid)) {
309
+ const cmd = readProcessCommandLine(record.pid);
310
+ if (cmd === void 0) return "unknown";
311
+ if (cmd.includes(marker)) return "alive";
312
+ const zombie = isZombieProcess(record.pid);
313
+ if (zombie === "unknown") return "unknown";
314
+ if (!zombie) return "dead";
315
+ }
316
+ if (process.platform !== "win32") {
317
+ const groupProbe = probeProcessGroup(record.pid);
318
+ if (groupProbe === "dead") return "dead";
319
+ if (groupProbe === "eperm") return "unknown";
320
+ const hasSpawnedAt = typeof record.spawnedAt === "number" && Number.isFinite(record.spawnedAt);
321
+ if (!hasSpawnedAt) return "unknown";
322
+ const bootAtMs = Date.now() - os.uptime() * 1e3;
323
+ if (record.spawnedAt < bootAtMs - 5e3) return "dead";
324
+ const members = readProcessGroupMembers(record.pid);
325
+ if (members === void 0) return "unknown";
326
+ if (members.length === 0) return "dead";
327
+ if (members.some((m) => m.pid === record.pid)) return "unknown";
328
+ const selfUid = typeof process.getuid === "function" ? process.getuid() : void 0;
329
+ if (selfUid !== void 0 && members.some((m) => m.uid !== selfUid)) return "unknown";
330
+ for (const member of members) {
331
+ if (member.startedAtMs === void 0) return "unknown";
332
+ if (member.startedAtMs < record.spawnedAt - 5e3) return "dead";
333
+ }
334
+ let envMatched = false;
335
+ for (const member of members) {
336
+ const ownership = verifyProcessEnvOwnership(member.pid, marker, record.pieDir);
337
+ if (ownership === "foreign") return "dead";
338
+ if (ownership === "matched") envMatched = true;
339
+ }
340
+ if (envMatched || opts.trustVerifiedGroup) return "orphaned_group";
341
+ return "unknown";
342
+ }
343
+ return "dead";
203
344
  }
204
345
  function canonicalDir(dir) {
205
346
  const resolved = path.resolve(expandTilde(dir));
@@ -357,6 +498,38 @@ function pieProc(ctx) {
357
498
  ctx.log(`pie-proc: reservation release for gen ${generation} failed (${error instanceof Error ? error.message : String(error)}); sweep will retry`);
358
499
  }
359
500
  };
501
+ const signalWorkerProcessGroup = (pid, signal, opts = {}) => {
502
+ if (!Number.isSafeInteger(pid) || pid <= 1) return;
503
+ if (process.platform === "win32") {
504
+ try {
505
+ execFileSync("taskkill.exe", ["/F", "/T", "/PID", String(pid)], {
506
+ windowsHide: true,
507
+ stdio: "ignore",
508
+ timeout: 5e3
509
+ });
510
+ return;
511
+ } catch {
512
+ }
513
+ if (!opts.groupOnly) {
514
+ try {
515
+ process.kill(pid, signal);
516
+ } catch {
517
+ }
518
+ }
519
+ return;
520
+ }
521
+ try {
522
+ process.kill(-pid, signal);
523
+ return;
524
+ } catch {
525
+ }
526
+ if (!opts.groupOnly) {
527
+ try {
528
+ process.kill(pid, signal);
529
+ } catch {
530
+ }
531
+ }
532
+ };
360
533
  const sweep = () => {
361
534
  try {
362
535
  if (abortedGenerations.size > 0) {
@@ -410,14 +583,31 @@ function pieProc(ctx) {
410
583
  changed = true;
411
584
  continue;
412
585
  }
586
+ if (liveness === "orphaned_group") {
587
+ if (w.orphanSignaledAt === void 0) {
588
+ signalWorkerProcessGroup(w.pid, "SIGTERM", { groupOnly: true });
589
+ ctx.log(`pie-proc: orphaned process group detected for dead worker ${w.name} (pgid ${w.pid}); sent SIGTERM`);
590
+ keep.push({ ...w, orphanSignaledAt: cutoff });
591
+ changed = true;
592
+ } else if (cutoff - w.orphanSignaledAt >= currentConfig().killGraceMs) {
593
+ signalWorkerProcessGroup(w.pid, "SIGKILL", { groupOnly: true });
594
+ ctx.log(`pie-proc: orphaned process group for ${w.name} (pgid ${w.pid}) survived grace window; escalated to SIGKILL`);
595
+ if (w.orphanEscalatedAt === void 0) {
596
+ keep.push({ ...w, orphanEscalatedAt: cutoff });
597
+ changed = true;
598
+ } else {
599
+ keep.push(w);
600
+ }
601
+ } else {
602
+ keep.push(w);
603
+ }
604
+ continue;
605
+ }
413
606
  const ttl = w.kind === "resident" ? w.ttlMs ?? currentConfig().defaultTtlMs : 0;
414
607
  if (ttl > 0 && liveness === "alive" && cutoff - Math.max(w.lastActiveAt, observeActivity(w)) > ttl) {
415
- try {
416
- process.kill(w.pid, "SIGTERM");
417
- } catch {
418
- }
608
+ signalWorkerProcessGroup(w.pid, "SIGTERM");
419
609
  ctx.log(`pie-proc: idle TTL signaled worker ${w.name} (idle > ${Math.round(ttl / 1e3)}s, identity verified)`);
420
- keep.push({ ...w, ttlMs: 0 });
610
+ keep.push({ ...w, ttlMs: 0, orphanSignaledAt: cutoff });
421
611
  changed = true;
422
612
  continue;
423
613
  }
@@ -594,6 +784,7 @@ function pieProc(ctx) {
594
784
  PIE_CODING_AGENT_DIR: pieDir,
595
785
  PIE_IPC_CONFIG_DIR: inheritedIpcRoot,
596
786
  PIE_PROC_REGISTRY_ROOT: inheritedRegistryRoot,
787
+ [LAUNCH_TOKEN_ENV]: launchToken,
597
788
  PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME
598
789
  };
599
790
  if (params.kind === "oneshot") {
@@ -654,9 +845,12 @@ function pieProc(ctx) {
654
845
  };
655
846
  });
656
847
  } catch (error) {
657
- try {
658
- child.kill("SIGKILL");
659
- } catch {
848
+ if (typeof child.pid === "number") signalWorkerProcessGroup(child.pid, "SIGKILL");
849
+ else {
850
+ try {
851
+ child.kill("SIGKILL");
852
+ } catch {
853
+ }
660
854
  }
661
855
  releaseReservation(generation);
662
856
  throw error instanceof Error ? error : new Error(String(error));
@@ -690,25 +884,35 @@ function pieProc(ctx) {
690
884
  if (liveness === "unknown") {
691
885
  throw new Error(`worker "${name}" (pid ${target.pid}): identity could not be verified (probe failed); refusing to signal an unverified pid. Retry shortly, or inspect the process manually before removing the registry entry.`);
692
886
  }
693
- try {
694
- process.kill(target.pid, opts.force ? "SIGKILL" : "SIGTERM");
695
- } catch {
696
- }
697
- if (!opts.force) {
887
+ const verifiedGroupOpts = { trustVerifiedGroup: true };
888
+ signalWorkerProcessGroup(target.pid, opts.force ? "SIGKILL" : "SIGTERM", {
889
+ groupOnly: liveness === "orphaned_group"
890
+ });
891
+ if (opts.force) {
892
+ const killDeadline = Date.now() + 1500;
893
+ while (Date.now() < killDeadline) {
894
+ await new Promise((r) => setTimeout(r, 100));
895
+ if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
896
+ }
897
+ } else {
698
898
  const deadline = Date.now() + currentConfig().killGraceMs;
699
899
  while (Date.now() < deadline) {
700
- await new Promise((r) => setTimeout(r, 300));
701
- if (workerLiveness(target) === "dead") break;
900
+ await new Promise((r) => setTimeout(r, 200));
901
+ if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
702
902
  }
703
- if (workerLiveness(target) === "alive") {
704
- try {
705
- process.kill(target.pid, "SIGKILL");
706
- } catch {
903
+ const afterGrace = workerLiveness(target, verifiedGroupOpts);
904
+ if (afterGrace === "alive" || afterGrace === "orphaned_group") {
905
+ signalWorkerProcessGroup(target.pid, "SIGKILL", {
906
+ groupOnly: afterGrace === "orphaned_group"
907
+ });
908
+ const killDeadline = Date.now() + 1500;
909
+ while (Date.now() < killDeadline) {
910
+ await new Promise((r) => setTimeout(r, 100));
911
+ if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
707
912
  }
708
- await new Promise((r) => setTimeout(r, 500));
709
913
  }
710
914
  }
711
- const finalState = workerLiveness(target);
915
+ const finalState = workerLiveness(target, verifiedGroupOpts);
712
916
  if (finalState === "dead") {
713
917
  updateRegistry((snap) => ({ next: snap.workers.filter((w) => w.generation !== target.generation), result: void 0 }));
714
918
  ctx.log(`pie-proc: killed worker "${name}" (pid ${target.pid}, gen ${target.generation})`);