@cydm/pie 4.2.0 → 4.3.1

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.
@@ -1,4 +1,28 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ BoundedIdSet,
4
+ DEFAULT_SEND_WAIT_MS,
5
+ FrameDecoder,
6
+ HEARTBEAT_INTERVAL_MS,
7
+ IPC_PROTOCOL_VERSION,
8
+ MAX_BODY_CHARS,
9
+ MAX_INBOX_MESSAGES,
10
+ MAX_INFLIGHT_SENDS,
11
+ MAX_STATUS_BODY_CHARS,
12
+ MAX_STATUS_FILE_BYTES,
13
+ assistantBodyText,
14
+ clipBody,
15
+ foldLifecycleEvent,
16
+ generateInstanceId,
17
+ isValidInstanceId,
18
+ isWrappedInboundText,
19
+ parseStatusFile,
20
+ peerHealth,
21
+ peerLabel,
22
+ resolveIpcConfig,
23
+ wrapInboundText,
24
+ wrappedMessageMarker
25
+ } from "../../../chunks/chunk-GJLSYBFN.js";
2
26
  import {
3
27
  Type
4
28
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -10,337 +34,6 @@ import * as os from "node:os";
10
34
  import * as path4 from "node:path";
11
35
  import { randomUUID as randomUUID2 } from "node:crypto";
12
36
 
13
- // builtin/extensions/pie-ipc/pure.ts
14
- import { randomBytes } from "node:crypto";
15
- var IPC_PROTOCOL_VERSION = 1;
16
- var INSTANCE_ID_PATTERN = /^pie-[a-z0-9]{12}$/;
17
- var MAX_STATUS_FILE_BYTES = 128 * 1024;
18
- var MAX_DISPLAY_NAME_CHARS = 64;
19
- var MAX_STATUS_TEXT_FIELD_CHARS = 4096;
20
- var MAX_BODY_CHARS = 8e3;
21
- var MAX_STATUS_BODY_CHARS = 2e3;
22
- var STATUS_FILE_STALE_MS = 12e4;
23
- var HEARTBEAT_INTERVAL_MS = 2e4;
24
- var DEFAULT_SEND_WAIT_MS = 12e4;
25
- var MAX_SEEN_ENVELOPE_IDS = 1e3;
26
- var MAX_INBOX_MESSAGES = 100;
27
- var MAX_INFLIGHT_SENDS = 8;
28
- var INSTANCE_ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
29
- function generateInstanceId(randomSource = defaultRandomBytes) {
30
- const bytes = randomSource(12);
31
- let id = "";
32
- for (const byte of bytes) {
33
- id += INSTANCE_ID_ALPHABET[byte % INSTANCE_ID_ALPHABET.length];
34
- }
35
- return `pie-${id}`;
36
- }
37
- function defaultRandomBytes(count) {
38
- return randomBytes(count);
39
- }
40
- function isValidInstanceId(id) {
41
- return INSTANCE_ID_PATTERN.test(id);
42
- }
43
- function peerLabel(instanceId, displayName) {
44
- const name = displayName?.trim();
45
- if (name) return name;
46
- return instanceId.length > 12 ? instanceId.slice(0, 12) : instanceId;
47
- }
48
- var ENVELOPE_KINDS = /* @__PURE__ */ new Set([
49
- "hello",
50
- "bye",
51
- "ping",
52
- "message",
53
- "ack",
54
- "result",
55
- "state.get",
56
- "state",
57
- "result.get"
58
- ]);
59
- var LIFECYCLE_STATES = /* @__PURE__ */ new Set(["working", "idle", "blocked"]);
60
- function parseEnvelope(raw) {
61
- let parsed;
62
- try {
63
- parsed = JSON.parse(raw);
64
- } catch {
65
- return null;
66
- }
67
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
68
- const record = parsed;
69
- if (typeof record.v !== "number" || record.v !== IPC_PROTOCOL_VERSION) return null;
70
- if (typeof record.id !== "string" || !/^[a-zA-Z0-9:-]{1,128}$/.test(record.id)) return null;
71
- if (typeof record.from !== "string" || !isValidInstanceId(record.from)) return null;
72
- if (typeof record.to !== "string" || !isValidInstanceId(record.to)) return null;
73
- if (record.text !== void 0 && (typeof record.text !== "string" || record.text.length > MAX_BODY_CHARS + 100)) return null;
74
- if (record.sessionId !== void 0 && (typeof record.sessionId !== "string" || record.sessionId.length > 256)) return null;
75
- if (record.replyTo !== void 0 && (typeof record.replyTo !== "string" || !/^[a-zA-Z0-9:-]{1,128}$/.test(record.replyTo))) return null;
76
- if (record.waitMs !== void 0 && (typeof record.waitMs !== "number" || !Number.isFinite(record.waitMs) || record.waitMs < 0 || record.waitMs > 6e5)) return null;
77
- if (record.notifyCompletion !== void 0 && typeof record.notifyCompletion !== "boolean") return null;
78
- if (record.subscriberSession !== void 0 && (typeof record.subscriberSession !== "string" || record.subscriberSession.length > 256)) return null;
79
- if (typeof record.kind !== "string" || !ENVELOPE_KINDS.has(record.kind)) return null;
80
- if (typeof record.createdAt !== "number" || !Number.isSafeInteger(record.createdAt) || record.createdAt < 0) return null;
81
- const envelope = {
82
- v: record.v,
83
- id: record.id,
84
- from: record.from,
85
- to: record.to,
86
- kind: record.kind,
87
- createdAt: record.createdAt
88
- };
89
- if (typeof record.auth === "string" && /^[a-f0-9]{64}$/.test(record.auth)) envelope.auth = record.auth;
90
- if (typeof record.sessionId === "string") envelope.sessionId = record.sessionId;
91
- if (typeof record.text === "string") envelope.text = record.text;
92
- if (typeof record.replyTo === "string") envelope.replyTo = record.replyTo;
93
- if (typeof record.waitMs === "number" && Number.isFinite(record.waitMs)) envelope.waitMs = record.waitMs;
94
- if (record.notifyCompletion === true) envelope.notifyCompletion = true;
95
- if (typeof record.subscriberSession === "string") envelope.subscriberSession = record.subscriberSession;
96
- return envelope;
97
- }
98
- var FrameTooLargeError = class extends Error {
99
- constructor() {
100
- super("pie-ipc frame exceeds byte cap");
101
- this.name = "FrameTooLargeError";
102
- }
103
- };
104
- var FrameDecoder = class {
105
- buffer = "";
106
- get partial() {
107
- return this.buffer.length > 0;
108
- }
109
- push(chunk) {
110
- this.buffer += chunk;
111
- if (this.buffer.split("\n").some((line) => Buffer.byteLength(line, "utf8") > 64 * 1024)) {
112
- this.buffer = "";
113
- throw new FrameTooLargeError();
114
- }
115
- const envelopes = [];
116
- let newline = this.buffer.indexOf("\n");
117
- while (newline !== -1) {
118
- const line = this.buffer.slice(0, newline).trim();
119
- this.buffer = this.buffer.slice(newline + 1);
120
- if (line) {
121
- const envelope = parseEnvelope(line);
122
- if (envelope) envelopes.push(envelope);
123
- }
124
- newline = this.buffer.indexOf("\n");
125
- }
126
- return envelopes;
127
- }
128
- };
129
- var WRAP_PREFIX = "[pie-ipc]";
130
- function wrapInboundText(fromLabel, text, at = Date.now(), messageId) {
131
- const stamp = new Date(at).toISOString().slice(11, 19);
132
- const marker = messageId ? ` #${clipMarker(messageId)} ` : " ";
133
- return `${WRAP_PREFIX} ${stamp}${marker}peer "${clipLabel(fromLabel)}" says:
134
- ${clipBody(text, MAX_BODY_CHARS)}`;
135
- }
136
- function isWrappedInboundText(text) {
137
- return text.startsWith(`${WRAP_PREFIX} `);
138
- }
139
- function wrappedMessageMarker(text) {
140
- if (!isWrappedInboundText(text)) return null;
141
- const firstLine = text.split("\n", 1)[0];
142
- const match = / #(\S+) peer "/.exec(firstLine);
143
- return match ? match[1] : null;
144
- }
145
- function clipMarker(id) {
146
- const clipped = id;
147
- return clipped || "noid";
148
- }
149
- function clipLabel(label) {
150
- const collapsed = label.replace(/\s+/g, " ").trim().slice(0, 60);
151
- return collapsed || "unknown";
152
- }
153
- function clipBody(text, maxChars = MAX_BODY_CHARS) {
154
- if (text.length <= maxChars) return text;
155
- return `${text.slice(0, maxChars)}\u2026[truncated ${text.length - maxChars} chars]`;
156
- }
157
- var BoundedIdSet = class {
158
- constructor(max = MAX_SEEN_ENVELOPE_IDS) {
159
- this.max = max;
160
- }
161
- max;
162
- seen = /* @__PURE__ */ new Map();
163
- /** Returns true when the id is new (and records it). */
164
- add(id, now = Date.now()) {
165
- if (this.seen.has(id)) return false;
166
- this.seen.set(id, now);
167
- if (this.seen.size > this.max) {
168
- const drop = Math.max(1, Math.floor(this.max / 4));
169
- let dropped = 0;
170
- for (const key of this.seen.keys()) {
171
- if (dropped >= drop) break;
172
- this.seen.delete(key);
173
- dropped += 1;
174
- }
175
- }
176
- return true;
177
- }
178
- has(id) {
179
- return this.seen.has(id);
180
- }
181
- get size() {
182
- return this.seen.size;
183
- }
184
- };
185
- var signalAliveCheck = (pid) => {
186
- try {
187
- process.kill(pid, 0);
188
- return true;
189
- } catch (error) {
190
- return error.code === "EPERM";
191
- }
192
- };
193
- function peerHealth(file, now = Date.now(), aliveCheck = signalAliveCheck) {
194
- if (Number.isInteger(file.pid) && file.pid > 0 && !aliveCheck(file.pid)) return "dead";
195
- if (now - file.updatedAt > STATUS_FILE_STALE_MS) return "stale";
196
- return "alive";
197
- }
198
- function parseStatusFile(raw) {
199
- let parsed;
200
- try {
201
- parsed = JSON.parse(raw);
202
- } catch {
203
- return null;
204
- }
205
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
206
- const record = parsed;
207
- if (record.schema !== 1) return null;
208
- if (typeof record.instanceId !== "string" || !isValidInstanceId(record.instanceId)) return null;
209
- if (typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0 || record.pid > 99999999) return null;
210
- if (typeof record.protocol !== "number" || record.protocol !== IPC_PROTOCOL_VERSION) return null;
211
- if (typeof record.displayName !== "string" || !record.displayName || record.displayName.length > MAX_DISPLAY_NAME_CHARS) return null;
212
- if (hasControlChars(record.displayName)) return null;
213
- if (record.sessionId !== null && (typeof record.sessionId !== "string" || record.sessionId.length > 256 || hasControlChars(record.sessionId))) return null;
214
- if (typeof record.cwd !== "string" || record.cwd.length > MAX_STATUS_TEXT_FIELD_CHARS || hasControlChars(record.cwd)) return null;
215
- if (typeof record.startedAt !== "number" || !Number.isSafeInteger(record.startedAt) || record.startedAt < 0) return null;
216
- if (typeof record.updatedAt !== "number" || !Number.isSafeInteger(record.updatedAt) || record.updatedAt < 0) return null;
217
- if (typeof record.state !== "string" || !LIFECYCLE_STATES.has(record.state)) return null;
218
- const file = {
219
- schema: 1,
220
- instanceId: record.instanceId,
221
- pid: record.pid,
222
- protocol: record.protocol,
223
- displayName: record.displayName,
224
- sessionId: record.sessionId,
225
- cwd: record.cwd,
226
- startedAt: record.startedAt,
227
- updatedAt: record.updatedAt,
228
- state: record.state
229
- };
230
- if (Array.isArray(record.allowPeers) && record.allowPeers.length <= 1e3 && record.allowPeers.every((id) => typeof id === "string" && (id === "*" || isValidInstanceId(id)))) file.allowPeers = record.allowPeers;
231
- if (typeof record.secret === "string" && /^[a-f0-9]{64}$/.test(record.secret)) file.secret = record.secret;
232
- if (typeof record.sessionName === "string" && !hasControlChars(record.sessionName) && record.sessionName.length <= MAX_DISPLAY_NAME_CHARS) file.sessionName = record.sessionName;
233
- if (typeof record.displaySessionName === "string" && !hasControlChars(record.displaySessionName) && record.displaySessionName.length <= MAX_DISPLAY_NAME_CHARS) file.displaySessionName = record.displaySessionName;
234
- if (typeof record.currentTool === "string" && !hasControlChars(record.currentTool) && record.currentTool.length <= 200) file.currentTool = record.currentTool;
235
- if (typeof record.blockedSince === "number" && Number.isSafeInteger(record.blockedSince) && record.blockedSince >= 0) file.blockedSince = record.blockedSince;
236
- if (typeof record.turnStartedAt === "number" && Number.isSafeInteger(record.turnStartedAt) && record.turnStartedAt >= 0) file.turnStartedAt = record.turnStartedAt;
237
- if (typeof record.undeliveredInjections === "number" && Number.isFinite(record.undeliveredInjections)) file.undeliveredInjections = Math.min(100, Math.max(0, Math.floor(record.undeliveredInjections)));
238
- if (typeof record.lastBodyText === "string" && record.lastBodyText.length <= MAX_STATUS_TEXT_FIELD_CHARS && !/[\u0000-\u0008\u000b-\u001f\u007f]/.test(record.lastBodyText)) file.lastBodyText = record.lastBodyText;
239
- if (typeof record.lastBodyAt === "number" && Number.isSafeInteger(record.lastBodyAt) && record.lastBodyAt >= 0) file.lastBodyAt = record.lastBodyAt;
240
- if (typeof record.port === "number" && Number.isInteger(record.port) && record.port > 0 && record.port <= 65535) file.port = record.port;
241
- return file;
242
- }
243
- function hasControlChars(text) {
244
- return /[\u0000-\u001f\u007f]/.test(text);
245
- }
246
- var BLOCKING_TOOL_NAMES = /* @__PURE__ */ new Set(["ask_user_multi"]);
247
- function isBlockingTool(toolName) {
248
- return BLOCKING_TOOL_NAMES.has(toolName);
249
- }
250
- function foldLifecycleEvent(current, event, now = Date.now()) {
251
- switch (event.type) {
252
- case "turn:start":
253
- case "agent:start": {
254
- const next = { state: "working", turnStartedAt: now };
255
- if (current.blockedSince !== void 0) next.blockedSince = current.blockedSince;
256
- return next;
257
- }
258
- case "tool:execution:start": {
259
- if (current.state === "idle") return { ...current, state: "working", turnStartedAt: current.turnStartedAt ?? now };
260
- if (event.toolName && isBlockingTool(event.toolName) && current.state !== "blocked") {
261
- return { ...current, state: "blocked", blockedSince: now, currentTool: event.toolName };
262
- }
263
- return { ...current, currentTool: event.toolName };
264
- }
265
- case "tool:execution:end": {
266
- if (current.state === "blocked" && (!event.toolName || isBlockingTool(event.toolName))) {
267
- return { ...current, state: "working", blockedSince: void 0, currentTool: void 0 };
268
- }
269
- return current;
270
- }
271
- case "turn:completed":
272
- case "turn:failed":
273
- case "turn:cancelled":
274
- case "agent:end": {
275
- if (current.state === "idle") return current;
276
- return { state: "idle" };
277
- }
278
- default:
279
- return current;
280
- }
281
- }
282
- function resolveIpcConfig(configLayers) {
283
- const problems = [];
284
- let invalidConfig = false;
285
- const merged = {};
286
- for (const layer of configLayers) {
287
- if (layer.content === void 0) continue;
288
- try {
289
- const parsed = JSON.parse(layer.content);
290
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
291
- problems.push(`${layer.file}: root is not an object`);
292
- invalidConfig = true;
293
- continue;
294
- }
295
- Object.assign(merged, parsed);
296
- } catch (error) {
297
- problems.push(`${layer.file}: ${error instanceof Error ? error.message : String(error)}`);
298
- invalidConfig = true;
299
- }
300
- }
301
- if (merged.enabled !== void 0 && typeof merged.enabled !== "boolean") {
302
- problems.push("pie-ipc: enabled must be a boolean");
303
- invalidConfig = true;
304
- }
305
- if (invalidConfig || merged.enabled === false) return { config: null, problems };
306
- const config = { enabled: true, allowPeers: ["*"], autoInject: true };
307
- if (typeof merged.displayName === "string" && merged.displayName.trim()) {
308
- config.displayName = merged.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 60);
309
- }
310
- const envName = process.env.PIE_IPC_DISPLAY_NAME;
311
- if (typeof envName === "string" && envName.trim()) {
312
- config.displayName = envName.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 60);
313
- }
314
- if (Array.isArray(merged.allowPeers)) {
315
- config.allowPeers = merged.allowPeers.filter((id) => typeof id === "string" && (id === "*" || isValidInstanceId(id))).slice(0, 1e3);
316
- } else if (merged.allowPeers !== void 0) {
317
- config.allowPeers = [];
318
- problems.push("pie-ipc: allowPeers must be an array");
319
- }
320
- if (merged.autoInject !== void 0) config.autoInject = merged.autoInject === true;
321
- if (typeof merged.maxBodyChars === "number" && Number.isFinite(merged.maxBodyChars)) {
322
- const bounded = Math.min(Math.max(Math.floor(merged.maxBodyChars), 100), MAX_BODY_CHARS);
323
- if (bounded !== merged.maxBodyChars) {
324
- problems.push(`pie-ipc: maxBodyChars clamped to ${bounded}`);
325
- }
326
- config.maxBodyChars = bounded;
327
- }
328
- return { config, problems };
329
- }
330
- function assistantBodyText(message) {
331
- if (message?.role !== "assistant" || !Array.isArray(message.content)) return "";
332
- let text = "";
333
- let hasToolCalls = false;
334
- for (const block of message.content) {
335
- if (typeof block !== "object" || block === null) continue;
336
- const record = block;
337
- if (record.type === "text" && typeof record.text === "string") text += record.text;
338
- else if (record.type === "toolCall") hasToolCalls = true;
339
- }
340
- if (hasToolCalls) return "";
341
- return text.trim();
342
- }
343
-
344
37
  // builtin/extensions/pie-ipc/discovery.ts
345
38
  import * as fs2 from "node:fs";
346
39
 
@@ -348,7 +41,7 @@ import * as fs2 from "node:fs";
348
41
  import { createRequire } from "node:module";
349
42
  import * as path2 from "node:path";
350
43
  import * as fs from "node:fs";
351
- import { randomBytes as randomBytes2 } from "node:crypto";
44
+ import { randomBytes } from "node:crypto";
352
45
 
353
46
  // builtin/extensions/pie-ipc/windows-path.ts
354
47
  import * as path from "node:path";
@@ -530,7 +223,7 @@ function initialize() {
530
223
  }),
531
224
  remove: (dir, name) => pinned(dir, false, () => remove(dir, name)),
532
225
  write: (dir, name, raw) => pinned(dir, true, () => {
533
- const target = fileName(dir, name), tempName = `.${randomBytes2(16).toString("hex")}.tmp`, temp = fileName(dir, tempName);
226
+ const target = fileName(dir, name), tempName = `.${randomBytes(16).toString("hex")}.tmp`, temp = fileName(dir, tempName);
534
227
  let created = false;
535
228
  try {
536
229
  const h = withPrivateSecurity((sa) => handle(temp, false, 1073872896, 1, sa));
@@ -579,7 +272,7 @@ function windowsSecurity() {
579
272
 
580
273
  // builtin/extensions/pie-ipc/discovery.ts
581
274
  import * as path3 from "node:path";
582
- import { randomBytes as randomBytes3 } from "node:crypto";
275
+ import { randomBytes as randomBytes2 } from "node:crypto";
583
276
  function ipcDiscoveryDir(configDir) {
584
277
  return process.platform === "win32" ? `${canonicalWindowsDirectory(configDir)}\\run\\ipc` : path3.join(configDir, "run", "ipc");
585
278
  }
@@ -605,7 +298,7 @@ function writeStatusFile(discoveryDir, file, log) {
605
298
  windowsSecurity().write(discoveryDir, `${file.instanceId}.json`, raw);
606
299
  return true;
607
300
  }
608
- temp = path3.join(discoveryDir, `.${randomBytes3(16).toString("hex")}.tmp`);
301
+ temp = path3.join(discoveryDir, `.${randomBytes2(16).toString("hex")}.tmp`);
609
302
  const handle = fs2.openSync(temp, "wx", 384);
610
303
  try {
611
304
  fs2.writeFileSync(handle, raw);
@@ -834,11 +527,11 @@ function buildStatusFile(input) {
834
527
 
835
528
  // builtin/extensions/pie-ipc/transport.ts
836
529
  import * as net from "node:net";
837
- import { createHmac, randomBytes as randomBytes4, randomUUID, timingSafeEqual } from "node:crypto";
530
+ import { createHmac, randomBytes as randomBytes3, randomUUID, timingSafeEqual } from "node:crypto";
838
531
  import { StringDecoder } from "node:string_decoder";
839
532
  var CLOSE_FLUSH_TIMEOUT_MS = 1e3;
840
533
  function signEnvelope(e, secret) {
841
- const payload = [e.v, e.id, e.from, e.to, e.kind, e.createdAt, e.sessionId ?? null, e.text ?? null, e.replyTo ?? null, e.waitMs ?? null, e.notifyCompletion ?? null, e.subscriberSession ?? null];
534
+ const payload = [e.v, e.id, e.from, e.to, e.kind, e.createdAt, e.sessionId ?? null, e.text ?? null, e.replyTo ?? null, e.waitMs ?? null, e.notifyCompletion ?? null, e.control ?? null, e.userAssigned ?? null, e.subscriberSession ?? null];
842
535
  return { ...e, auth: createHmac("sha256", secret).update(JSON.stringify(payload)).digest("hex") };
843
536
  }
844
537
  function verified(e, secret) {
@@ -849,7 +542,7 @@ var IpcTransport = class {
849
542
  constructor(host) {
850
543
  this.host = host;
851
544
  this.instanceId = host.instanceId;
852
- this.secret = host.secret ?? randomBytes4(32).toString("hex");
545
+ this.secret = host.secret ?? randomBytes3(32).toString("hex");
853
546
  this.server = net.createServer((socket) => this.accept(socket));
854
547
  this.server.on("error", () => {
855
548
  });
@@ -986,9 +679,9 @@ var IpcTransport = class {
986
679
  if (!this.seen.add(`${e.from}:${e.id}`)) return;
987
680
  try {
988
681
  if (this.closed) return;
989
- this.host.onEnvelope(e, (reply) => {
682
+ void Promise.resolve(this.host.onEnvelope(e, (reply) => {
990
683
  if (reply.from === this.instanceId && reply.to === e.from && reply.replyTo === e.id) this.write(socket, reply, this.secret);
991
- }, lifecycle.signal);
684
+ }, lifecycle.signal)).catch(() => socket.destroy());
992
685
  } catch {
993
686
  socket.destroy();
994
687
  }
@@ -1020,7 +713,7 @@ var IpcTransport = class {
1020
713
  return new Promise((resolve2) => {
1021
714
  const socket = new net.Socket();
1022
715
  this.sockets.add(socket);
1023
- const envelope = { v: IPC_PROTOCOL_VERSION, id: options.requestId ?? randomUUID(), from: this.instanceId, to: peerInstanceId, kind, createdAt: Date.now(), ...options.text !== void 0 ? { text: clipBody(options.text) } : {}, ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}, ...options.replyTo ? { replyTo: options.replyTo } : {}, waitMs: options.expectReply ? waitMs : 0, ...options.notifyCompletion === true ? { notifyCompletion: true } : {}, ...options.subscriberSession !== void 0 ? { subscriberSession: options.subscriberSession } : {} };
716
+ const envelope = { v: IPC_PROTOCOL_VERSION, id: options.requestId ?? randomUUID(), from: this.instanceId, to: peerInstanceId, kind, createdAt: Date.now(), ...options.text !== void 0 ? { text: clipBody(options.text) } : {}, ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}, ...options.replyTo ? { replyTo: options.replyTo } : {}, waitMs: options.expectReply ? waitMs : 0, ...options.notifyCompletion === true ? { notifyCompletion: true } : {}, ...options.subscriberSession !== void 0 ? { subscriberSession: options.subscriberSession } : {}, ...options.userAssigned === true ? { userAssigned: true } : {} };
1024
717
  let done = false;
1025
718
  const finish = (value) => {
1026
719
  if (done) return;
@@ -1666,7 +1359,7 @@ var Runtime = class {
1666
1359
  if (!this.serverReady) return false;
1667
1360
  return writeStatusFile(this.discoveryDir, { ...this.currentStatus(), updatedAt: Date.now() }, (message) => this.ctx.log(message));
1668
1361
  }
1669
- handleEnvelope(envelope, respond, signal) {
1362
+ async handleEnvelope(envelope, respond, signal) {
1670
1363
  const reply = (kind, text) => {
1671
1364
  respond({
1672
1365
  v: IPC_PROTOCOL_VERSION,
@@ -1683,6 +1376,29 @@ var Runtime = class {
1683
1376
  case "ping":
1684
1377
  reply("ack", "pong");
1685
1378
  return;
1379
+ case "control": {
1380
+ if (!this.allowPolicy.allows(envelope.from)) {
1381
+ reply("ack", JSON.stringify({ ok: false, message: "denied by local allow policy" }));
1382
+ return;
1383
+ }
1384
+ try {
1385
+ const parsed = JSON.parse(envelope.text ?? "{}");
1386
+ if (typeof parsed.control !== "string" || !/^[a-z][a-z0-9.]{0,63}$/.test(parsed.control)) {
1387
+ reply("ack", JSON.stringify({ ok: false, message: "invalid control frame" }));
1388
+ return;
1389
+ }
1390
+ const applier = this.ctx.applyIpcControl;
1391
+ if (!applier) {
1392
+ reply("ack", JSON.stringify({ ok: false, message: "host does not support control frames" }));
1393
+ return;
1394
+ }
1395
+ const receipt = await applier(parsed.control, parsed.payload);
1396
+ reply("ack", JSON.stringify(receipt ?? { ok: false, message: "no receipt" }));
1397
+ } catch (error) {
1398
+ reply("ack", JSON.stringify({ ok: false, message: error instanceof Error ? error.message : String(error) }));
1399
+ }
1400
+ return;
1401
+ }
1686
1402
  case "state.get": {
1687
1403
  if (envelope.from !== this.instanceId && !this.allowPolicy.allows(envelope.from)) {
1688
1404
  reply("state", JSON.stringify({ state: this.projection.state, restricted: true }));
@@ -1773,7 +1489,7 @@ var Runtime = class {
1773
1489
  this.sendCompletionNotification(retired, "unknown", void 0);
1774
1490
  }
1775
1491
  }
1776
- this.completionWatchers.set(deliveryId, { peer: envelope.from, requestId: envelope.id, subscriberSession: envelope.subscriberSession ?? "" });
1492
+ this.completionWatchers.set(deliveryId, { peer: envelope.from, requestId: envelope.id, subscriberSession: envelope.subscriberSession ?? "", ...envelope.userAssigned === true ? { userAssigned: true } : {} });
1777
1493
  }
1778
1494
  const decision = this.delivery?.routeMessage({ ...envelope, id: deliveryId }, this.displayNameOf(envelope.from));
1779
1495
  if (decision === "denied") {
@@ -1923,7 +1639,7 @@ var Runtime = class {
1923
1639
  * sender's 10-minute fallback. On admission failure the watcher is now
1924
1640
  * RE-QUEUED for the next settle event instead of retired. */
1925
1641
  sendCompletionNotification(watcher, outcome, body, deliveryId) {
1926
- const notification = `[ipc-done] requestId=${watcher.requestId} outcome=${outcome}${outcome === "unknown" ? " (result evicted; query ipc_result)" : body !== void 0 ? `
1642
+ const notification = `[ipc-done] requestId=${watcher.requestId} outcome=${outcome}${watcher.userAssigned ? " user_assigned=true" : ""}${outcome === "unknown" ? " (result evicted; query ipc_result)" : body !== void 0 ? `
1927
1643
  ${body}` : ""}`;
1928
1644
  const statusFile = readStatusFile(this.discoveryDir, watcher.peer);
1929
1645
  if (!statusFile?.port) return;
@@ -2046,9 +1762,7 @@ ${body}` : ""}`;
2046
1762
  const fileRecord = file;
2047
1763
  const humanName = typeof fileRecord.displaySessionName === "string" && fileRecord.displaySessionName.trim() ? fileRecord.displaySessionName.trim() : void 0;
2048
1764
  const label = humanName ?? peerLabel(file.instanceId, file.displayName);
2049
- const project = typeof file.cwd === "string" && file.cwd.trim() ? file.cwd.trim().split("/").filter(Boolean).pop() : void 0;
2050
- const bits = [`${label} [${health}] ${file.state}${project ? ` \xB7 ${project}` : ""}`];
2051
- if (this.allowPolicy.allows(file.instanceId) && typeof file.sessionName === "string" && file.sessionName.trim()) bits.push(`address=${file.sessionName.trim()}`);
1765
+ const bits = [`${label} [${health}] ${file.state}`];
2052
1766
  if (this.allowPolicy.allows(file.instanceId) && file.currentTool) bits.push(`tool=${file.currentTool}`);
2053
1767
  if (this.allowPolicy.allows(file.instanceId) && file.blockedSince !== void 0) bits.push(`blocked ${Math.max(0, Math.round((Date.now() - file.blockedSince) / 1e3))}s`);
2054
1768
  if (this.allowPolicy.allows(file.instanceId) && file.sessionId) bits.push(`session=${file.sessionId.slice(0, 8)}`);
@@ -2098,6 +1812,27 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
2098
1812
  const matches = listings.filter(({ file }) => file.instanceId.toLowerCase().startsWith(ref) || file.displayName.toLowerCase().startsWith(ref));
2099
1813
  return matches.length === 1 ? matches[0].file : null;
2100
1814
  }
1815
+ /** MULTI-AGENT IM v2 Phase 2.3 — send an enumerated CONTROL frame to a
1816
+ * peer (first control: model.set). Returns the peer's receipt (the ack
1817
+ * envelope text, a small JSON object). The frame bypasses the target's
1818
+ * input queue entirely: no turn, no history — the peer's host applies
1819
+ * it directly. Awaits the ack (bounded); null means unreachable/timeout. */
1820
+ async sendControl(peerRef, control, payload, waitMs) {
1821
+ const target = this.resolvePeer(peerRef);
1822
+ if (!target) return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.` }], isError: true };
1823
+ if (!target.port) return { content: [{ type: "text", text: `${peerLabel(target.instanceId, target.displayName)} is not listening.` }], isError: true };
1824
+ if (!this.transport) return { content: [{ type: "text", text: "IPC transport is unavailable." }], isError: true };
1825
+ const body = JSON.stringify({ control, ...payload !== void 0 ? { payload } : {} });
1826
+ const reply = await this.transport.send(target.instanceId, target.port, "control", {
1827
+ text: body,
1828
+ sessionId: target.sessionId ?? "",
1829
+ expectReply: true,
1830
+ waitMs,
1831
+ replyKinds: /* @__PURE__ */ new Set(["ack"])
1832
+ });
1833
+ 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 };
1834
+ return { content: [{ type: "text", text: reply.text ?? "(empty receipt)" }] };
1835
+ }
2101
1836
  async sendToPeer(peerRef, text, wait, waitMs, context, notify = false, fallbackMs = DEFAULT_NOTIFY_FALLBACK_MS) {
2102
1837
  const target = this.resolvePeer(peerRef);
2103
1838
  if (!target) {
@@ -2113,6 +1848,23 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
2113
1848
  const requestId = randomUUID2();
2114
1849
  const notifyMode = notify && !wait;
2115
1850
  const sendGeneration = this.notifyGeneration;
1851
+ let userAssigned = false;
1852
+ if (notifyMode) {
1853
+ try {
1854
+ const messages = this.ctx.getMessages?.() ?? [];
1855
+ for (let i = messages.length - 1; i >= 0; i--) {
1856
+ const message = messages[i];
1857
+ if (!message || message.role !== "user") continue;
1858
+ const content = message.content;
1859
+ const text2 = typeof content === "string" ? content : Array.isArray(content) ? content.map((block) => block && typeof block === "object" && "text" in block && typeof block.text === "string" ? block.text : "").join("") : "";
1860
+ const trimmed = text2.trim();
1861
+ if (!trimmed) continue;
1862
+ userAssigned = /^\[(Feishu|Other)\]/.test(trimmed) && !trimmed.startsWith("[ipc-done]") && !trimmed.startsWith("[pie-ipc]");
1863
+ break;
1864
+ }
1865
+ } catch {
1866
+ }
1867
+ }
2116
1868
  const reply = await this.transport.send(target.instanceId, target.port, "message", {
2117
1869
  requestId,
2118
1870
  text: body,
@@ -2123,7 +1875,7 @@ last body (snapshot; may be stale): ${clipBody(target.lastBodyText, 400)}` : ""}
2123
1875
  // Waiting sends resolve only on the peer's turn-settling result (or
2124
1876
  // its terminal denied answer); the receipt ack stays informational.
2125
1877
  replyKinds: wait ? /* @__PURE__ */ new Set(["result"]) : /* @__PURE__ */ new Set(["result", "ack"]),
2126
- ...notifyMode ? { notifyCompletion: true, awaitAck: true, subscriberSession: this.sessionId ?? "" } : {}
1878
+ ...notifyMode ? { notifyCompletion: true, awaitAck: true, subscriberSession: this.sessionId ?? "", ...userAssigned ? { userAssigned: true } : {} } : {}
2127
1879
  });
2128
1880
  if (notifyMode) {
2129
1881
  if (sendGeneration !== this.notifyGeneration) {
@@ -2352,6 +2104,32 @@ function pieIpcExtension(ctx) {
2352
2104
  },
2353
2105
  execute: async (args, context) => runtime.sendToPeer(args.to, args.text, args.wait ?? false, Math.min(args.waitMs ?? DEFAULT_SEND_WAIT_MS, 6e5), context, args.notify !== false, Math.min(args.fallbackMs ?? DEFAULT_NOTIFY_FALLBACK_MS, 6e5))
2354
2106
  });
2107
+ ctx.registerTool({
2108
+ name: "ipc_control_notify",
2109
+ label: "Send a control frame to a Pie peer",
2110
+ 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. First control: 'model.set' with payload {model: 'provider/modelId'} switches the peer's model for its subsequent turns (same validation as the peer's own /model). Receipt (success or structured refusal) returns as this tool's result. Controls are idempotent: re-sending after an uncertain outcome is safe.",
2111
+ parameters: Type.Object({
2112
+ to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
2113
+ control: Type.Union([Type.Literal("model.set")], { description: "Control to apply (enumerated whitelist)" }),
2114
+ payload: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Control payload. model.set requires {model: 'provider/modelId'}" })),
2115
+ waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
2116
+ }),
2117
+ risk: { ...risk, riskClass: "session_mutation", concurrencySafe: false },
2118
+ renderHint: {
2119
+ summary: (args) => {
2120
+ const record = args ?? {};
2121
+ return `control ${record.control ?? "?"} \u2192 ${record.to ?? "?"}`;
2122
+ }
2123
+ },
2124
+ execute: async (args) => {
2125
+ if (args.control === "model.set") {
2126
+ const payload = args.payload ?? {};
2127
+ if (typeof payload.model !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(payload.model))
2128
+ return { content: [{ type: "text", text: "model.set requires payload.model as 'provider/modelId'." }], isError: true };
2129
+ }
2130
+ return runtime.sendControl(args.to, args.control, args.payload, Math.min(args.waitMs ?? 12e4, 6e5));
2131
+ }
2132
+ });
2355
2133
  ctx.registerTool({
2356
2134
  name: "ipc_result",
2357
2135
  label: "Query a Pie request result",
@@ -437,20 +437,6 @@ function pieProc(ctx) {
437
437
  }
438
438
  }
439
439
  }
440
- if (params.kind === "resident") {
441
- const imFile = path.join(pieDir, "im-forward.json");
442
- try {
443
- if (fs.existsSync(imFile)) {
444
- const existing = JSON.parse(fs.readFileSync(imFile, "utf8"));
445
- if (existing.outboundMode === void 0) {
446
- existing.outboundMode = "mirror";
447
- fs.writeFileSync(imFile, JSON.stringify(existing, null, " "));
448
- ctx.log(`pie-proc: migrated worker IM config to outboundMode=mirror (${params.name})`);
449
- }
450
- }
451
- } catch {
452
- }
453
- }
454
440
  if (imForward) {
455
441
  const imFile = path.join(pieDir, "im-forward.json");
456
442
  if (!fs.existsSync(imFile)) {
@@ -462,13 +448,6 @@ function pieProc(ctx) {
462
448
  const doc = {
463
449
  enabled: imForward.enabled === true,
464
450
  provider,
465
- // MULTI-AGENT IM §3 (review r1 P1-5): a spawned WORKER sharing the
466
- // app binding must never be a second gateway. The unattended
467
- // default would make every resident worker one (it forwards every
468
- // settled turn — exactly the dispatch-result flood this design
469
- // exists to kill). mirror = it speaks only where the user spoke to
470
- // IT first; the dispatching concierge remains the single voice.
471
- outboundMode: "mirror",
472
451
  providers: { [provider]: providerSettings }
473
452
  };
474
453
  if (typeof imForward.retryBackoffMs === "number") doc.retryBackoffMs = imForward.retryBackoffMs;
@@ -483,12 +462,7 @@ function pieProc(ctx) {
483
462
  ...process.env,
484
463
  PIE_CODING_AGENT_DIR: pieDir,
485
464
  PIE_IPC_CONFIG_DIR: inheritedIpcRoot,
486
- PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME,
487
- // MULTI-AGENT IM §2 (review r1 P2-2): the dispatcher names the
488
- // worker at spawn — the athlete never manages its own name tag.
489
- // The child applies it as a CURATED session name (see
490
- // json-events-mode startup), which never outranks a human rename.
491
- PIE_PROC_CURATED_NAME: params.name
465
+ PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME
492
466
  };
493
467
  if (params.kind === "oneshot") childEnv[ONESHOT_TASK_ENV] = params.task ?? "";
494
468
  try {