@cydm/pie 4.5.1 → 4.6.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.
@@ -1125,6 +1125,22 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
1125
1125
  if (indexed === route) threadRoutes.delete(threadKey);
1126
1126
  }
1127
1127
  }
1128
+ function refreshAnchorThreadRoutes(now) {
1129
+ for (const [sessionId, anchor] of replyAnchor) {
1130
+ if (!anchor.threadId || !anchor.messageId) continue;
1131
+ const threadKey = key(anchor.threadId);
1132
+ const indexed = threadRoutes.get(threadKey);
1133
+ if (indexed && indexed.sessionId === sessionId) continue;
1134
+ const route = {
1135
+ messageId: anchor.messageId,
1136
+ threadId: anchor.threadId,
1137
+ sessionId,
1138
+ sentAt: now
1139
+ };
1140
+ threadRoutes.set(threadKey, route);
1141
+ routes.set(key(anchor.messageId), route);
1142
+ }
1143
+ }
1128
1144
  function pruneState(now = Date.now()) {
1129
1145
  for (const [id, route] of routes) {
1130
1146
  if (now - route.sentAt > ROUTE_TTL_MS) {
@@ -1146,6 +1162,7 @@ function createRuntime(ctx, cfg, connection, liveEnabled, persistEnabled) {
1146
1162
  if (oldest.threadId) threadRoutes.delete(key(oldest.threadId));
1147
1163
  removeThreadAliasesOf(oldest);
1148
1164
  }
1165
+ refreshAnchorThreadRoutes(now);
1149
1166
  const cutoff = now - PENDING_IM_INPUT_TTL_MS;
1150
1167
  while (pendingInputs.length && pendingInputs[0].at <= cutoff)
1151
1168
  pendingInputs.shift();
@@ -1951,8 +1968,9 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1951
1968
  const messageId = event.message_id;
1952
1969
  if (!messageId) return;
1953
1970
  const owner = panelCardOwners.get(messageId);
1971
+ const nonBoundPanel = cfg.targetKind === "chat" && !!cfg.targetId && event.chat_id !== cfg.targetId;
1954
1972
  const fastEpoch = inputEpoch;
1955
- if (owner && owner.sessionId === currentSessionId && owner.epoch === fastEpoch && owner.chatId === event.chat_id && event.text?.startsWith("/card ")) {
1973
+ if (owner && !nonBoundPanel && owner.sessionId === currentSessionId && owner.epoch === fastEpoch && owner.chatId === event.chat_id && event.text?.startsWith("/card ")) {
1956
1974
  const command = parsePanelCommand(event.text);
1957
1975
  if (command) {
1958
1976
  ctx.log(`im-forward: panel fast path (${command.cmd})`);
@@ -1962,7 +1980,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
1962
1980
  }
1963
1981
  const address = resolveInboundAddress(event.text);
1964
1982
  if (address.kind === "other") {
1965
- if (isGroup && (nonBoundGroup || event.isBotMentioned === false)) {
1983
+ if (isGroup && (nonBoundGroup || event.isBotMentioned !== true)) {
1966
1984
  const meta = await fetchMessageMeta(messageId).catch(() => void 0);
1967
1985
  if (nonBoundGroup || !meta?.threadId) {
1968
1986
  ctx.log("im-forward: group address outside the bound chat or without bot mention/thread; ignoring");
@@ -2010,8 +2028,8 @@ ${result.spec.body}`, `panel-${event.event_id}`);
2010
2028
  releaseInvalidatedEvent();
2011
2029
  return;
2012
2030
  }
2013
- if (isGroup && event.isBotMentioned === false && !meta.threadId) {
2014
- ctx.log("im-forward: group message without bot mention outside any thread; ignoring");
2031
+ if (isGroup && event.isBotMentioned !== true && !meta.threadId) {
2032
+ ctx.log(`im-forward: group message without a confirmed bot mention (flag=${String(event.isBotMentioned)}) outside any thread; ignoring`);
2015
2033
  releaseInvalidatedEvent();
2016
2034
  return;
2017
2035
  }
@@ -2021,6 +2039,11 @@ ${result.spec.body}`, `panel-${event.event_id}`);
2021
2039
  releaseInvalidatedEvent();
2022
2040
  return;
2023
2041
  }
2042
+ if (address.kind === "self" && isGroup && event.isBotMentioned !== true) {
2043
+ ctx.log(`im-forward: group self-address without a confirmed mention (flag=${String(event.isBotMentioned)}); ignoring`);
2044
+ releaseInvalidatedEvent();
2045
+ return;
2046
+ }
2024
2047
  const resolution = address.kind === "self" ? {
2025
2048
  found: {
2026
2049
  messageId: "",
@@ -2069,7 +2092,7 @@ ${result.spec.body}`, `panel-${event.event_id}`);
2069
2092
  ctx.log(`im-forward: thread ownership unreadable for ${messageId}; dropping (fail closed)`);
2070
2093
  return;
2071
2094
  }
2072
- if (isManager && meta.threadId && !nonBoundGroup && (event.chatType === "group" || event.chatType === "p2p")) {
2095
+ if (isManager && meta.threadId && !nonBoundGroup && (!isGroup || event.isBotMentioned === true) && (event.chatType === "group" || event.chatType === "p2p")) {
2073
2096
  if (!scope.isCurrent()) {
2074
2097
  releaseInvalidatedEvent();
2075
2098
  return;
@@ -2125,9 +2148,12 @@ ${result.spec.body}`, `panel-${event.event_id}`);
2125
2148
  return;
2126
2149
  }
2127
2150
  }
2151
+ const stripImagePlaceholders = (text) => text.replace(/!\[Image\]\(img_[A-Za-z0-9_-]+\)/g, "").replace(/\[Image:\s*img_[A-Za-z0-9_-]+\]/g, "").trim();
2152
+ const imagelessCaption = imageKeys.length ? stripImagePlaceholders(caption) : caption;
2128
2153
  const submitText = `${IM_INPUT_PREFIX}
2129
- ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2130
- const accepted = imageKeys.length ? await injectImageMessage(messageId, imageKeys, submitText, scope) : await scope.submit(submitText);
2154
+ ${imagelessCaption || (imageKeys.length ? IM_INPUT_FALLBACK_CAPTION : "") || caption || ""}`;
2155
+ const imageResult = imageKeys.length ? await injectImageMessage(messageId, imageKeys, submitText, scope) : { ok: await scope.submit(submitText), submittedText: submitText };
2156
+ const accepted = imageResult.ok;
2131
2157
  const currentAfterSubmit = scope.isCurrent();
2132
2158
  if (!accepted || !currentAfterSubmit) {
2133
2159
  if (!accepted && !currentAfterSubmit) releaseInvalidatedEvent();
@@ -2172,7 +2198,13 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2172
2198
  }
2173
2199
  pendingInputs.push({
2174
2200
  sessionId: route.sessionId,
2175
- caption,
2201
+ // Attribution source-of-truth (review r2 P1): record the text ACTUALLY
2202
+ // submitted — the image pipeline may have stripped placeholders or
2203
+ // appended a degraded-delivery note, and resolveOutboundAttribution
2204
+ // compares EXACTLY against this string. Recording the raw caption made
2205
+ // the comparison fail and the outbound gate silently dropped the
2206
+ // manager's answer to a degraded image message.
2207
+ caption: imageKeys.length ? imageResult.submittedText ? stripImagePlaceholders(imageResult.submittedText).replace(/^\[Feishu\]\n/, "") || caption : caption : caption,
2176
2208
  messageId,
2177
2209
  threadId: route.threadId,
2178
2210
  at: Date.now()
@@ -2242,22 +2274,30 @@ ${caption || IM_INPUT_FALLBACK_CAPTION}`;
2242
2274
  async function injectImageMessage(messageId, imageKeys, submitText, scope) {
2243
2275
  if (imageKeys.length > 10) {
2244
2276
  ctx.log("im-forward: refusing more than 10 images in one message");
2245
- return false;
2277
+ return { ok: false };
2246
2278
  }
2247
2279
  const downloads = [];
2248
2280
  try {
2249
2281
  for (const [index, image] of imageKeys.entries()) {
2250
- if (!scope.isCurrent()) return false;
2282
+ if (!scope.isCurrent()) return { ok: false };
2251
2283
  downloads.push(await connection.downloadImage(messageId, image, index));
2252
2284
  }
2253
- if (!scope.isCurrent()) return false;
2254
- return await scope.submit(
2285
+ if (!scope.isCurrent()) return { ok: false };
2286
+ const submitted = await scope.submit(
2255
2287
  submitText,
2256
2288
  downloads.map((item) => item.file)
2257
2289
  );
2258
- } catch {
2259
- ctx.log("im-forward: image preparation failed");
2260
- return false;
2290
+ return submitted ? { ok: true, submittedText: submitText } : { ok: false };
2291
+ } catch (error) {
2292
+ ctx.log(`im-forward: image preparation failed (${error instanceof Error ? error.message : String(error)}); submitting text without ${imageKeys.length} image(s)`);
2293
+ const degraded = `${submitText}
2294
+ [image delivery failed: ${imageKeys.length} attachment(s) could not be downloaded]`;
2295
+ try {
2296
+ const submitted = await scope.submit(degraded);
2297
+ return submitted ? { ok: true, submittedText: degraded } : { ok: false };
2298
+ } catch {
2299
+ return { ok: false };
2300
+ }
2261
2301
  } finally {
2262
2302
  for (const item of downloads) {
2263
2303
  try {
@@ -3149,7 +3189,10 @@ function extractInboundText(content) {
3149
3189
  }
3150
3190
  function extractImageKeys(content) {
3151
3191
  if (typeof content !== "string") return [];
3152
- return [...new Set(Array.from(content.matchAll(/\[Image:\s*(img_[A-Za-z0-9_-]+)\]/g), (match) => match[1]))];
3192
+ const keys = /* @__PURE__ */ new Set();
3193
+ for (const match of content.matchAll(/\[Image:\s*(img_[A-Za-z0-9_-]+)\]/g)) keys.add(match[1]);
3194
+ for (const match of content.matchAll(/!\[Image\]\((img_[A-Za-z0-9_-]+)\)/g)) keys.add(match[1]);
3195
+ return [...keys];
3153
3196
  }
3154
3197
  function extractImageKey(content) {
3155
3198
  return extractImageKeys(content)[0] ?? null;
@@ -3749,7 +3792,7 @@ function normalizeEvent(line, botOpenId) {
3749
3792
  const esc = selfMention.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3750
3793
  text = text.replace(new RegExp(`^(?:[^\\n]*\\n)?@${esc}\\s*`), "").trim();
3751
3794
  }
3752
- const isBotMentioned = chatType === "group" ? botOpenId ? mentions?.some((m) => m.id === botOpenId) === true : Boolean(mentions?.length) : void 0;
3795
+ const isBotMentioned = chatType === "group" ? botOpenId ? mentions?.some((m) => m.id === botOpenId) === true : void 0 : void 0;
3753
3796
  return {
3754
3797
  event_id: raw.event_id,
3755
3798
  message_id: id,
@@ -4038,21 +4081,26 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
4038
4081
  return void 0;
4039
4082
  }
4040
4083
  };
4041
- const botIdentity = { openId: void 0, attempts: 0, pending: false };
4084
+ const botIdentity = { openId: void 0, attempts: 0, pending: false, nextAttemptAt: 0 };
4042
4085
  const resolveBotIdentity = () => {
4043
- if (botIdentity.openId || botIdentity.pending || botIdentity.attempts >= 3) return;
4086
+ if (botIdentity.openId || botIdentity.pending) return;
4087
+ const now = Date.now();
4088
+ if (now < botIdentity.nextAttemptAt) return;
4089
+ botIdentity.nextAttemptAt = now + Math.min(5e3 * 2 ** botIdentity.attempts, 6e5);
4044
4090
  botIdentity.pending = true;
4045
4091
  botIdentity.attempts += 1;
4046
4092
  void call(["api", "GET", "/open-apis/bot/v3/info", "--as", "bot"]).then((info) => {
4047
- if (typeof info?.open_id === "string") botIdentity.openId = info.open_id;
4048
- else console.warn(`[im-forward] bot identity lookup returned no open_id (attempt ${botIdentity.attempts}); gating stays on any-mention semantics`);
4049
- }).catch(() => console.warn(`[im-forward] bot identity lookup failed (attempt ${botIdentity.attempts}); gating stays on any-mention semantics`)).finally(() => {
4093
+ if (typeof info?.open_id === "string") {
4094
+ botIdentity.openId = info.open_id;
4095
+ botIdentity.attempts = 0;
4096
+ } else console.warn(`[im-forward] bot identity lookup returned no open_id (attempt ${botIdentity.attempts}); group gating stays UNCLASSIFIED \u2014 new group conversations are refused until the identity resolves`);
4097
+ }).catch(() => console.warn(`[im-forward] bot identity lookup failed (attempt ${botIdentity.attempts}); group gating stays UNCLASSIFIED \u2014 new group conversations are refused until the identity resolves`)).finally(() => {
4050
4098
  botIdentity.pending = false;
4051
4099
  });
4052
4100
  };
4053
4101
  const child = spawnConsume("im.message.receive_v1", (line) => {
4054
4102
  const event = normalizeEvent(line, botIdentity.openId);
4055
- if (event?.chatType === "group" || event?.chatType === "p2p") resolveBotIdentity();
4103
+ if ((event?.chatType === "group" || event?.chatType === "p2p") && !botIdentity.openId) resolveBotIdentity();
4056
4104
  return event;
4057
4105
  }, true);
4058
4106
  {
@@ -4060,7 +4108,10 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
4060
4108
  const text = line.trim();
4061
4109
  if (!text) return;
4062
4110
  if (text.startsWith("[event] ready")) {
4063
- if (!failed && !stopped) callbacks.ready();
4111
+ if (!failed && !stopped) {
4112
+ resolveBotIdentity();
4113
+ callbacks.ready();
4114
+ }
4064
4115
  return;
4065
4116
  }
4066
4117
  if (safeErrorPatterns.some((pattern) => pattern.test(text)) && text.length <= 200) lastErrorLine = text;
@@ -1014,6 +1014,16 @@ var Runtime = class {
1014
1014
  return;
1015
1015
  }
1016
1016
  const receipt = await applier(parsed.control, parsed.payload);
1017
+ try {
1018
+ this.ctx.appendEntry?.("pie.ipc.control", {
1019
+ from: envelope.from,
1020
+ self: envelope.from === this.instanceId,
1021
+ control: parsed.control,
1022
+ ok: receipt?.ok === true
1023
+ });
1024
+ } catch (auditError) {
1025
+ this.ctx.log(`pie-ipc: control audit entry FAILED (degraded): from=${envelope.from} control=${parsed.control} ok=${receipt?.ok === true} error=${auditError instanceof Error ? auditError.message : String(auditError)}`);
1026
+ }
1017
1027
  reply("ack", JSON.stringify(receipt ?? { ok: false, message: "no receipt" }));
1018
1028
  } catch (error) {
1019
1029
  reply("ack", JSON.stringify({ ok: false, message: error instanceof Error ? error.message : String(error) }));
@@ -1026,12 +1036,18 @@ var Runtime = class {
1026
1036
  return;
1027
1037
  }
1028
1038
  const status = this.currentStatus();
1039
+ let queueGate;
1040
+ try {
1041
+ queueGate = this.ctx.getQueueGateDiagnostics?.();
1042
+ } catch {
1043
+ }
1029
1044
  reply("state", JSON.stringify({
1030
1045
  state: status.state,
1031
1046
  currentTool: status.currentTool,
1032
1047
  blockedSince: status.blockedSince,
1033
1048
  turnStartedAt: status.turnStartedAt,
1034
- undeliveredInjections: status.undeliveredInjections
1049
+ undeliveredInjections: status.undeliveredInjections,
1050
+ ...queueGate ? { queueGate } : {}
1035
1051
  }));
1036
1052
  return;
1037
1053
  }
@@ -1507,6 +1523,12 @@ ${outcome.text}`
1507
1523
  * matches at any tier resolve to null (same as before); dead-pid entries
1508
1524
  * are skipped at every tier except the exact instanceId tier (which
1509
1525
  * keeps the file-view behavior of statusOf on a dying peer). */
1526
+ /** Host lifecycle state as tracked by the status projection (the same
1527
+ * state peers see in ipc_list_peers). Used by the self-control tool to
1528
+ * annotate mid-turn receipts. */
1529
+ projectionState() {
1530
+ return this.projection.state;
1531
+ }
1510
1532
  resolvePeer(peerRef) {
1511
1533
  const listings = listPeers(this.discoveryDir, { selfId: this.instanceId, pruneDead: false });
1512
1534
  const ref = peerRef.trim().toLowerCase();
@@ -1546,14 +1568,19 @@ ${outcome.text}`
1546
1568
  * input queue entirely: no turn, no history — the peer's host applies
1547
1569
  * it directly. Awaits the ack (bounded); null means unreachable/timeout. */
1548
1570
  async sendControl(peerRef, control, payload, waitMs) {
1549
- const target = this.resolvePeer(peerRef);
1571
+ const isSelfRef = peerRef.trim().toLowerCase() === "self";
1572
+ const target = isSelfRef ? { instanceId: this.instanceId, displayName: this.displayName, port: this.transport?.listenPort ?? void 0, sessionId: this.sessionId ?? void 0 } : this.resolvePeer(peerRef);
1550
1573
  if (!target) return { content: [{ type: "text", text: `Peer not found: ${peerRef}. Call ipc_list_peers first.${this.livePeerHint()}` }], isError: true };
1574
+ if (isSelfRef && !target.port) return { content: [{ type: "text", text: "This host is not listening (client-only peer); self-control requires a server peer." }], isError: true };
1551
1575
  if (!target.port) return { content: [{ type: "text", text: `${peerLabel(target.instanceId, target.displayName)} is not listening.` }], isError: true };
1552
1576
  if (!this.transport) return { content: [{ type: "text", text: "IPC transport is unavailable." }], isError: true };
1553
1577
  const body = JSON.stringify({ control, ...payload !== void 0 ? { payload } : {} });
1554
1578
  const reply = await this.transport.send(target.instanceId, target.port, "control", {
1555
1579
  text: body,
1556
- sessionId: target.sessionId ?? "",
1580
+ // SELF-LOOP: the envelope session is OUR bound session (the frame's
1581
+ // target-session check on arrival compares against the same value).
1582
+ // Peer sends keep using the DISCOVERED session id as before.
1583
+ sessionId: isSelfRef ? this.sessionId ?? "" : target.sessionId ?? "",
1557
1584
  expectReply: true,
1558
1585
  waitMs,
1559
1586
  replyKinds: /* @__PURE__ */ new Set(["ack"])
@@ -1899,8 +1926,8 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1899
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. 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.",
1900
1927
  parameters: Type.Object({
1901
1928
  to: Type.String({ description: "Peer display name or instance id (see ipc_list_peers)" }),
1902
- control: Type.Union([Type.Literal("model.set")], { description: "Control to apply (enumerated whitelist)" }),
1903
- payload: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Control payload. model.set requires {model: 'provider/modelId'}" })),
1929
+ control: Type.Union([Type.Literal("model.set"), Type.Literal("thinking.set")], { description: "Control to apply (enumerated whitelist)" }),
1930
+ 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'}" })),
1904
1931
  waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
1905
1932
  }),
1906
1933
  risk: { ...risk, riskClass: "session_mutation", concurrencySafe: false },
@@ -1916,10 +1943,59 @@ SIDE EFFECT: this is NOT a read-only query. The text is injected into the peer's
1916
1943
  if (typeof payload.model !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(payload.model))
1917
1944
  return { content: [{ type: "text", text: "model.set requires payload.model as 'provider/modelId'." }], isError: true };
1918
1945
  }
1946
+ if (args.control === "thinking.set") {
1947
+ const payload = args.payload ?? {};
1948
+ const valid = ["off", "minimal", "low", "medium", "high", "xhigh"];
1949
+ if (typeof payload.level !== "string" || !valid.includes(payload.level))
1950
+ return { content: [{ type: "text", text: `thinking.set requires payload.level as one of ${valid.join("|")}.` }], isError: true };
1951
+ }
1919
1952
  return runtime.sendControl(args.to, args.control, args.payload, Math.min(args.waitMs ?? 12e4, 6e5));
1920
1953
  }
1921
1954
  });
1922
1955
  }, isManagerRole);
1956
+ ctx.registerTool({
1957
+ name: "self_control",
1958
+ 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. Receipt (success or structured refusal) returns as this tool's result. Controls are idempotent: re-sending after an uncertain outcome is safe.",
1960
+ parameters: Type.Object({
1961
+ control: Type.Union([Type.Literal("model.set"), Type.Literal("thinking.set")], { description: "Control to apply (enumerated host whitelist)" }),
1962
+ 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'}" })),
1963
+ waitMs: Type.Optional(Type.Number({ description: "Receipt wait budget in ms (default 120000, max 600000)", minimum: 100, maximum: 6e5 }))
1964
+ }),
1965
+ risk: { ...risk, riskClass: "session_mutation", concurrencySafe: false },
1966
+ renderHint: {
1967
+ summary: (args) => {
1968
+ const record = args ?? {};
1969
+ return `self-control ${record.control ?? "?"}`;
1970
+ }
1971
+ },
1972
+ execute: async (args) => {
1973
+ if (args.control === "model.set") {
1974
+ const payload = args.payload ?? {};
1975
+ if (typeof payload.model !== "string" || !/^[^/\s]+\/[^/\s]+$/.test(payload.model))
1976
+ return { content: [{ type: "text", text: "model.set requires payload.model as 'provider/modelId'." }], isError: true };
1977
+ }
1978
+ if (args.control === "thinking.set") {
1979
+ const payload = args.payload ?? {};
1980
+ const valid = ["off", "minimal", "low", "medium", "high", "xhigh"];
1981
+ if (typeof payload.level !== "string" || !valid.includes(payload.level))
1982
+ return { content: [{ type: "text", text: `thinking.set requires payload.level as one of ${valid.join("|")}.` }], isError: true };
1983
+ }
1984
+ const midTurn = runtime.projectionState() === "working";
1985
+ const receipt = await runtime.sendControl("self", args.control, args.payload, Math.min(args.waitMs ?? 12e4, 6e5));
1986
+ if (midTurn && !receipt.isError) {
1987
+ let applied = false;
1988
+ try {
1989
+ applied = JSON.parse(receipt.content[0]?.text ?? "{}").ok === true;
1990
+ } catch {
1991
+ }
1992
+ if (applied) {
1993
+ return { content: [{ type: "text", text: `${receipt.content[0]?.text ?? ""} (you are mid-execution: the switch applies from your host's NEXT agent execution \u2014 this execution's remaining model calls, including tool-continuation rounds, still use the settings it started with)` }] };
1994
+ }
1995
+ }
1996
+ return receipt;
1997
+ }
1998
+ });
1923
1999
  registerRoleTool({ name: "ipc_result" }, () => {
1924
2000
  ctx.registerTool({
1925
2001
  name: "ipc_result",
@@ -34,7 +34,8 @@ function resolveOperatorSessionsDir() {
34
34
  return path.join(os.homedir(), ".pie", "sessions");
35
35
  }
36
36
  }
37
- var DEFAULT_CONFIG = { allowCwd: [], maxWorkers: 5, killGraceMs: 15e3, defaultTtlMs: 0 };
37
+ var DEFAULT_MAX_WORKERS = 50;
38
+ var DEFAULT_CONFIG = { allowCwd: [], maxWorkers: DEFAULT_MAX_WORKERS, killGraceMs: 15e3, defaultTtlMs: 0 };
38
39
  var IM_FORWARD_ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "chatId", "openId", "allowUsers", "retryBackoffMs", "larkCliProfile"]);
39
40
  var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
40
41
  function configDirRoot() {
@@ -46,18 +47,24 @@ function expandTilde(p) {
46
47
  return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
47
48
  }
48
49
  function readConfig() {
49
- const file = path.join(configDirRoot(), "pie-proc.json");
50
- try {
51
- const raw = JSON.parse(fs.readFileSync(file, "utf8"));
52
- return {
53
- allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
54
- maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
55
- killGraceMs: typeof raw.killGraceMs === "number" && raw.killGraceMs >= 1e3 ? raw.killGraceMs : DEFAULT_CONFIG.killGraceMs,
56
- defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? raw.defaultTtlMs : DEFAULT_CONFIG.defaultTtlMs
57
- };
58
- } catch {
59
- return { ...DEFAULT_CONFIG };
50
+ const candidates = [path.join(configDirRoot(), "pie-proc.json")];
51
+ if (configDirRoot() !== path.join(os.homedir(), ".pie")) {
52
+ candidates.push(path.join(os.homedir(), ".pie", "pie-proc.json"));
53
+ }
54
+ for (const file of candidates) {
55
+ try {
56
+ const raw = JSON.parse(fs.readFileSync(file, "utf8"));
57
+ return {
58
+ allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
59
+ maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
60
+ killGraceMs: typeof raw.killGraceMs === "number" && raw.killGraceMs >= 1e3 ? Math.floor(raw.killGraceMs) : DEFAULT_CONFIG.killGraceMs,
61
+ defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? Math.floor(raw.defaultTtlMs) : DEFAULT_CONFIG.defaultTtlMs
62
+ };
63
+ } catch {
64
+ if (fs.existsSync(file)) return { ...DEFAULT_CONFIG };
65
+ }
60
66
  }
67
+ return { ...DEFAULT_CONFIG };
61
68
  }
62
69
  function pieProcDir() {
63
70
  return path.join(configDirRoot(), "pie-proc");
@@ -452,7 +459,21 @@ function pieProc(ctx) {
452
459
  const generation = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
453
460
  const launchToken = `pie-proc-${params.name}-${generation}`;
454
461
  const sessionId = resumeSessionId ?? launchToken;
455
- const imForward = sanitizeImForward(params.imForward);
462
+ let imForwardParam = params.imForward;
463
+ if (imForwardParam === void 0 && params.kind === "resident" && !resumeSessionId && process.env.PIE_PROC_CURATED_NAME === "manager") {
464
+ imForwardParam = "inherit";
465
+ }
466
+ const imForwardDefaulted = imForwardParam !== params.imForward;
467
+ let imForward;
468
+ try {
469
+ imForward = sanitizeImForward(imForwardParam);
470
+ } catch (error) {
471
+ if (imForwardDefaulted) {
472
+ ctx.log(`pie-proc: default imForward inherit unavailable (${error instanceof Error ? error.message : String(error)}); spawning WITHOUT IM forwarding`);
473
+ } else {
474
+ throw error;
475
+ }
476
+ }
456
477
  casRegistry((snap) => {
457
478
  const current = snap.workers;
458
479
  const sameName = current.find((w) => w.name === params.name);