@parall/daemon 1.42.0 → 1.43.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.
@@ -17718,9 +17718,9 @@ var require_getMachineId_linux = __commonJS({
17718
17718
  var api_1 = (init_esm(), __toCommonJS(esm_exports));
17719
17719
  async function getMachineId() {
17720
17720
  const paths = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
17721
- for (const path9 of paths) {
17721
+ for (const path11 of paths) {
17722
17722
  try {
17723
- const result = await fs_1.promises.readFile(path9, { encoding: "utf8" });
17723
+ const result = await fs_1.promises.readFile(path11, { encoding: "utf8" });
17724
17724
  return result.trim();
17725
17725
  } catch (e) {
17726
17726
  api_1.diag.debug(`error reading machine id: ${e}`);
@@ -21123,7 +21123,7 @@ function appendRootPathToUrlIfNeeded(url) {
21123
21123
  return void 0;
21124
21124
  }
21125
21125
  }
21126
- function appendResourcePathToUrl(url, path9) {
21126
+ function appendResourcePathToUrl(url, path11) {
21127
21127
  try {
21128
21128
  new URL(url);
21129
21129
  } catch (_a) {
@@ -21133,11 +21133,11 @@ function appendResourcePathToUrl(url, path9) {
21133
21133
  if (!url.endsWith("/")) {
21134
21134
  url = url + "/";
21135
21135
  }
21136
- url += path9;
21136
+ url += path11;
21137
21137
  try {
21138
21138
  new URL(url);
21139
21139
  } catch (_b) {
21140
- diag2.warn("Configuration: Provided URL appended with '" + path9 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
21140
+ diag2.warn("Configuration: Provided URL appended with '" + path11 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
21141
21141
  return void 0;
21142
21142
  }
21143
21143
  return url;
@@ -26487,716 +26487,8 @@ function laneContextFilePath(contextDir, targetUri, threadRootId) {
26487
26487
  return path.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
26488
26488
  }
26489
26489
 
26490
- // ts/agent-core/dist/session-state.js
26491
- function normalizeSessionKey(sessionKey) {
26492
- return sessionKey.toLowerCase();
26493
- }
26494
- var sessionChatIdMap = /* @__PURE__ */ new Map();
26495
- var sessionMessageIdMap = /* @__PURE__ */ new Map();
26496
- var dispatchMessageIdMap = /* @__PURE__ */ new Map();
26497
- var dispatchNoReplyMap = /* @__PURE__ */ new Map();
26498
- function setSessionChatId(sessionKey, chatId) {
26499
- sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
26500
- }
26501
- function setSessionMessageId(sessionKey, messageId) {
26502
- sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
26503
- }
26504
- function clearSessionMessageId(sessionKey) {
26505
- sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
26506
- }
26507
- function setDispatchMessageId(sessionKey, messageId) {
26508
- dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
26509
- }
26510
- function clearDispatchMessageId(sessionKey) {
26511
- dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
26512
- }
26513
- function setDispatchNoReply(sessionKey, noReply) {
26514
- dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
26515
- }
26516
- function clearDispatchNoReply(sessionKey) {
26517
- dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
26518
- }
26519
- var dispatchMetricsMap = /* @__PURE__ */ new Map();
26520
- function resetDispatchMetrics(sessionKey) {
26521
- dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
26522
- deliver_text_chunks: 0,
26523
- deliver_text_chars: 0,
26524
- message_send_attempts: 0,
26525
- message_send_successes: 0,
26526
- no_reply_called: false,
26527
- tool_call_count: 0,
26528
- started_at: Date.now()
26529
- });
26530
- }
26531
- function getDispatchMetrics(sessionKey) {
26532
- return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26533
- }
26534
- function clearDispatchMetrics(sessionKey) {
26535
- dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
26536
- }
26537
- function recordDeliverText(sessionKey, charCount) {
26538
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26539
- if (!m)
26540
- return;
26541
- m.deliver_text_chunks++;
26542
- m.deliver_text_chars += charCount;
26543
- }
26544
- function recordMessageSend(sessionKey, success) {
26545
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26546
- if (!m)
26547
- return;
26548
- m.message_send_attempts++;
26549
- if (success)
26550
- m.message_send_successes++;
26551
- }
26552
- function recordNoReply(sessionKey) {
26553
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26554
- if (!m)
26555
- return;
26556
- m.no_reply_called = true;
26557
- }
26558
- function recordToolCall(sessionKey) {
26559
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26560
- if (!m)
26561
- return;
26562
- m.tool_call_count++;
26563
- }
26564
-
26565
- // ts/agent-core/dist/routing.js
26566
- var MAX_CONCURRENT_FORKS = 20;
26567
- var defaultRoutingStrategy = (event, state) => {
26568
- if (state.mainCurrentTargetId === event.targetId) {
26569
- return { action: "buffer-main" };
26570
- }
26571
- const existingForkKey = state.activeForks.get(event.targetId);
26572
- if (existingForkKey)
26573
- return { action: "buffer-fork", forkKey: existingForkKey };
26574
- if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
26575
- return { action: "buffer-main" };
26576
- }
26577
- return { action: "new-fork" };
26578
- };
26579
- function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
26580
- const existingForkKey = state.activeForks.get(event.targetId);
26581
- if (existingForkKey)
26582
- return { action: "buffer-fork", forkKey: existingForkKey };
26583
- if (!state.mainDispatching)
26584
- return { action: "main" };
26585
- return strategy(event, state);
26586
- }
26587
-
26588
- // ts/agent-core/dist/event-format.js
26589
- function sanitizeMeta(value) {
26590
- return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
26591
- }
26592
- function buildEventBody(event) {
26593
- const lines = [];
26594
- if (event.type === "message") {
26595
- lines.push(`[Event: message.new]`);
26596
- const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
26597
- lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
26598
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26599
- lines.push(`[Message ID: prll://${event.messageId}]`);
26600
- if (event.threadRootId) {
26601
- const threadMeta = [
26602
- `prll://${event.threadRootId}`,
26603
- event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
26604
- event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
26605
- event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
26606
- ].filter(Boolean).join(" | ");
26607
- lines.push(`[Thread: ${threadMeta}]`);
26608
- }
26609
- if (event.unreadCount != null && event.unreadCount > 1) {
26610
- const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
26611
- const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
26612
- let line = `[Unread: ${countStr} messages${sinceStr}]`;
26613
- if (event.unreadCount > 50)
26614
- line += ` \u2014 fetch recent context with --limit, not all`;
26615
- lines.push(line);
26616
- }
26617
- if (event.noReply)
26618
- lines.push(`[Hint: no_reply]`);
26619
- if (event.attachments?.length) {
26620
- for (const att of event.attachments) {
26621
- const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
26622
- lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
26623
- }
26624
- }
26625
- lines.push("", event.body);
26626
- } else if (event.type === "task_comment") {
26627
- lines.push(`[Event: task.comment.created]`);
26628
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
26629
- lines.push(`[Task: ${taskLabel}]`);
26630
- if (event.deliveryReason)
26631
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
26632
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26633
- lines.push(`[Comment ID: prll://${event.messageId}]`);
26634
- lines.push("", event.body);
26635
- } else if (event.type === "wiki_comment") {
26636
- lines.push(`[Event: wiki.comment.created]`);
26637
- const target = event.replyTargetUri ?? `prll://${event.targetId}`;
26638
- if (event.targetType === "changeset") {
26639
- lines.push(`[Wiki Changeset: ${target}]`);
26640
- } else {
26641
- lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
26642
- }
26643
- if (event.deliveryReason)
26644
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
26645
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26646
- lines.push(`[Comment ID: prll://${event.messageId}]`);
26647
- lines.push("", event.body);
26648
- } else if (event.type === "approval") {
26649
- lines.push(`[Event: approval.decided]`);
26650
- lines.push(`[Approval: prll://${event.messageId}]`);
26651
- lines.push(`[Chat: prll://${event.targetId}]`);
26652
- lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
26653
- lines.push("", event.body);
26654
- } else if (event.type === "schedule") {
26655
- lines.push(`[Event: schedule.fired]`);
26656
- lines.push(`[Schedule: prll://${event.targetId}]`);
26657
- lines.push(`[Run: prll://${event.messageId}]`);
26658
- if (event.scheduledFireAt)
26659
- lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
26660
- if (event.attachedUri)
26661
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
26662
- lines.push("", event.body);
26663
- } else if (event.type === "channel_message") {
26664
- lines.push(`[Event: channel.message]`);
26665
- const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
26666
- const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
26667
- lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
26668
- lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
26669
- if (event.channelExternalMessageId) {
26670
- lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
26671
- }
26672
- lines.push(`[Audience: this conversation lives on ${providerLabel}, OUTSIDE Parall. Readers cannot open prll:// links, Parall cards, or internal attachments \u2014 never include them in replies. Write plain conversational text.]`);
26673
- lines.push("", event.body);
26674
- } else if (event.type === "external_trigger") {
26675
- lines.push(`[Event: external.trigger]`);
26676
- lines.push(`[Trigger: prll://${event.targetId}]`);
26677
- lines.push(`[Run: prll://${event.messageId}]`);
26678
- if (event.externalConnectionId) {
26679
- const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
26680
- lines.push(`[Connection: ${label}]`);
26681
- }
26682
- if (event.externalIngressEventId)
26683
- lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
26684
- if (event.attachedUri)
26685
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
26686
- if (event.externalConnectionSourceType) {
26687
- lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
26688
- }
26689
- if (event.externalIngressEventType) {
26690
- lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
26691
- }
26692
- lines.push("", event.body);
26693
- } else {
26694
- lines.push(`[Event: task.assigned]`);
26695
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
26696
- lines.push(`[Task: ${taskLabel}]`);
26697
- lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
26698
- lines.push("", event.body);
26699
- }
26700
- return lines.join("\n") + buildSendMessageHint(event);
26701
- }
26702
- function buildEventBodyForForkResult(event) {
26703
- return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
26704
- }
26705
- function buildSendMessageHint(event) {
26706
- if (event.noReply)
26707
- return "";
26708
- if (event.type === "wiki_comment" && event.replyTargetUri) {
26709
- const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
26710
- return `
26711
- <system-reminder>To reply on ${where}, run: \`parall comments add --target "${event.replyTargetUri}" --body "..."\` (read the thread first with \`parall comments list --target "${event.replyTargetUri}"\`). To message someone instead, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
26712
- }
26713
- if (event.targetId.startsWith("cht_")) {
26714
- if (event.threadRootId) {
26715
- return `
26716
- <system-reminder>To reply in this thread, run \`parall messages send prll://${event.targetId} --thread-root-id ${sanitizeMeta(event.threadRootId)} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
26717
- }
26718
- return `
26719
- <system-reminder>To reply, run \`parall messages send prll://${event.targetId} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
26720
- }
26721
- if (event.targetId.startsWith("tsk_")) {
26722
- return `
26723
- <system-reminder>To respond, use the CLI: \`parall tasks update\` / \`parall tasks comments add\`. To message someone, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
26724
- }
26725
- if (event.targetId.startsWith("sch_")) {
26726
- return `
26727
- <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
26728
- }
26729
- if (event.type === "channel_message") {
26730
- const clipLabel = event.channelProvider ? `the \`${event.channelProvider}\` clip's` : "your channel provider clip's";
26731
- const apiLabel = event.channelProvider ?? "external platform";
26732
- const target = event.channelExternalConversationId ? `{"chat_id": "${event.channelExternalConversationId}", "text": "..."}` : `{"chat_id": "<conversation id>", "text": "..."}`;
26733
- const threadAlt = event.channelExternalMessageId ? ` To reply in-thread to this specific message, use {"message_id": "${event.channelExternalMessageId}", "text": "..."} instead.` : "";
26734
- return `
26735
- <system-reminder>To reply, invoke ${clipLabel} \`send_message\` command with ${target} \u2014 your plain text output is NOT delivered to the external conversation.${threadAlt} The same clip's \`call\` command reaches the wider ${apiLabel} API when needed.</system-reminder>`;
26736
- }
26737
- if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
26738
- return `
26739
- <system-reminder>This external trigger is incoming-only. Your plain text output is not sent back to the external provider. To communicate in Parall, use \`parall messages send\` / \`parall dm\`; provider-specific outbound actions require a separate capability.</system-reminder>`;
26740
- }
26741
- return "";
26742
- }
26743
- function buildForkScopePrefix(event) {
26744
- const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
26745
- return `[Fork scope: You are a parallel worker forked from the main session to handle ${targetLabel}. The conversation history above belongs to the main session's in-progress dispatch \u2014 do NOT continue it or complete it, or produce external output (comments, messages) for work visible there. The main session owns its own output.
26746
-
26747
- Only act on the event below within your target scope. If your event reveals findings about the main session's work, report them in your summary \u2014 do not post them externally.
26748
-
26749
- End with a brief "Fork summary" of actions taken and decisions made.]
26750
-
26751
- `;
26752
- }
26753
- function buildForkResultPrefix(results) {
26754
- if (!results.length)
26755
- return "";
26756
- const blocks = results.map((result) => {
26757
- const lines = [];
26758
- for (const body of result.eventBodies) {
26759
- lines.push(body);
26760
- }
26761
- lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
26762
- lines.push(`[Fork summary: ${result.agentSummary ? sanitizeMeta(result.agentSummary) : "No fork summary available \u2014 the fork completed without producing a text summary. Check the target chat/task for any actions the fork already took before acting."}]`);
26763
- if (result.actions.length)
26764
- lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
26765
- if (result.historyPath)
26766
- lines.push(`[Fork history: ${result.historyPath}]`);
26767
- return lines.join("\n");
26768
- });
26769
- return blocks.join("\n\n") + "\n\n---\n\n";
26770
- }
26771
-
26772
- // ts/agent-core/dist/prompt-fragments.js
26773
- var PRLL_IDENTITY_BASE = `## You on Parall
26774
-
26775
- Parall is a shared workspace where humans and agents work side by side as equals.
26776
- You are a participant here, not a service. You hold tasks, own decisions, and are
26777
- accountable for the work you take on \u2014 the same way a human teammate is.
26778
-
26779
- The people and agents around you are collaborators, not users to serve. Be honest,
26780
- be direct, and care about the outcome of the work \u2014 not just the request in front
26781
- of you.`;
26782
- function sanitizeProfileField(value) {
26783
- return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
26784
- }
26785
- function sanitizeProfileBlock(value) {
26786
- return value.replace(/\r\n?/g, "\n").trim();
26787
- }
26788
- function buildIdentity(agent) {
26789
- if (!agent)
26790
- return PRLL_IDENTITY_BASE;
26791
- const name = sanitizeProfileField(agent.displayName);
26792
- const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
26793
- lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
26794
- if (agent.description) {
26795
- const description = sanitizeProfileBlock(agent.description);
26796
- if (description) {
26797
- lines.push("", "### Your Agent Profile", "", description);
26798
- }
26799
- }
26800
- lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
26801
- return lines.join("\n");
26802
- }
26803
- var PRLL_BEHAVIOR = `## How to work here
26804
-
26805
- ### Move work forward
26806
- Don't wait for instructions. If you see the next step, take it. If something is
26807
- ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
26808
- \u2014 don't go silent. Initiative is expected.
26809
-
26810
- Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
26811
- requests, verifying something landed. When a thing needs future attention and
26812
- nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
26813
-
26814
- ### Work in the open
26815
- Nothing you do exists until the system can see it. Your progress, decisions,
26816
- blockers, and results need to live in tasks, comments, messages, or wiki pages
26817
- \u2014 otherwise the organization is blind to your work, and so is the next agent
26818
- who picks up where you left off. Leave traces as you go, not at the end.
26819
-
26820
- For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
26821
- when status materially changes, close it when done, and link the origin that
26822
- triggered it. Decompose multi-step work into subtasks and keep their statuses
26823
- current \u2014 progress should be auditable without watching the work happen.
26824
- Details: load the \`parall-tasks\` skill.
26825
-
26826
- ### Done means landed
26827
- Producing output does not complete a task. Work counts as done only when it has
26828
- cleared its remaining gates \u2014 review, merge, deployment, the requester's
26829
- verification. Until then keep the status honest (\`in_progress\` or
26830
- \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
26831
- self-reminder if nothing else will prompt follow-up). Never mark done what a
26832
- human still has to accept.
26833
-
26834
- ### Sessions, forks, and what survives
26835
- Sessions end and context compacts. Anything that must survive \u2014 decisions,
26836
- progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
26837
- read the workspace, not this conversation.
26838
-
26839
- Some events are handled by parallel fork sessions \u2014 short-lived copies of the
26840
- same agent identity with separate context. In a fork: leave a written trace of
26841
- what was done or deliberately not done (other sessions cannot see fork
26842
- context), and do not start long-running processes \u2014 they die with the fork.
26843
- When an event is marked fork-handled: do not re-handle it; verify its outcome
26844
- instead of assuming it.
26845
-
26846
- ### Communicate like a teammate
26847
- Match the conversation \u2014 concise in chat, thorough in docs, plain language over
26848
- jargon. Say what matters; stop when you're done. Don't narrate every tool call
26849
- or pad replies to seem thorough.
26850
-
26851
- Match the language of the person you're replying to. If someone writes in
26852
- Chinese, reply in Chinese. If in English, reply in English. Never force a
26853
- language switch unless explicitly asked.
26854
-
26855
- Do not promise delivery times ("in an hour", "by tonight") unless the work is
26856
- driven by an explicit schedule. Scope visibly; report when actually done.
26857
-
26858
- ### Keep topics in threads
26859
- Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
26860
- Present \u2192 that thread is the context; reply there, passing the same root as
26861
- \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
26862
- never treat it as continuing your most recent thread. The sender's newest
26863
- message is the anchor \u2014 never route a reply back into an older thread just
26864
- because the topic used to live there.
26865
-
26866
- Reply where the event lives: a thread message gets a thread reply, a
26867
- top-level message gets a top-level reply. But in group chats, your later
26868
- follow-up on that topic \u2014 progress updates, analysis, links, verification you
26869
- post afterwards \u2014 belongs in a thread rooted at the topic's message
26870
- (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
26871
- the main channel stays scannable. Post follow-up at top level only when
26872
- starting a genuinely new topic, making a channel-wide announcement, or when
26873
- explicitly asked. Never post the same update in both the thread and the main
26874
- channel \u2014 thread replies surface in the thread panel; no need to duplicate
26875
- for visibility.
26876
-
26877
- In DMs, reply top-level by default; use a thread only to continue one that
26878
- already exists.
26879
-
26880
- ### Group chats: mentions and unaddressed work
26881
- An @mention is a direct request \u2014 act on it. A group message delivered to you
26882
- without an @mention means the chat's routing lets you see the conversation:
26883
- decide whether a reply adds value; silence is the default.
26884
-
26885
- A message without an @mention is not an open invitation. Judge from context
26886
- who the work belongs to \u2014 the named domain, the topic's owner, whoever is
26887
- already on it. If it belongs to someone else, leave it. If genuinely unclear,
26888
- ask or claim in one line ("taking this unless someone else has it") before
26889
- starting \u2014 asking first beats duplicated or misdirected work.
26890
-
26891
- ### Verify before you act
26892
- Events can be redelivered \u2014 before acting, check whether it was already
26893
- handled (your own recent replies, task comments); if handled, do nothing.
26894
- Sends can fail silently, and creates can error after succeeding server-side \u2014
26895
- check the chat or entity before retrying. Never blind-retry a mutating call.
26896
-
26897
- ### Gather the full picture first
26898
- When a request is vague, an entity may already exist, or work may already be
26899
- underway \u2014 gather context before acting: search (\`parall search "..."\`),
26900
- check existing tasks/chats/wiki, read the surrounding conversation. Act on the
26901
- full picture, not the fragment that arrived in the event.
26902
-
26903
- ### Report only work that ran
26904
- If a scheduled job, scan, or tool call did not actually run \u2014 restarted
26905
- session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
26906
- or approximate results of work that did not execute.
26907
-
26908
- ### Respect what's shared
26909
- You have broad latitude inside your own work. But actions that are visible to
26910
- others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
26911
- wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
26912
- acting, unless you've been explicitly authorized.
26913
-
26914
- ### Shared workspace
26915
- Other agents share this workspace. Before starting work, check whether someone
26916
- \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
26917
-
26918
- ### Permissions and approvals
26919
- You have real permissions based on your roles (chat member/admin, org member).
26920
- If you lack permission for an action, the API returns PERMISSION_DENIED with the
26921
- \`action\` and \`resource_uri\` that were denied. The server decides whether that
26922
- action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
26923
- fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
26924
- it to ask someone with permission. If it is NOT approvable, the output says so;
26925
- ask a human with permission instead of requesting approval. A
26926
- \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
26927
- (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
26928
- \`dm\` for a user). Don't retry or work around a denial; only request approval
26929
- after an actual denial, never preemptively.
26930
-
26931
- ### When in doubt
26932
- Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
26933
- credibility is what you bring to the workspace \u2014 protect it.`;
26934
- var PRLL_REFERENCE_GUIDE = `## Parall References
26935
-
26936
- Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
26937
- entities when you create or update tasks, comments, messages, and wiki files.
26938
-
26939
- All three forms work \u2014 pick whichever fits:
26940
-
26941
- prll://tsk_abc bare URI (auto-linked)
26942
- [](prll://tsk_abc) empty context (renders resolved title)
26943
- [relevant context](prll://tsk_abc) with author annotation
26944
-
26945
- Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
26946
- resolves and renders the entity title automatically.
26947
-
26948
- ### URI format
26949
-
26950
- \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
26951
-
26952
- **Entities** \u2014 the entity ID is the authority:
26953
-
26954
- prll://usr_xxx user prll://prj_xxx project
26955
- prll://tsk_xxx task prll://wik_xxx wiki
26956
- prll://msg_xxx message prll://tcm_xxx task comment
26957
- prll://cht_xxx chat prll://ase_xxx agent session
26958
- prll://att_xxx attachment prll://sch_xxx schedule
26959
- prll://srn_xxx schedule run
26960
-
26961
- **Wiki** \u2014 path is file path, fragment is a typed anchor:
26962
-
26963
- prll://wik_xxx/docs/guide.md file
26964
- prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
26965
- prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
26966
-
26967
- Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
26968
- Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
26969
-
26970
- **Chat message range**:
26971
-
26972
- prll://cht_xxx#range=msg_01HA,msg_01HZ
26973
-
26974
- **Field access** \u2014 path selects a field (omit to reference the entity itself):
26975
-
26976
- prll://tsk_xxx/description#Implementation heading within task description
26977
-
26978
- ### Unread context
26979
-
26980
- When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
26981
- This shows messages since your last interaction \u2014 your read cursor advances after each
26982
- dispatch, so context you skip now won't appear as unread next time. Use
26983
- \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
26984
- counts (50+), fetch only recent messages rather than everything.
26985
-
26986
- Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
26987
- Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
26988
- catch up on the thread.
26989
-
26990
- ### Reading context on demand
26991
-
26992
- An event only carries the single triggering message. If you're mentioned in a
26993
- group chat and lack context, pull what you need from the chat \u2014 don't guess:
26994
-
26995
- parall messages list cht_xxx --limit 20 --before msg_xxx
26996
- parall messages get msg_xxx
26997
- parall chats get cht_xxx
26998
-
26999
- Rule of thumb: in a group chat mention, the conversation that led up to you
27000
- being called almost always matters \u2014 read it before replying. In a DM, your
27001
- session already has continuity, so skip the fetch unless something is unclear.
27002
-
27003
- Same pattern for any other entity referenced in the event: \`tasks get\`,
27004
- \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
27005
-
27006
- ### Find context with search first
27007
-
27008
- Reach for unified semantic search before paging chat history:
27009
-
27010
- parall search "pricing decision june" [--limit 10]
27011
-
27012
- It spans messages, tasks, and wiki. Page \`messages list\` only for the verbatim
27013
- recent flow of one chat, not for discovery.
27014
-
27015
- ### File attachments
27016
-
27017
- Messages may include attachments. They appear in events as:
27018
-
27019
- [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
27020
-
27021
- To download an attachment, use the CLI:
27022
-
27023
- parall files download att_xxx --output /tmp/screenshot.png
27024
-
27025
- To send a file:
27026
-
27027
- parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
27028
-
27029
- Or upload first and reuse across chats:
27030
-
27031
- parall files upload /tmp/report.pdf
27032
- parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
27033
- parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
27034
-
27035
- The \`--text\` captions above are safe short literals. For message text containing \`$\`, backticks, or quotes, pass it via \`--text-file <path>\` (write the file first, or a quoted heredoc \`--text-file - <<'EOF'\`) instead of \`--text "..."\` \u2014 inside double quotes the shell turns \`$1,000\` into \`,000\` and executes \`$(...)\`.
27036
-
27037
- ### When to reference
27038
-
27039
- - **Origin** \u2014 always link the message or task that triggered your work
27040
- - **Design docs / wiki** \u2014 link specs and guides relevant to the work
27041
- - **Related tasks** \u2014 link parent, sibling, or blocking tasks
27042
- - **People** \u2014 link assignees or stakeholders when mentioning them
27043
- - **Conversations** \u2014 link a chat or message range as context
27044
-
27045
- ### Why this matters
27046
-
27047
- Other agents and humans read your output. References build a navigable context graph \u2014
27048
- in multi-agent workflows, your references are the map that the next agent follows.`;
27049
- function renderLocalAttachmentSection(section) {
27050
- if (section.images.length === 0 && section.notes.length === 0)
27051
- return "";
27052
- const lines = ["[Local attachment files]"];
27053
- for (const image of section.images) {
27054
- lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
27055
- }
27056
- lines.push(...section.notes);
27057
- return lines.join("\n");
27058
- }
27059
- function sanitizePromptMeta(value) {
27060
- return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
27061
- }
27062
- function formatBytes(bytes) {
27063
- if (bytes >= 1048576)
27064
- return `${(bytes / 1048576).toFixed(1)}MB`;
27065
- if (bytes >= 1024)
27066
- return `${Math.round(bytes / 1024)}KB`;
27067
- return `${bytes}B`;
27068
- }
27069
-
27070
- // ts/agent-core/dist/bridge-workspace.js
27071
- var BRIDGE_WORKSPACE_INSTRUCTIONS = `# Agent workspace
27072
-
27073
- You are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.
27074
-
27075
- ## Message Model
27076
-
27077
- Incoming events are rendered as structured \`[Event: ...]\` blocks.
27078
- Each event includes \`[Chat: ... (prll://cht_xxx)]\` \u2014 use that chat ID (or full URI) when replying.
27079
-
27080
- **Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.
27081
- To say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.
27082
-
27083
- ## Parall CLI
27084
-
27085
- All outbound interactions go through the \`parall\` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If \`parall\` is not on PATH, use \`npx --yes @parall/cli@latest\` instead.
27086
-
27087
- - \`parall messages send prll://cht_xxx --text-file -\` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)
27088
- - \`parall dm prll://usr_xxx --text-file - [--no-reply]\` \u2014 direct message another user
27089
- - \`parall tasks update prll://tsk_xxx --status in_progress\` \u2014 task state
27090
- - \`parall no-reply [--reason "..."]\` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)
27091
-
27092
- **Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands \`$\`, backticks, and \`$(...)\` inside \`"..."\` before the CLI sees them: \`--text "That costs $1,000"\` sends \`That costs ,000\`, and \`--text "$(cmd)"\` executes \`cmd\`. Pass message bodies via \`--text-file <path>\` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:
27093
-
27094
- \`\`\`bash
27095
- parall messages send prll://cht_xxx --text-file - <<'EOF'
27096
- That costs $1,000, and $(whoami) stays literal. I'm on it.
27097
- EOF
27098
- \`\`\`
27099
-
27100
- Keep \`--text "..."\` for short literals with no \`$\`, backtick, or apostrophe.
27101
-
27102
- The bridge injects Parall context via environment variables. The static credentials \`PRLL_API_URL\`, \`PRLL_API_KEY\`, and \`PRLL_ORG_ID\` are always set. \`PRLL_CONTEXT_FILE\` points to a per-session JSON file that the gateway updates each dispatch with \`session_id\`, \`chat_id\`, \`trigger_message_id\`, \`no_reply\`, and \`step_id\` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass \`--chat\` or \`--session\` explicitly when the context file is present.
27103
-
27104
- CLI errors are agent-readable \u2014 read them; they usually name the next step.
27105
-
27106
- ## Attachments
27107
-
27108
- Image attachments are pre-downloaded under \`.parall/attachments/<messageId>/\`. Each event's \`[Local attachment files]\` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.
27109
-
27110
- Supported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with \`parall files download att_xxx --output ...\`.
27111
-
27112
- ## Guardrails
27113
-
27114
- - A dispatch may coalesce multiple events. Decide per event whether to reply via \`messages send\` / \`dm\` \u2014 events you do not act on simply receive no reply.
27115
- - If an event carries \`[Hint: no_reply]\`, do not send anything for that event. \`no-reply\` is optional and only useful as an explicit intent marker.
27116
- - Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.
27117
- - Keep CLI replies concise and task-focused.
27118
-
27119
- See \`docs/engineering-design/agent-dm-loop-prevention.md\` \xA7 Layer 0 for why plain text is never auto-projected.
27120
-
27121
- ## Approval Flow
27122
-
27123
- When you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:
27124
-
27125
- 1. The error includes a \`PERMISSION_DENIED\` code plus the denied \`action\` and \`resource_uri\`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a \`Request approval:\` line with an approval command is printed \u2014 fill in its \`--chat\`, \`--title\`, \`--reason\` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.
27126
- 2. Request approval: \`parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"\`
27127
- 3. A card will appear in the specified chat for someone with permission to approve
27128
- 4. Check the result: \`parall approvals get prll://<id>\` or wait: \`parall approvals wait prll://<id> --timeout 300\`
27129
- 5. List available actions: \`parall approvals actions\`
27130
-
27131
- Only request approval when you've actually been denied permission. Don't request approval preemptively.
27132
- `;
27133
- function extractShellCommand(input) {
27134
- if (!input || typeof input !== "object")
27135
- return void 0;
27136
- const command = input.command;
27137
- return typeof command === "string" && command.trim() ? command.trim() : void 0;
27138
- }
27139
- function parseParallCliInvocation(command) {
27140
- const tokens = command.replace(/\s+/g, " ").trim().split(" ");
27141
- let i = 0;
27142
- if (tokens[i] === "parall") {
27143
- i++;
27144
- } else if (tokens[i] === "npx") {
27145
- i++;
27146
- while (i < tokens.length && tokens[i].startsWith("-"))
27147
- i++;
27148
- if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
27149
- return null;
27150
- i++;
27151
- } else if (tokens[i] === "pnpm") {
27152
- i++;
27153
- if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
27154
- i++;
27155
- if (i >= tokens.length || tokens[i] !== "parall")
27156
- return null;
27157
- i++;
27158
- } else {
27159
- return null;
27160
- }
27161
- return tokens.slice(i).filter((t) => !t.startsWith("-"));
27162
- }
27163
- function isParallSendCommand(command) {
27164
- if (!command)
27165
- return false;
27166
- const sub = parseParallCliInvocation(command);
27167
- if (!sub || sub.length === 0)
27168
- return false;
27169
- return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
27170
- }
27171
- function isParallNoReplyCommand(command) {
27172
- if (!command)
27173
- return false;
27174
- const sub = parseParallCliInvocation(command);
27175
- return sub?.[0] === "no-reply";
27176
- }
27177
-
27178
- // ts/agent-core/dist/dispatch-adapter.js
27179
- function buildErrorStepContent(message) {
27180
- return { text: message, suppressed: false, status: "error" };
27181
- }
27182
-
27183
- // ts/agent-core/dist/logger.js
27184
- function createLogger(prefix) {
27185
- return {
27186
- info: (msg) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
27187
- warn: (msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
27188
- error: (msg) => console.error(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
27189
- child: (sub) => createLogger(`${prefix}:${sub}`)
27190
- };
27191
- }
27192
- function childLogger(logger, sub) {
27193
- return logger.child ? logger.child(sub) : logger;
27194
- }
27195
-
27196
- // ts/agent-core/dist/gateway-base.js
27197
- import * as os from "node:os";
27198
- import * as fs2 from "node:fs";
27199
- import * as path2 from "node:path";
26490
+ // ts/agent-core/dist/lane-ledger.js
26491
+ import * as fs from "node:fs";
27200
26492
 
27201
26493
  // ts/sdk/dist/types.js
27202
26494
  var MENTION_ALL_USER_ID = "all";
@@ -27642,6 +26934,7 @@ var ParallClient = class _ParallClient {
27642
26934
  setTokens;
27643
26935
  refreshPromise = null;
27644
26936
  swimlaneName;
26937
+ getFeatureFlagOverrides;
27645
26938
  /** Auth endpoints excluded from automatic 401 refresh to prevent recursion. */
27646
26939
  static AUTH_PATHS = /* @__PURE__ */ new Set([
27647
26940
  "/auth/login",
@@ -27672,7 +26965,7 @@ var ParallClient = class _ParallClient {
27672
26965
  return apiError;
27673
26966
  }
27674
26967
  /** Build headers common to all requests (auth, swimlane). */
27675
- buildHeaders(extra) {
26968
+ buildHeaders(path11, extra) {
27676
26969
  const headers = {
27677
26970
  "Content-Type": "application/json",
27678
26971
  ...extra
@@ -27683,6 +26976,11 @@ var ParallClient = class _ParallClient {
27683
26976
  if (this.swimlaneName) {
27684
26977
  headers["X-Prll-Swimlane"] = this.swimlaneName;
27685
26978
  }
26979
+ if (path11.startsWith(API_BASE)) {
26980
+ const overrides = this.getFeatureFlagOverrides?.();
26981
+ if (overrides)
26982
+ headers["X-Prll-FF-Override"] = overrides;
26983
+ }
27686
26984
  return headers;
27687
26985
  }
27688
26986
  constructor(options = {}) {
@@ -27693,6 +26991,7 @@ var ParallClient = class _ParallClient {
27693
26991
  this.getRefreshToken = options.getRefreshToken;
27694
26992
  this.setTokens = options.setTokens;
27695
26993
  this.swimlaneName = options.swimlaneName;
26994
+ this.getFeatureFlagOverrides = options.getFeatureFlagOverrides;
27696
26995
  }
27697
26996
  /**
27698
26997
  * Pick the origin for a request path: wiki-service base for `/wiki/v1`
@@ -27700,8 +26999,8 @@ var ParallClient = class _ParallClient {
27700
26999
  * is authoritative, so wiki vs api routing can't drift from how a caller
27701
27000
  * happens to invoke the client.
27702
27001
  */
27703
- baseUrlFor(path9) {
27704
- return path9.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
27002
+ baseUrlFor(path11) {
27003
+ return path11.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
27705
27004
  }
27706
27005
  setToken(token) {
27707
27006
  this.token = token;
@@ -27728,10 +27027,10 @@ var ParallClient = class _ParallClient {
27728
27027
  * REFRESH_THRESHOLD_S, refresh it **before** sending the request.
27729
27028
  * No-op when the token is still fresh, missing, or un-parseable.
27730
27029
  */
27731
- async ensureFreshToken(path9) {
27030
+ async ensureFreshToken(path11) {
27732
27031
  if (!this.token || !this.getRefreshToken)
27733
27032
  return;
27734
- const pathSuffix = path9.replace(/^\/api\/v1/, "");
27033
+ const pathSuffix = path11.replace(/^\/api\/v1/, "");
27735
27034
  if (_ParallClient.AUTH_PATHS.has(pathSuffix))
27736
27035
  return;
27737
27036
  const exp = _ParallClient.decodeJwtExp(this.token);
@@ -27763,11 +27062,11 @@ var ParallClient = class _ParallClient {
27763
27062
  this.refreshPromise = null;
27764
27063
  }
27765
27064
  }
27766
- async request(method, path9, body, query, retried = false, opts) {
27065
+ async request(method, path11, body, query, retried = false, opts) {
27767
27066
  if (!retried) {
27768
- await this.ensureFreshToken(path9);
27067
+ await this.ensureFreshToken(path11);
27769
27068
  }
27770
- let url = `${this.baseUrlFor(path9)}${path9}`;
27069
+ let url = `${this.baseUrlFor(path11)}${path11}`;
27771
27070
  if (query) {
27772
27071
  const params = new URLSearchParams();
27773
27072
  for (const [key, value] of Object.entries(query)) {
@@ -27779,7 +27078,7 @@ var ParallClient = class _ParallClient {
27779
27078
  if (qs)
27780
27079
  url += `?${qs}`;
27781
27080
  }
27782
- const headers = this.buildHeaders();
27081
+ const headers = this.buildHeaders(path11);
27783
27082
  const timeoutSignal = AbortSignal.timeout(opts?.timeoutMs ?? 15e3);
27784
27083
  const signal = opts?.signal ? AbortSignal.any([opts.signal, timeoutSignal]) : timeoutSignal;
27785
27084
  let res;
@@ -27797,12 +27096,12 @@ var ParallClient = class _ParallClient {
27797
27096
  throw _ParallClient.normalizeFetchError(err);
27798
27097
  }
27799
27098
  if (res.status === 401) {
27800
- const pathSuffix = path9.replace(/^\/api\/v1/, "");
27099
+ const pathSuffix = path11.replace(/^\/api\/v1/, "");
27801
27100
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
27802
27101
  if (!retried && !isAuthPath && this.getRefreshToken) {
27803
27102
  const refreshed = await this.tryRefresh();
27804
27103
  if (refreshed) {
27805
- return this.request(method, path9, body, query, true, opts);
27104
+ return this.request(method, path11, body, query, true, opts);
27806
27105
  }
27807
27106
  }
27808
27107
  if (this.onTokenExpired && !isAuthPath) {
@@ -27832,15 +27131,15 @@ var ParallClient = class _ParallClient {
27832
27131
  * hit the 100 MiB cap, so a longer 5-minute timeout is used so a
27833
27132
  * 50 MiB blob on a slow connection doesn't get chopped at 15 s.
27834
27133
  */
27835
- async multipartRequest(method, path9, body, retried = false) {
27134
+ async multipartRequest(method, path11, body, retried = false) {
27836
27135
  if (!retried) {
27837
- await this.ensureFreshToken(path9);
27136
+ await this.ensureFreshToken(path11);
27838
27137
  }
27839
- const { "Content-Type": _drop, ...headers } = this.buildHeaders();
27138
+ const { "Content-Type": _drop, ...headers } = this.buildHeaders(path11);
27840
27139
  void _drop;
27841
27140
  let res;
27842
27141
  try {
27843
- res = await fetch(`${this.baseUrlFor(path9)}${path9}`, {
27142
+ res = await fetch(`${this.baseUrlFor(path11)}${path11}`, {
27844
27143
  method,
27845
27144
  headers,
27846
27145
  body,
@@ -27850,12 +27149,12 @@ var ParallClient = class _ParallClient {
27850
27149
  throw _ParallClient.normalizeFetchError(err);
27851
27150
  }
27852
27151
  if (res.status === 401) {
27853
- const pathSuffix = path9.replace(/^\/api\/v1/, "");
27152
+ const pathSuffix = path11.replace(/^\/api\/v1/, "");
27854
27153
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
27855
27154
  if (!retried && !isAuthPath && this.getRefreshToken) {
27856
27155
  const refreshed = await this.tryRefresh();
27857
27156
  if (refreshed) {
27858
- return this.multipartRequest(method, path9, body, true);
27157
+ return this.multipartRequest(method, path11, body, true);
27859
27158
  }
27860
27159
  }
27861
27160
  if (this.onTokenExpired && !isAuthPath) {
@@ -28559,8 +27858,8 @@ var ParallClient = class _ParallClient {
28559
27858
  async requestMachineUpdate(orgId, machineId, mandatory = false) {
28560
27859
  await this.request("POST", ENDPOINTS.MACHINE_REQUEST_UPDATE(orgId, machineId), { mandatory });
28561
27860
  }
28562
- async browseMachineFilesystem(orgId, machineId, path9) {
28563
- return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path9 }, void 0, false, { timeoutMs: 15e3 });
27861
+ async browseMachineFilesystem(orgId, machineId, path11) {
27862
+ return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path11 }, void 0, false, { timeoutMs: 15e3 });
28564
27863
  }
28565
27864
  /** Create a new machine key. Returns the raw key string (shown once) + metadata. */
28566
27865
  async createMachineKey(orgId, machineId, name) {
@@ -28641,7 +27940,7 @@ var ParallClient = class _ParallClient {
28641
27940
  async claimDispatch(orgId, req) {
28642
27941
  return this.request("POST", ENDPOINTS.DISPATCH_CLAIM(orgId), req);
28643
27942
  }
28644
- /** Fold a pending same-target WorkItem into a live lane (409 STALE_LANE when dethroned). */
27943
+ /** Fold into a live lane: 409 STALE_LANE when dethroned; 409 INELIGIBLE_REF for a bad ref. */
28645
27944
  async steerDispatch(orgId, req) {
28646
27945
  return this.request("POST", ENDPOINTS.DISPATCH_STEER(orgId), req);
28647
27946
  }
@@ -28681,7 +27980,7 @@ var ParallClient = class _ParallClient {
28681
27980
  if (currentVersion !== void 0) {
28682
27981
  extra["If-None-Match"] = currentVersion;
28683
27982
  }
28684
- const headers = this.buildHeaders(extra);
27983
+ const headers = this.buildHeaders(ENDPOINTS.PLATFORM_CONFIG, extra);
28685
27984
  let res;
28686
27985
  try {
28687
27986
  res = await fetch(url, {
@@ -29129,8 +28428,8 @@ var ParallClient = class _ParallClient {
29129
28428
  async deleteWikiRestriction(orgId, wikiId, restrictionId) {
29130
28429
  await this.request("DELETE", ENDPOINTS.WIKI_RESTRICTION(orgId, wikiId, restrictionId));
29131
28430
  }
29132
- async getWikiAccessStatus(orgId, wikiId, path9) {
29133
- return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path9 ? { path: path9 } : void 0);
28431
+ async getWikiAccessStatus(orgId, wikiId, path11) {
28432
+ return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path11 ? { path: path11 } : void 0);
29134
28433
  }
29135
28434
  async createWikiAccessRequest(orgId, wikiId, data) {
29136
28435
  await this.request("POST", ENDPOINTS.WIKI_ACCESS_REQUESTS(orgId, wikiId), data);
@@ -29139,14 +28438,14 @@ var ParallClient = class _ParallClient {
29139
28438
  async getWikiCommits(orgId, wikiId, params) {
29140
28439
  return this.request("GET", ENDPOINTS.WIKI_COMMITS(orgId, wikiId), void 0, params);
29141
28440
  }
29142
- async getWikiFileCommits(orgId, wikiId, path9, params) {
28441
+ async getWikiFileCommits(orgId, wikiId, path11, params) {
29143
28442
  return this.request("GET", ENDPOINTS.WIKI_FILE_COMMITS(orgId, wikiId), void 0, {
29144
- path: path9,
28443
+ path: path11,
29145
28444
  ...params
29146
28445
  });
29147
28446
  }
29148
- async getWikiBlame(orgId, wikiId, path9, ref) {
29149
- return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path9, ref });
28447
+ async getWikiBlame(orgId, wikiId, path11, ref) {
28448
+ return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path11, ref });
29150
28449
  }
29151
28450
  // ---- Wiki Operations (audit log) ----
29152
28451
  async getWikiOperations(orgId, wikiId, params) {
@@ -29590,612 +28889,1390 @@ var ParallWs = class {
29590
28889
  this.ws.close();
29591
28890
  this.ws = null;
29592
28891
  }
29593
- this.setState("disconnected");
29594
- }
29595
- // ---- Client -> Server messages ----
29596
- /** Tell the server which chats the user is currently viewing (no auth implications). */
29597
- watch(chatIds) {
29598
- this.send({ type: WS_EVENTS.WATCH, data: { chat_ids: chatIds } });
28892
+ this.setState("disconnected");
28893
+ }
28894
+ // ---- Client -> Server messages ----
28895
+ /** Tell the server which chats the user is currently viewing (no auth implications). */
28896
+ watch(chatIds) {
28897
+ this.send({ type: WS_EVENTS.WATCH, data: { chat_ids: chatIds } });
28898
+ }
28899
+ sendTyping(chatId, action, threadRootId) {
28900
+ this.send({
28901
+ type: WS_EVENTS.TYPING,
28902
+ data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
28903
+ });
28904
+ }
28905
+ /** Send an agent heartbeat with telemetry data. */
28906
+ sendAgentHeartbeat(sessionId, telemetry) {
28907
+ this.send({
28908
+ type: WS_EVENTS.AGENT_HEARTBEAT,
28909
+ data: { session_id: sessionId, telemetry }
28910
+ });
28911
+ }
28912
+ sendEvent(type, data) {
28913
+ this.send({ type, data });
28914
+ }
28915
+ // ---- Event listeners ----
28916
+ on(event, handler) {
28917
+ let set = this.listeners.get(event);
28918
+ if (!set) {
28919
+ set = /* @__PURE__ */ new Set();
28920
+ this.listeners.set(event, set);
28921
+ }
28922
+ set.add(handler);
28923
+ return () => {
28924
+ set.delete(handler);
28925
+ };
28926
+ }
28927
+ off(event, handler) {
28928
+ this.listeners.get(event)?.delete(handler);
28929
+ }
28930
+ onStateChange(handler) {
28931
+ this.stateListeners.add(handler);
28932
+ return () => {
28933
+ this.stateListeners.delete(handler);
28934
+ };
28935
+ }
28936
+ // ---- Internal ----
28937
+ send(frame) {
28938
+ if (this.ws?.readyState === WebSocket.OPEN) {
28939
+ this.ws.send(JSON.stringify(frame));
28940
+ }
28941
+ }
28942
+ handleFrame(frame) {
28943
+ this.lastReceivedAt = Date.now();
28944
+ this.clearProbe();
28945
+ if (frame.seq !== void 0) {
28946
+ this.lastSeq = frame.seq;
28947
+ }
28948
+ if (frame.type === WS_EVENTS.HELLO) {
28949
+ const interval = frame.data.heartbeat_interval;
28950
+ this.startHeartbeat(interval);
28951
+ }
28952
+ const handlers = this.listeners.get(frame.type);
28953
+ if (handlers) {
28954
+ for (const handler of handlers) {
28955
+ handler(frame.data, frame.seq);
28956
+ }
28957
+ }
28958
+ }
28959
+ startHeartbeat(intervalSec) {
28960
+ this.stopHeartbeat();
28961
+ if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
28962
+ console.error("Invalid heartbeat interval from server:", intervalSec);
28963
+ return;
28964
+ }
28965
+ this.heartbeatIntervalMs = intervalSec * 1e3;
28966
+ this.heartbeatTimer = setInterval(() => {
28967
+ if (this.lastReceivedAt > 0 && Date.now() - this.lastReceivedAt > this.heartbeatIntervalMs * 1.5) {
28968
+ this.probeConnection();
28969
+ return;
28970
+ }
28971
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
28972
+ }, intervalSec * 1e3);
28973
+ }
28974
+ stopHeartbeat() {
28975
+ if (this.heartbeatTimer) {
28976
+ clearInterval(this.heartbeatTimer);
28977
+ this.heartbeatTimer = null;
28978
+ }
28979
+ }
28980
+ scheduleReconnect() {
28981
+ this.setState("reconnecting");
28982
+ this.clearReconnect();
28983
+ const base = Math.min(this.options.reconnectInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
28984
+ const delay = base * (0.5 + Math.random() * 0.5);
28985
+ this.reconnectAttempts++;
28986
+ this.reconnectTimer = setTimeout(() => {
28987
+ this.connect();
28988
+ }, delay);
28989
+ }
28990
+ clearReconnect() {
28991
+ if (this.reconnectTimer) {
28992
+ clearTimeout(this.reconnectTimer);
28993
+ this.reconnectTimer = null;
28994
+ }
28995
+ }
28996
+ /** Force-close a dead/stale connection and trigger reconnect. */
28997
+ forceReconnect() {
28998
+ this.stopHeartbeat();
28999
+ this.clearReconnect();
29000
+ this.clearProbe();
29001
+ if (this.ws) {
29002
+ this.ws.onclose = null;
29003
+ this.ws.onopen = null;
29004
+ this.ws.onerror = null;
29005
+ this.ws.onmessage = null;
29006
+ try {
29007
+ this.ws.close();
29008
+ } catch {
29009
+ }
29010
+ this.ws = null;
29011
+ }
29012
+ if (this.options.reconnect && !this.intentionalClose) {
29013
+ this.scheduleReconnect();
29014
+ } else {
29015
+ this.setState("disconnected");
29016
+ }
29017
+ }
29018
+ // ---- Browser event listeners for proactive reconnection ----
29019
+ setupBrowserListeners() {
29020
+ if (this.browserListenersActive)
29021
+ return;
29022
+ this.browserListenersActive = true;
29023
+ if (typeof document !== "undefined") {
29024
+ document.addEventListener("visibilitychange", this.handleVisibilityChange);
29025
+ }
29026
+ if (typeof window !== "undefined") {
29027
+ window.addEventListener("online", this.handleOnline);
29028
+ }
29029
+ }
29030
+ teardownBrowserListeners() {
29031
+ if (!this.browserListenersActive)
29032
+ return;
29033
+ this.browserListenersActive = false;
29034
+ if (typeof document !== "undefined") {
29035
+ document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29036
+ }
29037
+ if (typeof window !== "undefined") {
29038
+ window.removeEventListener("online", this.handleOnline);
29039
+ }
29040
+ }
29041
+ /**
29042
+ * Send a ping and arm a short timeout. If no frame arrives within 5s the
29043
+ * connection is assumed dead and force-reconnected. Any received frame
29044
+ * (including the pong) cancels the timer via clearProbe() in handleFrame.
29045
+ */
29046
+ probeConnection() {
29047
+ if (this.probeTimer)
29048
+ return;
29049
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29050
+ this.probeTimer = setTimeout(() => {
29051
+ this.forceReconnect();
29052
+ }, 5e3);
29053
+ }
29054
+ clearProbe() {
29055
+ if (this.probeTimer) {
29056
+ clearTimeout(this.probeTimer);
29057
+ this.probeTimer = null;
29058
+ }
29059
+ }
29060
+ /** Tab returned to foreground — verify connection or accelerate reconnect. */
29061
+ handleVisibilityChange = () => {
29062
+ if (typeof document !== "undefined" && document.hidden)
29063
+ return;
29064
+ if (this._state === "connected") {
29065
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29066
+ this.forceReconnect();
29067
+ } else {
29068
+ this.probeConnection();
29069
+ }
29070
+ } else if (this._state === "reconnecting") {
29071
+ this.clearReconnect();
29072
+ this.reconnectAttempts = 0;
29073
+ this.connect();
29074
+ }
29075
+ };
29076
+ /** Network restored — accelerate reconnection. */
29077
+ handleOnline = () => {
29078
+ if (this.intentionalClose)
29079
+ return;
29080
+ if (this._state === "connected") {
29081
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29082
+ this.forceReconnect();
29083
+ } else {
29084
+ this.probeConnection();
29085
+ }
29086
+ } else if (this._state === "reconnecting") {
29087
+ this.clearReconnect();
29088
+ this.reconnectAttempts = 0;
29089
+ this.connect();
29090
+ }
29091
+ };
29092
+ setState(state) {
29093
+ this._state = state;
29094
+ for (const listener of this.stateListeners) {
29095
+ listener(state);
29096
+ }
29599
29097
  }
29600
- sendTyping(chatId, action, threadRootId) {
29601
- this.send({
29602
- type: WS_EVENTS.TYPING,
29603
- data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
29604
- });
29098
+ };
29099
+
29100
+ // ts/agent-core/dist/lane-ledger.js
29101
+ var LedgerUnsupportedError = class extends Error {
29102
+ };
29103
+ function isStaleLane(err) {
29104
+ return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
29105
+ }
29106
+ function isEndpointMissing(err) {
29107
+ return err instanceof ApiError && err.status === 404 && !err.code;
29108
+ }
29109
+ var LaneLedger = class {
29110
+ opts;
29111
+ lanes = /* @__PURE__ */ new Map();
29112
+ constructor(opts) {
29113
+ this.opts = opts;
29605
29114
  }
29606
- /** Send an agent heartbeat with telemetry data. */
29607
- sendAgentHeartbeat(sessionId, telemetry) {
29608
- this.send({
29609
- type: WS_EVENTS.AGENT_HEARTBEAT,
29610
- data: { session_id: sessionId, telemetry }
29611
- });
29115
+ get contextDir() {
29116
+ return this.opts.contextDir;
29612
29117
  }
29613
- sendEvent(type, data) {
29614
- this.send({ type, data });
29118
+ /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
29119
+ handles(event) {
29120
+ return event.type === "message" && event.targetId.startsWith("cht_");
29615
29121
  }
29616
- // ---- Event listeners ----
29617
- on(event, handler) {
29618
- let set = this.listeners.get(event);
29619
- if (!set) {
29620
- set = /* @__PURE__ */ new Set();
29621
- this.listeners.set(event, set);
29122
+ laneKeyFor(event) {
29123
+ if (event.type !== "message" && event.dispatchEventId) {
29124
+ return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29622
29125
  }
29623
- set.add(handler);
29624
- return () => {
29625
- set.delete(handler);
29626
- };
29126
+ return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29627
29127
  }
29628
- off(event, handler) {
29629
- this.listeners.get(event)?.delete(handler);
29128
+ getForEvent(event) {
29129
+ return this.lanes.get(this.laneKeyFor(event));
29630
29130
  }
29631
- onStateChange(handler) {
29632
- this.stateListeners.add(handler);
29633
- return () => {
29634
- this.stateListeners.delete(handler);
29635
- };
29131
+ laneContextPath(lane) {
29132
+ return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29636
29133
  }
29637
- // ---- Internal ----
29638
- send(frame) {
29639
- if (this.ws?.readyState === WebSocket.OPEN) {
29640
- this.ws.send(JSON.stringify(frame));
29134
+ /**
29135
+ * Claim (or reuse) the lane for a group of same-lane message events and
29136
+ * fold every group member into it. Returns 'foreign' when a healthy
29137
+ * incumbent (another pod) holds the resource — the caller must not
29138
+ * dispatch; the events stay pending server-side and re-drive after the
29139
+ * incumbent completes.
29140
+ */
29141
+ async ensureLane(events) {
29142
+ const trigger = events[events.length - 1];
29143
+ const laneKey = this.laneKeyFor(trigger);
29144
+ let lane = this.lanes.get(laneKey);
29145
+ if (!lane) {
29146
+ const targetUri = `prll://${trigger.targetId}`;
29147
+ let res;
29148
+ try {
29149
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29150
+ target_uri: targetUri,
29151
+ thread_root_id: trigger.threadRootId,
29152
+ limit: 100
29153
+ });
29154
+ } catch (err) {
29155
+ if (isEndpointMissing(err))
29156
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29157
+ throw err;
29158
+ }
29159
+ if (!res.claimed || !res.lane) {
29160
+ this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
29161
+ return null;
29162
+ }
29163
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29164
+ lane = {
29165
+ laneKey,
29166
+ lane: res.lane,
29167
+ targetUri,
29168
+ threadRootId: trigger.threadRootId,
29169
+ folded: /* @__PURE__ */ new Map(),
29170
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29171
+ };
29172
+ for (const ev of res.events ?? []) {
29173
+ lane.folded.set(ev.source_id, ev.id);
29174
+ }
29175
+ this.lanes.set(laneKey, lane);
29641
29176
  }
29642
- }
29643
- handleFrame(frame) {
29644
- this.lastReceivedAt = Date.now();
29645
- this.clearProbe();
29646
- if (frame.seq !== void 0) {
29647
- this.lastSeq = frame.seq;
29177
+ for (const ev of events) {
29178
+ if (lane.folded.has(ev.messageId))
29179
+ continue;
29180
+ try {
29181
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29182
+ lane: lane.lane,
29183
+ target_uri: lane.targetUri,
29184
+ thread_root_id: lane.threadRootId,
29185
+ ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
29186
+ });
29187
+ lane.folded.set(ev.messageId, res.dispatch_event_id);
29188
+ } catch (err) {
29189
+ if (isStaleLane(err)) {
29190
+ this.lanes.delete(laneKey);
29191
+ return null;
29192
+ }
29193
+ this.opts.log?.warn(`steer fold failed for ${ev.messageId} \u2014 failing closed, releasing lane: ${String(err)}`);
29194
+ await this.release(laneKey);
29195
+ return null;
29196
+ }
29648
29197
  }
29649
- if (frame.type === WS_EVENTS.HELLO) {
29650
- const interval = frame.data.heartbeat_interval;
29651
- this.startHeartbeat(interval);
29198
+ return lane;
29199
+ }
29200
+ /**
29201
+ * Fold a live mid-turn message into its active lane BEFORE injecting it
29202
+ * into the running turn. Injection without a successful fold is forbidden —
29203
+ * an un-folded injected message would be re-driven after complete and the
29204
+ * model would handle it twice.
29205
+ */
29206
+ async steerLive(event) {
29207
+ const laneKey = this.laneKeyFor(event);
29208
+ const lane = this.lanes.get(laneKey);
29209
+ if (!lane)
29210
+ return false;
29211
+ if (lane.folded.has(event.messageId))
29212
+ return true;
29213
+ try {
29214
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29215
+ lane: lane.lane,
29216
+ target_uri: lane.targetUri,
29217
+ thread_root_id: lane.threadRootId,
29218
+ ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
29219
+ });
29220
+ lane.folded.set(event.messageId, res.dispatch_event_id);
29221
+ return true;
29222
+ } catch (err) {
29223
+ if (isStaleLane(err)) {
29224
+ this.lanes.delete(laneKey);
29225
+ } else {
29226
+ this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
29227
+ }
29228
+ return false;
29652
29229
  }
29653
- const handlers = this.listeners.get(frame.type);
29654
- if (handlers) {
29655
- for (const handler of handlers) {
29656
- handler(frame.data, frame.seq);
29230
+ }
29231
+ /**
29232
+ * Complete the lane when no local work remains for it: the server sweeps
29233
+ * still-leased members as no_action, releases the occupancy row, and
29234
+ * re-drives any same-target pending work. A STALE_LANE answer means a
29235
+ * takeover already owns the resource — local state is dropped either way.
29236
+ */
29237
+ async completeIfIdle(laneKey, hasMoreLocal) {
29238
+ const lane = this.lanes.get(laneKey);
29239
+ if (!lane || hasMoreLocal)
29240
+ return;
29241
+ this.lanes.delete(laneKey);
29242
+ this.removeLaneContext(lane);
29243
+ try {
29244
+ const res = await this.opts.client.completeDispatch(this.opts.orgId, {
29245
+ lane: lane.lane,
29246
+ target_uri: lane.targetUri,
29247
+ thread_root_id: lane.threadRootId
29248
+ });
29249
+ if (res.swept_no_action > 0 || res.redriven) {
29250
+ this.opts.log?.info(`lane complete for ${lane.targetUri}: swept ${res.swept_no_action} no_action, redriven=${res.redriven}`);
29251
+ }
29252
+ } catch (err) {
29253
+ if (isStaleLane(err)) {
29254
+ this.opts.log?.info(`lane complete skipped for ${lane.targetUri} \u2014 taken over`);
29255
+ return;
29657
29256
  }
29257
+ this.opts.log?.warn(`lane complete failed for ${lane.targetUri}: ${String(err)}`);
29658
29258
  }
29659
29259
  }
29660
- startHeartbeat(intervalSec) {
29661
- this.stopHeartbeat();
29662
- if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
29663
- console.error("Invalid heartbeat interval from server:", intervalSec);
29260
+ /**
29261
+ * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
29262
+ * so a chatty turn doesn't spam the server. Without this, a legitimately
29263
+ * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
29264
+ * write misfired with STALE_LANE — the design doc's "long turns renew via
29265
+ * step writes". Fire-and-forget: a failed renewal is surfaced by the next
29266
+ * write's incumbency check anyway.
29267
+ */
29268
+ maybeRenew(lane) {
29269
+ const now = Date.now();
29270
+ const ttl = lane.leaseTtlMs ?? 10 * 6e4;
29271
+ const until = lane.leaseUntilMs ?? now;
29272
+ if (until - now > ttl / 2)
29273
+ return;
29274
+ lane.leaseUntilMs = now + ttl;
29275
+ void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
29276
+ lane: lane.lane,
29277
+ target_uri: lane.targetUri,
29278
+ thread_root_id: lane.threadRootId
29279
+ }).then((res) => {
29280
+ const until2 = Date.parse(res?.lease_until ?? "");
29281
+ if (!Number.isNaN(until2))
29282
+ lane.leaseUntilMs = until2;
29283
+ }).catch((err) => {
29284
+ if (isStaleLane(err)) {
29285
+ this.lanes.delete(lane.laneKey);
29286
+ this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
29287
+ return;
29288
+ }
29289
+ this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
29290
+ });
29291
+ }
29292
+ /**
29293
+ * Release a lane's unresolved members back to pending (dispatch error /
29294
+ * shutdown) so the next pod re-claims immediately instead of waiting out
29295
+ * the lease.
29296
+ */
29297
+ async release(laneKey) {
29298
+ const lane = this.lanes.get(laneKey);
29299
+ if (!lane)
29664
29300
  return;
29301
+ this.lanes.delete(laneKey);
29302
+ this.removeLaneContext(lane);
29303
+ try {
29304
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane);
29305
+ } catch (err) {
29306
+ this.opts.log?.warn(`lane release failed for ${lane.targetUri}: ${String(err)}`);
29665
29307
  }
29666
- this.heartbeatIntervalMs = intervalSec * 1e3;
29667
- this.heartbeatTimer = setInterval(() => {
29668
- if (this.lastReceivedAt > 0 && Date.now() - this.lastReceivedAt > this.heartbeatIntervalMs * 1.5) {
29669
- this.probeConnection();
29670
- return;
29671
- }
29672
- this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29673
- }, intervalSec * 1e3);
29674
29308
  }
29675
- stopHeartbeat() {
29676
- if (this.heartbeatTimer) {
29677
- clearInterval(this.heartbeatTimer);
29678
- this.heartbeatTimer = null;
29309
+ async releaseAll() {
29310
+ const keys = [...this.lanes.keys()];
29311
+ for (const key of keys) {
29312
+ await this.release(key);
29679
29313
  }
29680
29314
  }
29681
- scheduleReconnect() {
29682
- this.setState("reconnecting");
29683
- this.clearReconnect();
29684
- const base = Math.min(this.options.reconnectInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
29685
- const delay = base * (0.5 + Math.random() * 0.5);
29686
- this.reconnectAttempts++;
29687
- this.reconnectTimer = setTimeout(() => {
29688
- this.connect();
29689
- }, delay);
29315
+ /** True when any lane is currently active (used by shutdown logging). */
29316
+ get activeCount() {
29317
+ return this.lanes.size;
29690
29318
  }
29691
- clearReconnect() {
29692
- if (this.reconnectTimer) {
29693
- clearTimeout(this.reconnectTimer);
29694
- this.reconnectTimer = null;
29319
+ /**
29320
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
29321
+ * by WorkItem id or by source identity (the live task.assigned event has no
29322
+ * WorkItem id). Returns null when a healthy incumbent (another pod) holds
29323
+ * it or the WorkItem is already resolved — the caller must skip processing.
29324
+ */
29325
+ async claimTyped(ref) {
29326
+ let res;
29327
+ try {
29328
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29329
+ dispatch_event_id: ref.dispatchEventId,
29330
+ source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
29331
+ source_id: ref.dispatchEventId ? void 0 : ref.sourceId
29332
+ });
29333
+ } catch (err) {
29334
+ if (isEndpointMissing(err))
29335
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29336
+ throw err;
29695
29337
  }
29338
+ if (!res.claimed || !res.lane || !res.events?.length)
29339
+ return null;
29340
+ const workItem = res.events[0];
29341
+ const targetUri = `dsp:${workItem.id}`;
29342
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29343
+ const lane = {
29344
+ laneKey: laneKeyForTarget(targetUri),
29345
+ lane: res.lane,
29346
+ targetUri,
29347
+ folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
29348
+ typedDispatchEventId: workItem.id,
29349
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29350
+ };
29351
+ this.lanes.set(lane.laneKey, lane);
29352
+ return lane;
29696
29353
  }
29697
- /** Force-close a dead/stale connection and trigger reconnect. */
29698
- forceReconnect() {
29699
- this.stopHeartbeat();
29700
- this.clearReconnect();
29701
- this.clearProbe();
29702
- if (this.ws) {
29703
- this.ws.onclose = null;
29704
- this.ws.onopen = null;
29705
- this.ws.onerror = null;
29706
- this.ws.onmessage = null;
29354
+ /**
29355
+ * Remove the per-lane context file (and its CLI sidecar) when the lane
29356
+ * ends. A leftover file would make a later cross-context send to the same
29357
+ * target bind a dead lane token and misfire with STALE_LANE instead of
29358
+ * taking the plain non-ledger path.
29359
+ */
29360
+ removeLaneContext(lane) {
29361
+ const contextPath = this.laneContextPath(lane);
29362
+ for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
29707
29363
  try {
29708
- this.ws.close();
29364
+ fs.rmSync(p, { force: true });
29709
29365
  } catch {
29710
29366
  }
29711
- this.ws = null;
29712
- }
29713
- if (this.options.reconnect && !this.intentionalClose) {
29714
- this.scheduleReconnect();
29715
- } else {
29716
- this.setState("disconnected");
29717
29367
  }
29718
29368
  }
29719
- // ---- Browser event listeners for proactive reconnection ----
29720
- setupBrowserListeners() {
29721
- if (this.browserListenersActive)
29722
- return;
29723
- this.browserListenersActive = true;
29724
- if (typeof document !== "undefined") {
29725
- document.addEventListener("visibilitychange", this.handleVisibilityChange);
29726
- }
29727
- if (typeof window !== "undefined") {
29728
- window.addEventListener("online", this.handleOnline);
29369
+ };
29370
+
29371
+ // ts/agent-core/dist/gateway-lane-flow.js
29372
+ async function dispatchLaneGroup(host, opts) {
29373
+ const ledger = host.laneLedger;
29374
+ const event = opts.events[opts.events.length - 1];
29375
+ let lane;
29376
+ try {
29377
+ lane = await ledger.ensureLane(opts.events);
29378
+ } catch (err) {
29379
+ if (!(err instanceof LedgerUnsupportedError))
29380
+ throw err;
29381
+ host.disableLedger("claim endpoint missing");
29382
+ await host.emitDispatchReceived(event);
29383
+ const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29384
+ if (!dispatched2)
29385
+ return "shutdown";
29386
+ for (const ev of opts.events) {
29387
+ host.opts.client.ackDispatch(host.opts.config.org_id, {
29388
+ source_type: ev.ackSourceType ?? "message",
29389
+ source_id: ev.ackSourceId ?? ev.messageId
29390
+ }).catch(() => {
29391
+ });
29729
29392
  }
29393
+ return "dispatched";
29730
29394
  }
29731
- teardownBrowserListeners() {
29732
- if (!this.browserListenersActive)
29733
- return;
29734
- this.browserListenersActive = false;
29735
- if (typeof document !== "undefined") {
29736
- document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29737
- }
29738
- if (typeof window !== "undefined") {
29739
- window.removeEventListener("online", this.handleOnline);
29395
+ if (!lane) {
29396
+ for (const ev of opts.events) {
29397
+ host.dispatchedMessages.delete(ev.messageId);
29740
29398
  }
29399
+ return "foreign";
29741
29400
  }
29742
- /**
29743
- * Send a ping and arm a short timeout. If no frame arrives within 5s the
29744
- * connection is assumed dead and force-reconnected. Any received frame
29745
- * (including the pong) cancels the timer via clearProbe() in handleFrame.
29746
- */
29747
- probeConnection() {
29748
- if (this.probeTimer)
29749
- return;
29750
- this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29751
- this.probeTimer = setTimeout(() => {
29752
- this.forceReconnect();
29753
- }, 5e3);
29401
+ let dispatched = false;
29402
+ try {
29403
+ dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29404
+ } catch (err) {
29405
+ await ledger.release(lane.laneKey).catch(() => {
29406
+ });
29407
+ throw err;
29754
29408
  }
29755
- clearProbe() {
29756
- if (this.probeTimer) {
29757
- clearTimeout(this.probeTimer);
29758
- this.probeTimer = null;
29409
+ if (!dispatched) {
29410
+ return "shutdown";
29411
+ }
29412
+ const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
29413
+ await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
29414
+ return "dispatched";
29415
+ }
29416
+ var TYPED_BACKOFF_BASE_MS = 2e3;
29417
+ var TYPED_BACKOFF_CAP_MS = 5 * 6e4;
29418
+ var TYPED_BACKOFF_MAP_CAP = 512;
29419
+ async function consumeTypedDispatch(host, ref, run, ack) {
29420
+ const backoffKey = ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`;
29421
+ const armed = host.typedRedriveBackoff.get(backoffKey);
29422
+ if (armed) {
29423
+ const waitMs = armed.until - Date.now();
29424
+ if (waitMs > 0) {
29425
+ host.opts.log?.info(`typed dispatch ${backoffKey} backing off ${Math.ceil(waitMs / 1e3)}s after ${armed.failures} failed consume(s)`);
29426
+ await new Promise((resolve4) => {
29427
+ const timer = setTimeout(resolve4, waitMs);
29428
+ timer.unref?.();
29429
+ });
29759
29430
  }
29431
+ if (host.shuttingDown)
29432
+ return;
29760
29433
  }
29761
- /** Tab returned to foreground verify connection or accelerate reconnect. */
29762
- handleVisibilityChange = () => {
29763
- if (typeof document !== "undefined" && document.hidden)
29434
+ const settleAck = (ackResult) => ackResult !== false;
29435
+ const settle = (acked2) => {
29436
+ if (acked2) {
29437
+ host.typedRedriveBackoff.delete(backoffKey);
29764
29438
  return;
29765
- if (this._state === "connected") {
29766
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29767
- this.forceReconnect();
29768
- } else {
29769
- this.probeConnection();
29439
+ }
29440
+ const failures = (host.typedRedriveBackoff.get(backoffKey)?.failures ?? 0) + 1;
29441
+ const backoffMs = Math.min(TYPED_BACKOFF_CAP_MS, TYPED_BACKOFF_BASE_MS * 2 ** (failures - 1));
29442
+ if (host.typedRedriveBackoff.delete(backoffKey) === false && host.typedRedriveBackoff.size >= TYPED_BACKOFF_MAP_CAP) {
29443
+ const oldest = host.typedRedriveBackoff.keys().next().value;
29444
+ if (oldest !== void 0)
29445
+ host.typedRedriveBackoff.delete(oldest);
29446
+ }
29447
+ host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
29448
+ };
29449
+ const runLegacy = async () => {
29450
+ let acked2 = false;
29451
+ try {
29452
+ if (await run(ref.dispatchEventId)) {
29453
+ acked2 = settleAck(await ack(ref.dispatchEventId));
29770
29454
  }
29771
- } else if (this._state === "reconnecting") {
29772
- this.clearReconnect();
29773
- this.reconnectAttempts = 0;
29774
- this.connect();
29455
+ } finally {
29456
+ settle(acked2);
29775
29457
  }
29776
29458
  };
29777
- /** Network restored — accelerate reconnection. */
29778
- handleOnline = () => {
29779
- if (this.intentionalClose)
29459
+ if (!host.laneLedger || host.ledgerDisabled) {
29460
+ await runLegacy();
29461
+ return;
29462
+ }
29463
+ let lane;
29464
+ try {
29465
+ lane = await host.laneLedger.claimTyped(ref);
29466
+ } catch (err) {
29467
+ if (err instanceof LedgerUnsupportedError) {
29468
+ host.disableLedger("claim endpoint missing");
29469
+ await runLegacy();
29780
29470
  return;
29781
- if (this._state === "connected") {
29782
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29783
- this.forceReconnect();
29784
- } else {
29785
- this.probeConnection();
29786
- }
29787
- } else if (this._state === "reconnecting") {
29788
- this.clearReconnect();
29789
- this.reconnectAttempts = 0;
29790
- this.connect();
29791
29471
  }
29472
+ throw err;
29473
+ }
29474
+ if (!lane) {
29475
+ host.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} not claimable (held elsewhere or already resolved) \u2014 skipping`);
29476
+ return;
29477
+ }
29478
+ let acked = false;
29479
+ try {
29480
+ if (await run(lane.typedDispatchEventId)) {
29481
+ acked = settleAck(await ack(lane.typedDispatchEventId));
29482
+ }
29483
+ } finally {
29484
+ settle(acked);
29485
+ await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
29486
+ });
29487
+ }
29488
+ }
29489
+ async function consumeMessageWorkItem(host, item) {
29490
+ if (host.shuttingDown)
29491
+ return;
29492
+ if (!host.tryClaimMessage(item.source_id))
29493
+ return;
29494
+ const ackItem = () => {
29495
+ host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
29496
+ });
29792
29497
  };
29793
- setState(state) {
29794
- this._state = state;
29795
- for (const listener of this.stateListeners) {
29796
- listener(state);
29498
+ let msg = null;
29499
+ try {
29500
+ msg = await host.opts.client.getMessage(item.source_id);
29501
+ } catch (err) {
29502
+ const status = err?.status;
29503
+ if (status !== 404) {
29504
+ host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
29505
+ host.dispatchedMessages.delete(item.source_id);
29506
+ return;
29797
29507
  }
29798
29508
  }
29799
- };
29800
-
29801
- // ts/agent-core/dist/lane-ledger.js
29802
- import * as fs from "node:fs";
29803
- var LedgerUnsupportedError = class extends Error {
29804
- };
29805
- function isStaleLane(err) {
29806
- return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
29807
- }
29808
- function isEndpointMissing(err) {
29809
- return err instanceof ApiError && err.status === 404 && !err.code;
29810
- }
29811
- var LaneLedger = class {
29812
- opts;
29813
- lanes = /* @__PURE__ */ new Map();
29814
- constructor(opts) {
29815
- this.opts = opts;
29509
+ if (!msg || msg.sender_id === host.opts.agentUserId) {
29510
+ host.dispatchedMessages.delete(item.source_id);
29511
+ ackItem();
29512
+ return;
29816
29513
  }
29817
- get contextDir() {
29818
- return this.opts.contextDir;
29514
+ const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
29515
+ if (decision.action === "retry") {
29516
+ host.dispatchedMessages.delete(item.source_id);
29517
+ return;
29819
29518
  }
29820
- /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
29821
- handles(event) {
29822
- return event.type === "message" && event.targetId.startsWith("cht_");
29519
+ if (decision.action === "skip") {
29520
+ host.dispatchedMessages.delete(item.source_id);
29521
+ ackItem();
29522
+ return;
29823
29523
  }
29824
- laneKeyFor(event) {
29825
- if (event.type !== "message" && event.dispatchEventId) {
29826
- return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29524
+ decision.event.dispatchEventId = item.id;
29525
+ const laneResolved = host.usesLaneLedger(decision.event);
29526
+ try {
29527
+ const dispatched = await host.handleInboundEvent(decision.event);
29528
+ if (dispatched) {
29529
+ if (!laneResolved)
29530
+ ackItem();
29531
+ } else {
29532
+ host.dispatchedMessages.delete(item.source_id);
29827
29533
  }
29828
- return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29534
+ } catch (err) {
29535
+ host.dispatchedMessages.delete(item.source_id);
29536
+ throw err;
29829
29537
  }
29830
- getForEvent(event) {
29831
- return this.lanes.get(this.laneKeyFor(event));
29538
+ }
29539
+
29540
+ // ts/agent-core/dist/session-state.js
29541
+ function normalizeSessionKey(sessionKey) {
29542
+ return sessionKey.toLowerCase();
29543
+ }
29544
+ var sessionChatIdMap = /* @__PURE__ */ new Map();
29545
+ var sessionMessageIdMap = /* @__PURE__ */ new Map();
29546
+ var dispatchMessageIdMap = /* @__PURE__ */ new Map();
29547
+ var dispatchNoReplyMap = /* @__PURE__ */ new Map();
29548
+ function setSessionChatId(sessionKey, chatId) {
29549
+ sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
29550
+ }
29551
+ function setSessionMessageId(sessionKey, messageId) {
29552
+ sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29553
+ }
29554
+ function clearSessionMessageId(sessionKey) {
29555
+ sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
29556
+ }
29557
+ function setDispatchMessageId(sessionKey, messageId) {
29558
+ dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29559
+ }
29560
+ function clearDispatchMessageId(sessionKey) {
29561
+ dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
29562
+ }
29563
+ function setDispatchNoReply(sessionKey, noReply) {
29564
+ dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
29565
+ }
29566
+ function clearDispatchNoReply(sessionKey) {
29567
+ dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
29568
+ }
29569
+ var dispatchMetricsMap = /* @__PURE__ */ new Map();
29570
+ function resetDispatchMetrics(sessionKey) {
29571
+ dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
29572
+ deliver_text_chunks: 0,
29573
+ deliver_text_chars: 0,
29574
+ message_send_attempts: 0,
29575
+ message_send_successes: 0,
29576
+ no_reply_called: false,
29577
+ tool_call_count: 0,
29578
+ started_at: Date.now()
29579
+ });
29580
+ }
29581
+ function getDispatchMetrics(sessionKey) {
29582
+ return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29583
+ }
29584
+ function clearDispatchMetrics(sessionKey) {
29585
+ dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
29586
+ }
29587
+ function recordDeliverText(sessionKey, charCount) {
29588
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29589
+ if (!m)
29590
+ return;
29591
+ m.deliver_text_chunks++;
29592
+ m.deliver_text_chars += charCount;
29593
+ }
29594
+ function recordMessageSend(sessionKey, success) {
29595
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29596
+ if (!m)
29597
+ return;
29598
+ m.message_send_attempts++;
29599
+ if (success)
29600
+ m.message_send_successes++;
29601
+ }
29602
+ function recordNoReply(sessionKey) {
29603
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29604
+ if (!m)
29605
+ return;
29606
+ m.no_reply_called = true;
29607
+ }
29608
+ function recordToolCall(sessionKey) {
29609
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29610
+ if (!m)
29611
+ return;
29612
+ m.tool_call_count++;
29613
+ }
29614
+
29615
+ // ts/agent-core/dist/routing.js
29616
+ var MAX_CONCURRENT_FORKS = 20;
29617
+ var defaultRoutingStrategy = (event, state) => {
29618
+ if (state.mainCurrentTargetId === event.targetId) {
29619
+ return { action: "buffer-main" };
29832
29620
  }
29833
- laneContextPath(lane) {
29834
- return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29621
+ const existingForkKey = state.activeForks.get(event.targetId);
29622
+ if (existingForkKey)
29623
+ return { action: "buffer-fork", forkKey: existingForkKey };
29624
+ if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
29625
+ return { action: "buffer-main" };
29835
29626
  }
29836
- /**
29837
- * Claim (or reuse) the lane for a group of same-lane message events and
29838
- * fold every group member into it. Returns 'foreign' when a healthy
29839
- * incumbent (another pod) holds the resource — the caller must not
29840
- * dispatch; the events stay pending server-side and re-drive after the
29841
- * incumbent completes.
29842
- */
29843
- async ensureLane(events) {
29844
- const trigger = events[events.length - 1];
29845
- const laneKey = this.laneKeyFor(trigger);
29846
- let lane = this.lanes.get(laneKey);
29847
- if (!lane) {
29848
- const targetUri = `prll://${trigger.targetId}`;
29849
- let res;
29850
- try {
29851
- res = await this.opts.client.claimDispatch(this.opts.orgId, {
29852
- target_uri: targetUri,
29853
- thread_root_id: trigger.threadRootId,
29854
- limit: 100
29855
- });
29856
- } catch (err) {
29857
- if (isEndpointMissing(err))
29858
- throw new LedgerUnsupportedError("claim endpoint unavailable");
29859
- throw err;
29860
- }
29861
- if (!res.claimed || !res.lane) {
29862
- this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
29863
- return null;
29864
- }
29865
- const leaseUntilMs = Date.parse(res.lease_until ?? "");
29866
- lane = {
29867
- laneKey,
29868
- lane: res.lane,
29869
- targetUri,
29870
- threadRootId: trigger.threadRootId,
29871
- folded: /* @__PURE__ */ new Map(),
29872
- ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29873
- };
29874
- for (const ev of res.events ?? []) {
29875
- lane.folded.set(ev.source_id, ev.id);
29627
+ return { action: "new-fork" };
29628
+ };
29629
+ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
29630
+ const existingForkKey = state.activeForks.get(event.targetId);
29631
+ if (existingForkKey)
29632
+ return { action: "buffer-fork", forkKey: existingForkKey };
29633
+ if (!state.mainDispatching)
29634
+ return { action: "main" };
29635
+ return strategy(event, state);
29636
+ }
29637
+
29638
+ // ts/agent-core/dist/event-format.js
29639
+ function sanitizeMeta(value) {
29640
+ return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
29641
+ }
29642
+ function buildEventBody(event) {
29643
+ const lines = [];
29644
+ if (event.type === "message") {
29645
+ lines.push(`[Event: message.new]`);
29646
+ const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29647
+ lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
29648
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29649
+ lines.push(`[Message ID: prll://${event.messageId}]`);
29650
+ if (event.threadRootId) {
29651
+ const threadMeta = [
29652
+ `prll://${event.threadRootId}`,
29653
+ event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
29654
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
29655
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
29656
+ ].filter(Boolean).join(" | ");
29657
+ lines.push(`[Thread: ${threadMeta}]`);
29658
+ }
29659
+ if (event.unreadCount != null && event.unreadCount > 1) {
29660
+ const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
29661
+ const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
29662
+ let line = `[Unread: ${countStr} messages${sinceStr}]`;
29663
+ if (event.unreadCount > 50)
29664
+ line += ` \u2014 fetch recent context with --limit, not all`;
29665
+ lines.push(line);
29666
+ }
29667
+ if (event.noReply)
29668
+ lines.push(`[Hint: no_reply]`);
29669
+ if (event.attachments?.length) {
29670
+ for (const att of event.attachments) {
29671
+ const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
29672
+ lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
29876
29673
  }
29877
- this.lanes.set(laneKey, lane);
29878
29674
  }
29879
- for (const ev of events) {
29880
- if (lane.folded.has(ev.messageId))
29881
- continue;
29882
- try {
29883
- const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29884
- lane: lane.lane,
29885
- target_uri: lane.targetUri,
29886
- thread_root_id: lane.threadRootId,
29887
- ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
29888
- });
29889
- lane.folded.set(ev.messageId, res.dispatch_event_id);
29890
- } catch (err) {
29891
- if (isStaleLane(err)) {
29892
- this.lanes.delete(laneKey);
29893
- return null;
29894
- }
29895
- this.opts.log?.warn(`steer fold failed for ${ev.messageId} \u2014 failing closed, releasing lane: ${String(err)}`);
29896
- await this.release(laneKey);
29897
- return null;
29898
- }
29675
+ lines.push("", event.body);
29676
+ } else if (event.type === "task_comment") {
29677
+ lines.push(`[Event: task.comment.created]`);
29678
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29679
+ lines.push(`[Task: ${taskLabel}]`);
29680
+ if (event.deliveryReason)
29681
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29682
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29683
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29684
+ lines.push("", event.body);
29685
+ } else if (event.type === "wiki_comment") {
29686
+ lines.push(`[Event: wiki.comment.created]`);
29687
+ const target = event.replyTargetUri ?? `prll://${event.targetId}`;
29688
+ if (event.targetType === "changeset") {
29689
+ lines.push(`[Wiki Changeset: ${target}]`);
29690
+ } else {
29691
+ lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
29692
+ }
29693
+ if (event.deliveryReason)
29694
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29695
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29696
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29697
+ lines.push("", event.body);
29698
+ } else if (event.type === "approval") {
29699
+ lines.push(`[Event: approval.decided]`);
29700
+ lines.push(`[Approval: prll://${event.messageId}]`);
29701
+ lines.push(`[Chat: prll://${event.targetId}]`);
29702
+ lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
29703
+ lines.push("", event.body);
29704
+ } else if (event.type === "schedule") {
29705
+ lines.push(`[Event: schedule.fired]`);
29706
+ lines.push(`[Schedule: prll://${event.targetId}]`);
29707
+ lines.push(`[Run: prll://${event.messageId}]`);
29708
+ if (event.scheduledFireAt)
29709
+ lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
29710
+ if (event.attachedUri)
29711
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29712
+ lines.push("", event.body);
29713
+ } else if (event.type === "channel_message") {
29714
+ lines.push(`[Event: channel.message]`);
29715
+ const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
29716
+ const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
29717
+ lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
29718
+ lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
29719
+ if (event.channelExternalMessageId) {
29720
+ lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
29721
+ }
29722
+ lines.push(`[Audience: this conversation lives on ${providerLabel}, OUTSIDE Parall. Readers cannot open prll:// links, Parall cards, or internal attachments \u2014 never include them in replies. Write plain conversational text.]`);
29723
+ lines.push("", event.body);
29724
+ } else if (event.type === "external_trigger") {
29725
+ lines.push(`[Event: external.trigger]`);
29726
+ lines.push(`[Trigger: prll://${event.targetId}]`);
29727
+ lines.push(`[Run: prll://${event.messageId}]`);
29728
+ if (event.externalConnectionId) {
29729
+ const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
29730
+ lines.push(`[Connection: ${label}]`);
29899
29731
  }
29900
- return lane;
29901
- }
29902
- /**
29903
- * Fold a live mid-turn message into its active lane BEFORE injecting it
29904
- * into the running turn. Injection without a successful fold is forbidden —
29905
- * an un-folded injected message would be re-driven after complete and the
29906
- * model would handle it twice.
29907
- */
29908
- async steerLive(event) {
29909
- const laneKey = this.laneKeyFor(event);
29910
- const lane = this.lanes.get(laneKey);
29911
- if (!lane)
29912
- return false;
29913
- if (lane.folded.has(event.messageId))
29914
- return true;
29915
- try {
29916
- const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29917
- lane: lane.lane,
29918
- target_uri: lane.targetUri,
29919
- thread_root_id: lane.threadRootId,
29920
- ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
29921
- });
29922
- lane.folded.set(event.messageId, res.dispatch_event_id);
29923
- return true;
29924
- } catch (err) {
29925
- if (isStaleLane(err)) {
29926
- this.lanes.delete(laneKey);
29927
- } else {
29928
- this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
29929
- }
29930
- return false;
29732
+ if (event.externalIngressEventId)
29733
+ lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
29734
+ if (event.attachedUri)
29735
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29736
+ if (event.externalConnectionSourceType) {
29737
+ lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
29931
29738
  }
29932
- }
29933
- /**
29934
- * Complete the lane when no local work remains for it: the server sweeps
29935
- * still-leased members as no_action, releases the occupancy row, and
29936
- * re-drives any same-target pending work. A STALE_LANE answer means a
29937
- * takeover already owns the resource — local state is dropped either way.
29938
- */
29939
- async completeIfIdle(laneKey, hasMoreLocal) {
29940
- const lane = this.lanes.get(laneKey);
29941
- if (!lane || hasMoreLocal)
29942
- return;
29943
- this.lanes.delete(laneKey);
29944
- this.removeLaneContext(lane);
29945
- try {
29946
- const res = await this.opts.client.completeDispatch(this.opts.orgId, {
29947
- lane: lane.lane,
29948
- target_uri: lane.targetUri,
29949
- thread_root_id: lane.threadRootId
29950
- });
29951
- if (res.swept_no_action > 0 || res.redriven) {
29952
- this.opts.log?.info(`lane complete for ${lane.targetUri}: swept ${res.swept_no_action} no_action, redriven=${res.redriven}`);
29953
- }
29954
- } catch (err) {
29955
- if (isStaleLane(err)) {
29956
- this.opts.log?.info(`lane complete skipped for ${lane.targetUri} \u2014 taken over`);
29957
- return;
29958
- }
29959
- this.opts.log?.warn(`lane complete failed for ${lane.targetUri}: ${String(err)}`);
29739
+ if (event.externalIngressEventType) {
29740
+ lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
29960
29741
  }
29742
+ lines.push("", event.body);
29743
+ } else {
29744
+ lines.push(`[Event: task.assigned]`);
29745
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29746
+ lines.push(`[Task: ${taskLabel}]`);
29747
+ lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
29748
+ lines.push("", event.body);
29961
29749
  }
29962
- /**
29963
- * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
29964
- * so a chatty turn doesn't spam the server. Without this, a legitimately
29965
- * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
29966
- * write misfired with STALE_LANE — the design doc's "long turns renew via
29967
- * step writes". Fire-and-forget: a failed renewal is surfaced by the next
29968
- * write's incumbency check anyway.
29969
- */
29970
- maybeRenew(lane) {
29971
- const now = Date.now();
29972
- const ttl = lane.leaseTtlMs ?? 10 * 6e4;
29973
- const until = lane.leaseUntilMs ?? now;
29974
- if (until - now > ttl / 2)
29975
- return;
29976
- lane.leaseUntilMs = now + ttl;
29977
- void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
29978
- lane: lane.lane,
29979
- target_uri: lane.targetUri,
29980
- thread_root_id: lane.threadRootId
29981
- }).then((res) => {
29982
- const until2 = Date.parse(res?.lease_until ?? "");
29983
- if (!Number.isNaN(until2))
29984
- lane.leaseUntilMs = until2;
29985
- }).catch((err) => {
29986
- if (isStaleLane(err)) {
29987
- this.lanes.delete(lane.laneKey);
29988
- this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
29989
- return;
29990
- }
29991
- this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
29992
- });
29993
- }
29994
- /**
29995
- * Release a lane's unresolved members back to pending (dispatch error /
29996
- * shutdown) so the next pod re-claims immediately instead of waiting out
29997
- * the lease.
29998
- */
29999
- async release(laneKey) {
30000
- const lane = this.lanes.get(laneKey);
30001
- if (!lane)
30002
- return;
30003
- this.lanes.delete(laneKey);
30004
- this.removeLaneContext(lane);
30005
- try {
30006
- await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane);
30007
- } catch (err) {
30008
- this.opts.log?.warn(`lane release failed for ${lane.targetUri}: ${String(err)}`);
30009
- }
29750
+ return lines.join("\n") + buildSendMessageHint(event);
29751
+ }
29752
+ function buildEventBodyForForkResult(event) {
29753
+ return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
29754
+ }
29755
+ function buildSendMessageHint(event) {
29756
+ if (event.noReply)
29757
+ return "";
29758
+ if (event.type === "wiki_comment" && event.replyTargetUri) {
29759
+ const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
29760
+ return `
29761
+ <system-reminder>To reply on ${where}, run: \`parall comments add --target "${event.replyTargetUri}" --body "..."\` (read the thread first with \`parall comments list --target "${event.replyTargetUri}"\`). To message someone instead, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
30010
29762
  }
30011
- async releaseAll() {
30012
- const keys = [...this.lanes.keys()];
30013
- for (const key of keys) {
30014
- await this.release(key);
29763
+ if (event.targetId.startsWith("cht_")) {
29764
+ if (event.threadRootId) {
29765
+ return `
29766
+ <system-reminder>To reply in this thread, run \`parall messages send prll://${event.targetId} --thread-root-id ${sanitizeMeta(event.threadRootId)} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
30015
29767
  }
29768
+ return `
29769
+ <system-reminder>To reply, run \`parall messages send prll://${event.targetId} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
30016
29770
  }
30017
- /** True when any lane is currently active (used by shutdown logging). */
30018
- get activeCount() {
30019
- return this.lanes.size;
29771
+ if (event.targetId.startsWith("tsk_")) {
29772
+ return `
29773
+ <system-reminder>To respond, use the CLI: \`parall tasks update\` / \`parall tasks comments add\`. To message someone, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
30020
29774
  }
30021
- /**
30022
- * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
30023
- * by WorkItem id or by source identity (the live task.assigned event has no
30024
- * WorkItem id). Returns null when a healthy incumbent (another pod) holds
30025
- * it or the WorkItem is already resolved — the caller must skip processing.
30026
- */
30027
- async claimTyped(ref) {
30028
- let res;
30029
- try {
30030
- res = await this.opts.client.claimDispatch(this.opts.orgId, {
30031
- dispatch_event_id: ref.dispatchEventId,
30032
- source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
30033
- source_id: ref.dispatchEventId ? void 0 : ref.sourceId
30034
- });
30035
- } catch (err) {
30036
- if (isEndpointMissing(err))
30037
- throw new LedgerUnsupportedError("claim endpoint unavailable");
30038
- throw err;
30039
- }
30040
- if (!res.claimed || !res.lane || !res.events?.length)
30041
- return null;
30042
- const workItem = res.events[0];
30043
- const targetUri = `dsp:${workItem.id}`;
30044
- const leaseUntilMs = Date.parse(res.lease_until ?? "");
30045
- const lane = {
30046
- laneKey: laneKeyForTarget(targetUri),
30047
- lane: res.lane,
30048
- targetUri,
30049
- folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
30050
- typedDispatchEventId: workItem.id,
30051
- ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
30052
- };
30053
- this.lanes.set(lane.laneKey, lane);
30054
- return lane;
29775
+ if (event.targetId.startsWith("sch_")) {
29776
+ return `
29777
+ <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
30055
29778
  }
30056
- /**
30057
- * Remove the per-lane context file (and its CLI sidecar) when the lane
30058
- * ends. A leftover file would make a later cross-context send to the same
30059
- * target bind a dead lane token and misfire with STALE_LANE instead of
30060
- * taking the plain non-ledger path.
30061
- */
30062
- removeLaneContext(lane) {
30063
- const contextPath = this.laneContextPath(lane);
30064
- for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
30065
- try {
30066
- fs.rmSync(p, { force: true });
30067
- } catch {
30068
- }
29779
+ if (event.type === "channel_message") {
29780
+ if (event.channelCliCapable) {
29781
+ const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
29782
+ const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
29783
+ return `
29784
+ <system-reminder>To reply, use the official Feishu CLI on your PATH: send a message to ${convRef} with \`lark-cli im\` (see \`lark-cli im --help\` for send syntax; auth is provisioned automatically).${threadAlt} lark-cli is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
30069
29785
  }
29786
+ const platform = event.channelProvider ?? "the external platform";
29787
+ return `
29788
+ <system-reminder>This message arrived from ${platform}, but outbound replies are currently disabled for this org (no channel capability granted). Do NOT attempt to reply on the external platform. If action is needed, surface it inside Parall (\`parall messages send\` / \`parall dm\`). Your plain text output is not delivered anywhere.</system-reminder>`;
30070
29789
  }
30071
- };
29790
+ if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
29791
+ return `
29792
+ <system-reminder>This external trigger is incoming-only. Your plain text output is not sent back to the external provider. To communicate in Parall, use \`parall messages send\` / \`parall dm\`; provider-specific outbound actions require a separate capability.</system-reminder>`;
29793
+ }
29794
+ return "";
29795
+ }
29796
+ function buildForkScopePrefix(event) {
29797
+ const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29798
+ return `[Fork scope: You are a parallel worker forked from the main session to handle ${targetLabel}. The conversation history above belongs to the main session's in-progress dispatch \u2014 do NOT continue it or complete it, or produce external output (comments, messages) for work visible there. The main session owns its own output.
29799
+
29800
+ Only act on the event below within your target scope. If your event reveals findings about the main session's work, report them in your summary \u2014 do not post them externally.
29801
+
29802
+ End with a brief "Fork summary" of actions taken and decisions made.]
29803
+
29804
+ `;
29805
+ }
29806
+ function buildForkResultPrefix(results) {
29807
+ if (!results.length)
29808
+ return "";
29809
+ const blocks = results.map((result) => {
29810
+ const lines = [];
29811
+ for (const body of result.eventBodies) {
29812
+ lines.push(body);
29813
+ }
29814
+ lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
29815
+ lines.push(`[Fork summary: ${result.agentSummary ? sanitizeMeta(result.agentSummary) : "No fork summary available \u2014 the fork completed without producing a text summary. Check the target chat/task for any actions the fork already took before acting."}]`);
29816
+ if (result.actions.length)
29817
+ lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
29818
+ if (result.historyPath)
29819
+ lines.push(`[Fork history: ${result.historyPath}]`);
29820
+ return lines.join("\n");
29821
+ });
29822
+ return blocks.join("\n\n") + "\n\n---\n\n";
29823
+ }
29824
+
29825
+ // ts/agent-core/dist/prompt-fragments.js
29826
+ var PRLL_IDENTITY_BASE = `## You on Parall
29827
+
29828
+ Parall is a shared workspace where humans and agents work side by side as equals.
29829
+ You are a participant here, not a service. You hold tasks, own decisions, and are
29830
+ accountable for the work you take on \u2014 the same way a human teammate is.
29831
+
29832
+ The people and agents around you are collaborators, not users to serve. Be honest,
29833
+ be direct, and care about the outcome of the work \u2014 not just the request in front
29834
+ of you.`;
29835
+ function sanitizeProfileField(value) {
29836
+ return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
29837
+ }
29838
+ function sanitizeProfileBlock(value) {
29839
+ return value.replace(/\r\n?/g, "\n").trim();
29840
+ }
29841
+ function buildIdentity(agent) {
29842
+ if (!agent)
29843
+ return PRLL_IDENTITY_BASE;
29844
+ const name = sanitizeProfileField(agent.displayName);
29845
+ const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
29846
+ lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
29847
+ if (agent.description) {
29848
+ const description = sanitizeProfileBlock(agent.description);
29849
+ if (description) {
29850
+ lines.push("", "### Your Agent Profile", "", description);
29851
+ }
29852
+ }
29853
+ lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
29854
+ return lines.join("\n");
29855
+ }
29856
+ var PRLL_BEHAVIOR = `## How to work here
29857
+
29858
+ ### Move work forward
29859
+ Don't wait for instructions. If you see the next step, take it. If something is
29860
+ ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
29861
+ \u2014 don't go silent. Initiative is expected.
29862
+
29863
+ Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
29864
+ requests, verifying something landed. When a thing needs future attention and
29865
+ nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
29866
+
29867
+ ### Work in the open
29868
+ Nothing you do exists until the system can see it. Your progress, decisions,
29869
+ blockers, and results need to live in tasks, comments, messages, or wiki pages
29870
+ \u2014 otherwise the organization is blind to your work, and so is the next agent
29871
+ who picks up where you left off. Leave traces as you go, not at the end.
29872
+
29873
+ For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
29874
+ when status materially changes, close it when done, and link the origin that
29875
+ triggered it. Decompose multi-step work into subtasks and keep their statuses
29876
+ current \u2014 progress should be auditable without watching the work happen.
29877
+ Details: load the \`parall-tasks\` skill.
29878
+
29879
+ ### Done means landed
29880
+ Producing output does not complete a task. Work counts as done only when it has
29881
+ cleared its remaining gates \u2014 review, merge, deployment, the requester's
29882
+ verification. Until then keep the status honest (\`in_progress\` or
29883
+ \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
29884
+ self-reminder if nothing else will prompt follow-up). Never mark done what a
29885
+ human still has to accept.
29886
+
29887
+ ### Sessions, forks, and what survives
29888
+ Sessions end and context compacts. Anything that must survive \u2014 decisions,
29889
+ progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
29890
+ read the workspace, not this conversation.
29891
+
29892
+ Some events are handled by parallel fork sessions \u2014 short-lived copies of the
29893
+ same agent identity with separate context. In a fork: leave a written trace of
29894
+ what was done or deliberately not done (other sessions cannot see fork
29895
+ context), and do not start long-running processes \u2014 they die with the fork.
29896
+ When an event is marked fork-handled: do not re-handle it; verify its outcome
29897
+ instead of assuming it.
29898
+
29899
+ ### Communicate like a teammate
29900
+ Match the conversation \u2014 concise in chat, thorough in docs, plain language over
29901
+ jargon. Say what matters; stop when you're done. Don't narrate every tool call
29902
+ or pad replies to seem thorough.
29903
+
29904
+ Match the language of the person you're replying to. If someone writes in
29905
+ Chinese, reply in Chinese. If in English, reply in English. Never force a
29906
+ language switch unless explicitly asked.
29907
+
29908
+ Do not promise delivery times ("in an hour", "by tonight") unless the work is
29909
+ driven by an explicit schedule. Scope visibly; report when actually done.
29910
+
29911
+ ### Keep topics in threads
29912
+ Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
29913
+ Present \u2192 that thread is the context; reply there, passing the same root as
29914
+ \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
29915
+ never treat it as continuing your most recent thread. The sender's newest
29916
+ message is the anchor \u2014 never route a reply back into an older thread just
29917
+ because the topic used to live there.
29918
+
29919
+ Reply where the event lives: a thread message gets a thread reply, a
29920
+ top-level message gets a top-level reply. But in group chats, your later
29921
+ follow-up on that topic \u2014 progress updates, analysis, links, verification you
29922
+ post afterwards \u2014 belongs in a thread rooted at the topic's message
29923
+ (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
29924
+ the main channel stays scannable. Post follow-up at top level only when
29925
+ starting a genuinely new topic, making a channel-wide announcement, or when
29926
+ explicitly asked. Never post the same update in both the thread and the main
29927
+ channel \u2014 thread replies surface in the thread panel; no need to duplicate
29928
+ for visibility.
29929
+
29930
+ In DMs, reply top-level by default; use a thread only to continue one that
29931
+ already exists.
29932
+
29933
+ ### Group chats: mentions and unaddressed work
29934
+ An @mention is a direct request \u2014 act on it. A group message delivered to you
29935
+ without an @mention means the chat's routing lets you see the conversation:
29936
+ decide whether a reply adds value; silence is the default.
29937
+
29938
+ A message without an @mention is not an open invitation. Judge from context
29939
+ who the work belongs to \u2014 the named domain, the topic's owner, whoever is
29940
+ already on it. If it belongs to someone else, leave it. If genuinely unclear,
29941
+ ask or claim in one line ("taking this unless someone else has it") before
29942
+ starting \u2014 asking first beats duplicated or misdirected work.
29943
+
29944
+ ### Verify before you act
29945
+ Events can be redelivered \u2014 before acting, check whether it was already
29946
+ handled (your own recent replies, task comments); if handled, do nothing.
29947
+ Sends can fail silently, and creates can error after succeeding server-side \u2014
29948
+ check the chat or entity before retrying. Never blind-retry a mutating call.
29949
+
29950
+ ### Gather the full picture first
29951
+ When a request is vague, an entity may already exist, or work may already be
29952
+ underway \u2014 gather context before acting: search (\`parall search "..."\`),
29953
+ check existing tasks/chats/wiki, read the surrounding conversation. Act on the
29954
+ full picture, not the fragment that arrived in the event.
29955
+
29956
+ ### Report only work that ran
29957
+ If a scheduled job, scan, or tool call did not actually run \u2014 restarted
29958
+ session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
29959
+ or approximate results of work that did not execute.
29960
+
29961
+ ### Respect what's shared
29962
+ You have broad latitude inside your own work. But actions that are visible to
29963
+ others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
29964
+ wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
29965
+ acting, unless you've been explicitly authorized.
29966
+
29967
+ ### Shared workspace
29968
+ Other agents share this workspace. Before starting work, check whether someone
29969
+ \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
29970
+
29971
+ ### Permissions and approvals
29972
+ You have real permissions based on your roles (chat member/admin, org member).
29973
+ If you lack permission for an action, the API returns PERMISSION_DENIED with the
29974
+ \`action\` and \`resource_uri\` that were denied. The server decides whether that
29975
+ action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
29976
+ fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
29977
+ it to ask someone with permission. If it is NOT approvable, the output says so;
29978
+ ask a human with permission instead of requesting approval. A
29979
+ \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
29980
+ (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
29981
+ \`dm\` for a user). Don't retry or work around a denial; only request approval
29982
+ after an actual denial, never preemptively.
29983
+
29984
+ ### When in doubt
29985
+ Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
29986
+ credibility is what you bring to the workspace \u2014 protect it.`;
29987
+ var PRLL_REFERENCE_GUIDE = `## Parall References
29988
+
29989
+ Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
29990
+ entities when you create or update tasks, comments, messages, and wiki files.
29991
+
29992
+ All three forms work \u2014 pick whichever fits:
29993
+
29994
+ prll://tsk_abc bare URI (auto-linked)
29995
+ [](prll://tsk_abc) empty context (renders resolved title)
29996
+ [relevant context](prll://tsk_abc) with author annotation
29997
+
29998
+ Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
29999
+ resolves and renders the entity title automatically.
30000
+
30001
+ ### URI format
30002
+
30003
+ \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
30004
+
30005
+ **Entities** \u2014 the entity ID is the authority:
30006
+
30007
+ prll://usr_xxx user prll://prj_xxx project
30008
+ prll://tsk_xxx task prll://wik_xxx wiki
30009
+ prll://msg_xxx message prll://cmt_xxx comment
30010
+ prll://cht_xxx chat prll://tcm_xxx task comment (legacy)
30011
+ prll://att_xxx attachment prll://ase_xxx agent session
30012
+ prll://sch_xxx schedule prll://srn_xxx schedule run
30013
+
30014
+ **Wiki** \u2014 path is file path, fragment is a typed anchor:
30015
+
30016
+ prll://wik_xxx/docs/guide.md file
30017
+ prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
30018
+ prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
30019
+
30020
+ Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
30021
+ Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
30022
+
30023
+ **Chat message range**:
30024
+
30025
+ prll://cht_xxx#range=msg_01HA,msg_01HZ
30026
+
30027
+ **Field access** \u2014 path selects a field (omit to reference the entity itself):
30028
+
30029
+ prll://tsk_xxx/description#Implementation heading within task description
30030
+
30031
+ ### Unread context
30032
+
30033
+ When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
30034
+ This shows messages since your last interaction \u2014 your read cursor advances after each
30035
+ dispatch, so context you skip now won't appear as unread next time. Use
30036
+ \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
30037
+ counts (50+), fetch only recent messages rather than everything.
30038
+
30039
+ Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
30040
+ Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
30041
+ catch up on the thread.
30042
+
30043
+ ### Reading context on demand
30044
+
30045
+ An event only carries the single triggering message. If you're mentioned in a
30046
+ group chat and lack context, pull what you need from the chat \u2014 don't guess:
30072
30047
 
30073
- // ts/agent-core/dist/gateway-lane-flow.js
30074
- async function dispatchLaneGroup(host, opts) {
30075
- const ledger = host.laneLedger;
30076
- const event = opts.events[opts.events.length - 1];
30077
- let lane;
30078
- try {
30079
- lane = await ledger.ensureLane(opts.events);
30080
- } catch (err) {
30081
- if (!(err instanceof LedgerUnsupportedError))
30082
- throw err;
30083
- host.disableLedger("claim endpoint missing");
30084
- await host.emitDispatchReceived(event);
30085
- const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
30086
- if (!dispatched2)
30087
- return "shutdown";
30088
- for (const ev of opts.events) {
30089
- host.opts.client.ackDispatch(host.opts.config.org_id, {
30090
- source_type: ev.ackSourceType ?? "message",
30091
- source_id: ev.ackSourceId ?? ev.messageId
30092
- }).catch(() => {
30093
- });
30094
- }
30095
- return "dispatched";
30096
- }
30097
- if (!lane) {
30098
- for (const ev of opts.events) {
30099
- host.dispatchedMessages.delete(ev.messageId);
30100
- }
30101
- return "foreign";
30102
- }
30103
- let dispatched = false;
30104
- try {
30105
- dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
30106
- } catch (err) {
30107
- await ledger.release(lane.laneKey).catch(() => {
30108
- });
30109
- throw err;
30110
- }
30111
- if (!dispatched) {
30112
- return "shutdown";
30048
+ parall messages list cht_xxx --limit 20 --before msg_xxx
30049
+ parall messages get msg_xxx
30050
+ parall chats get cht_xxx
30051
+
30052
+ Rule of thumb: in a group chat mention, the conversation that led up to you
30053
+ being called almost always matters \u2014 read it before replying. In a DM, your
30054
+ session already has continuity, so skip the fetch unless something is unclear.
30055
+
30056
+ Same pattern for any other entity referenced in the event: \`tasks get\`,
30057
+ \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
30058
+ When one entity isn't enough \u2014 you need what's *around* it \u2014 walk the
30059
+ reference graph instead of guessing (see "Walk the reference graph" below).
30060
+
30061
+ ### Find context with search first
30062
+
30063
+ Reach for unified semantic search before paging chat history:
30064
+
30065
+ parall search "pricing decision june" --limit 10
30066
+
30067
+ It spans messages, tasks, wiki, and comments. Page \`messages list\` only for the
30068
+ verbatim recent flow of one chat, not for discovery.
30069
+
30070
+ ### Walk the reference graph
30071
+
30072
+ References form a traversable graph, and you can query it \u2014 don't stop at
30073
+ fetching entities one by one:
30074
+
30075
+ # entity metadata (title, status, preview)
30076
+ parall refs resolve prll://tsk_xxx prll://wik_xxx
30077
+ # who references this entity
30078
+ parall refs backlinks prll://tsk_xxx
30079
+ # connected sub-graph around it
30080
+ parall refs graph prll://tsk_xxx --depth 2
30081
+
30082
+ Use \`refs backlinks\` when you need "where is this discussed / used"; use
30083
+ \`refs graph\` when you need the full picture around an entity (related tasks,
30084
+ docs, conversations \u2014 edges carry the author's annotation for why they linked).
30085
+ Then \`refs resolve\` the interesting node URIs in one batch to get titles and
30086
+ status. \`refs graph\` takes entity-level URIs only (\`prll://wik_xxx\`, not
30087
+ \`prll://wik_xxx/docs/a.md\`). All results are filtered to what you can see.
30088
+ Details: parall-platform skill.
30089
+
30090
+ ### File attachments
30091
+
30092
+ Messages may include attachments. They appear in events as:
30093
+
30094
+ [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
30095
+
30096
+ To download an attachment, use the CLI:
30097
+
30098
+ parall files download att_xxx --output /tmp/screenshot.png
30099
+
30100
+ To send a file:
30101
+
30102
+ parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
30103
+
30104
+ Or upload first and reuse across chats:
30105
+
30106
+ parall files upload /tmp/report.pdf
30107
+ parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
30108
+ parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
30109
+
30110
+ The \`--text\` captions above are safe short literals. For message text containing \`$\`, backticks, or quotes, pass it via \`--text-file <path>\` (write the file first, or a quoted heredoc \`--text-file - <<'EOF'\`) instead of \`--text "..."\` \u2014 inside double quotes the shell turns \`$1,000\` into \`,000\` and executes \`$(...)\`.
30111
+
30112
+ ### When to reference
30113
+
30114
+ - **Origin** \u2014 always link the message or task that triggered your work
30115
+ - **Design docs / wiki** \u2014 link specs and guides relevant to the work
30116
+ - **Related tasks** \u2014 link parent, sibling, or blocking tasks
30117
+ - **People** \u2014 link assignees or stakeholders when mentioning them
30118
+ - **Conversations** \u2014 link a chat or message range as context
30119
+
30120
+ ### Why this matters
30121
+
30122
+ Other agents and humans read your output. References build a navigable context graph \u2014
30123
+ in multi-agent workflows, your references are the map that the next agent follows.`;
30124
+ function renderLocalAttachmentSection(section) {
30125
+ if (section.images.length === 0 && section.notes.length === 0)
30126
+ return "";
30127
+ const lines = ["[Local attachment files]"];
30128
+ for (const image of section.images) {
30129
+ lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
30113
30130
  }
30114
- const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
30115
- await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
30116
- return "dispatched";
30131
+ lines.push(...section.notes);
30132
+ return lines.join("\n");
30117
30133
  }
30118
- async function consumeTypedDispatch(host, ref, run, ack) {
30119
- if (!host.laneLedger || host.ledgerDisabled) {
30120
- if (await run(ref.dispatchEventId))
30121
- ack(ref.dispatchEventId);
30122
- return;
30123
- }
30124
- let lane;
30125
- try {
30126
- lane = await host.laneLedger.claimTyped(ref);
30127
- } catch (err) {
30128
- if (err instanceof LedgerUnsupportedError) {
30129
- host.disableLedger("claim endpoint missing");
30130
- if (await run(ref.dispatchEventId))
30131
- ack(ref.dispatchEventId);
30132
- return;
30133
- }
30134
- throw err;
30135
- }
30136
- if (!lane) {
30137
- host.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} not claimable (held elsewhere or already resolved) \u2014 skipping`);
30138
- return;
30139
- }
30140
- try {
30141
- if (await run(lane.typedDispatchEventId))
30142
- ack(lane.typedDispatchEventId);
30143
- } finally {
30144
- await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
30145
- });
30146
- }
30134
+ function sanitizePromptMeta(value) {
30135
+ return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
30147
30136
  }
30148
- async function consumeMessageWorkItem(host, item) {
30149
- if (host.shuttingDown)
30150
- return;
30151
- if (!host.tryClaimMessage(item.source_id))
30152
- return;
30153
- const ackItem = () => {
30154
- host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
30155
- });
30156
- };
30157
- let msg = null;
30158
- try {
30159
- msg = await host.opts.client.getMessage(item.source_id);
30160
- } catch (err) {
30161
- const status = err?.status;
30162
- if (status !== 404) {
30163
- host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
30164
- host.dispatchedMessages.delete(item.source_id);
30165
- return;
30166
- }
30167
- }
30168
- if (!msg || msg.sender_id === host.opts.agentUserId) {
30169
- host.dispatchedMessages.delete(item.source_id);
30170
- ackItem();
30171
- return;
30172
- }
30173
- const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
30174
- if (decision.action === "retry") {
30175
- host.dispatchedMessages.delete(item.source_id);
30176
- return;
30177
- }
30178
- if (decision.action === "skip") {
30179
- host.dispatchedMessages.delete(item.source_id);
30180
- ackItem();
30181
- return;
30182
- }
30183
- decision.event.dispatchEventId = item.id;
30184
- const laneResolved = host.usesLaneLedger(decision.event);
30185
- try {
30186
- const dispatched = await host.handleInboundEvent(decision.event);
30187
- if (dispatched) {
30188
- if (!laneResolved)
30189
- ackItem();
30190
- } else {
30191
- host.dispatchedMessages.delete(item.source_id);
30192
- }
30193
- } catch (err) {
30194
- host.dispatchedMessages.delete(item.source_id);
30195
- throw err;
30137
+ function formatBytes(bytes) {
30138
+ if (bytes >= 1048576)
30139
+ return `${(bytes / 1048576).toFixed(1)}MB`;
30140
+ if (bytes >= 1024)
30141
+ return `${Math.round(bytes / 1024)}KB`;
30142
+ return `${bytes}B`;
30143
+ }
30144
+
30145
+ // ts/agent-core/dist/bridge-workspace.js
30146
+ var BRIDGE_WORKSPACE_INSTRUCTIONS = `# Agent workspace
30147
+
30148
+ You are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.
30149
+
30150
+ ## Message Model
30151
+
30152
+ Incoming events are rendered as structured \`[Event: ...]\` blocks.
30153
+ Each event includes \`[Chat: ... (prll://cht_xxx)]\` \u2014 use that chat ID (or full URI) when replying.
30154
+
30155
+ **Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.
30156
+ To say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.
30157
+
30158
+ ## Parall CLI
30159
+
30160
+ All outbound interactions go through the \`parall\` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If \`parall\` is not on PATH, use \`npx --yes @parall/cli@latest\` instead.
30161
+
30162
+ - \`parall messages send prll://cht_xxx --text-file -\` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)
30163
+ - \`parall dm prll://usr_xxx --text-file - [--no-reply]\` \u2014 direct message another user
30164
+ - \`parall tasks update prll://tsk_xxx --status in_progress\` \u2014 task state
30165
+ - \`parall no-reply [--reason "..."]\` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)
30166
+
30167
+ **Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands \`$\`, backticks, and \`$(...)\` inside \`"..."\` before the CLI sees them: \`--text "That costs $1,000"\` sends \`That costs ,000\`, and \`--text "$(cmd)"\` executes \`cmd\`. Pass message bodies via \`--text-file <path>\` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:
30168
+
30169
+ \`\`\`bash
30170
+ parall messages send prll://cht_xxx --text-file - <<'EOF'
30171
+ That costs $1,000, and $(whoami) stays literal. I'm on it.
30172
+ EOF
30173
+ \`\`\`
30174
+
30175
+ Keep \`--text "..."\` for short literals with no \`$\`, backtick, or apostrophe.
30176
+
30177
+ The bridge injects Parall context via environment variables. The static credentials \`PRLL_API_URL\`, \`PRLL_API_KEY\`, and \`PRLL_ORG_ID\` are always set. \`PRLL_CONTEXT_FILE\` points to a per-session JSON file that the gateway updates each dispatch with \`session_id\`, \`chat_id\`, \`trigger_message_id\`, \`no_reply\`, and \`step_id\` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass \`--chat\` or \`--session\` explicitly when the context file is present.
30178
+
30179
+ CLI errors are agent-readable \u2014 read them; they usually name the next step.
30180
+
30181
+ ## Attachments
30182
+
30183
+ Image attachments are pre-downloaded under \`.parall/attachments/<messageId>/\`. Each event's \`[Local attachment files]\` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.
30184
+
30185
+ Supported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with \`parall files download att_xxx --output ...\`.
30186
+
30187
+ ## Guardrails
30188
+
30189
+ - A dispatch may coalesce multiple events. Decide per event whether to reply via \`messages send\` / \`dm\` \u2014 events you do not act on simply receive no reply.
30190
+ - If an event carries \`[Hint: no_reply]\`, do not send anything for that event. \`no-reply\` is optional and only useful as an explicit intent marker.
30191
+ - Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.
30192
+ - Keep CLI replies concise and task-focused.
30193
+
30194
+ See \`docs/engineering-design/agent-dm-loop-prevention.md\` \xA7 Layer 0 for why plain text is never auto-projected.
30195
+
30196
+ ## Approval Flow
30197
+
30198
+ When you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:
30199
+
30200
+ 1. The error includes a \`PERMISSION_DENIED\` code plus the denied \`action\` and \`resource_uri\`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a \`Request approval:\` line with an approval command is printed \u2014 fill in its \`--chat\`, \`--title\`, \`--reason\` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.
30201
+ 2. Request approval: \`parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"\`
30202
+ 3. A card will appear in the specified chat for someone with permission to approve
30203
+ 4. Check the result: \`parall approvals get prll://<id>\` or wait: \`parall approvals wait prll://<id> --timeout 300\`
30204
+ 5. List available actions: \`parall approvals actions\`
30205
+
30206
+ Only request approval when you've actually been denied permission. Don't request approval preemptively.
30207
+ `;
30208
+ function extractShellCommand(input) {
30209
+ if (!input || typeof input !== "object")
30210
+ return void 0;
30211
+ const command = input.command;
30212
+ return typeof command === "string" && command.trim() ? command.trim() : void 0;
30213
+ }
30214
+ function parseParallCliInvocation(command) {
30215
+ const tokens = command.replace(/\s+/g, " ").trim().split(" ");
30216
+ let i = 0;
30217
+ if (tokens[i] === "parall") {
30218
+ i++;
30219
+ } else if (tokens[i] === "npx") {
30220
+ i++;
30221
+ while (i < tokens.length && tokens[i].startsWith("-"))
30222
+ i++;
30223
+ if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
30224
+ return null;
30225
+ i++;
30226
+ } else if (tokens[i] === "pnpm") {
30227
+ i++;
30228
+ if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
30229
+ i++;
30230
+ if (i >= tokens.length || tokens[i] !== "parall")
30231
+ return null;
30232
+ i++;
30233
+ } else {
30234
+ return null;
30196
30235
  }
30236
+ return tokens.slice(i).filter((t) => !t.startsWith("-"));
30237
+ }
30238
+ function isParallSendCommand(command) {
30239
+ if (!command)
30240
+ return false;
30241
+ const sub = parseParallCliInvocation(command);
30242
+ if (!sub || sub.length === 0)
30243
+ return false;
30244
+ return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
30245
+ }
30246
+ function isParallNoReplyCommand(command) {
30247
+ if (!command)
30248
+ return false;
30249
+ const sub = parseParallCliInvocation(command);
30250
+ return sub?.[0] === "no-reply";
30251
+ }
30252
+
30253
+ // ts/agent-core/dist/dispatch-adapter.js
30254
+ function buildErrorStepContent(message) {
30255
+ return { text: message, suppressed: false, status: "error" };
30256
+ }
30257
+
30258
+ // ts/agent-core/dist/logger.js
30259
+ function createLogger(prefix) {
30260
+ return {
30261
+ info: (msg) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30262
+ warn: (msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30263
+ error: (msg) => console.error(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30264
+ child: (sub) => createLogger(`${prefix}:${sub}`)
30265
+ };
30266
+ }
30267
+ function childLogger(logger, sub) {
30268
+ return logger.child ? logger.child(sub) : logger;
30197
30269
  }
30198
30270
 
30271
+ // ts/agent-core/dist/gateway-base.js
30272
+ import * as os from "node:os";
30273
+ import * as fs2 from "node:fs";
30274
+ import * as path2 from "node:path";
30275
+
30199
30276
  // ts/agent-core/dist/telemetry.js
30200
30277
  init_esm();
30201
30278
  var import_api_logs = __toESM(require_src(), 1);
@@ -30476,6 +30553,9 @@ var ParallAgentGateway = class {
30476
30553
  // (stable mapping; avoids one connection fetch per inbound message).
30477
30554
  channelConnectionProviders = /* @__PURE__ */ new Map();
30478
30555
  dispatchedMessages = /* @__PURE__ */ new Set();
30556
+ // Per-WorkItem failure backoff for typed dispatch consumption — see
30557
+ // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
30558
+ typedRedriveBackoff = /* @__PURE__ */ new Map();
30479
30559
  forkStates = /* @__PURE__ */ new Map();
30480
30560
  dispatchState = {
30481
30561
  mainDispatching: false,
@@ -30593,14 +30673,17 @@ var ParallAgentGateway = class {
30593
30673
  try {
30594
30674
  await this.consumeTypedDispatch(data.dispatch_event_id ? { dispatchEventId: data.dispatch_event_id } : { sourceType: "task_activity", sourceId: data.id }, (dispatchEventId) => this.handleTaskAssignment(data, data.id, dispatchEventId), (dispatchEventId) => {
30595
30675
  if (dispatchEventId) {
30596
- this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).catch(() => {
30676
+ return this.ackDispatchEvent(dispatchEventId, () => {
30677
+ this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
30597
30678
  });
30598
- return;
30599
30679
  }
30600
- this.opts.client.ackDispatch(this.opts.config.org_id, {
30680
+ return this.opts.client.ackDispatch(this.opts.config.org_id, {
30601
30681
  source_type: "task_activity",
30602
30682
  source_id: data.id
30603
- }).catch(() => {
30683
+ }).then(() => true, (err) => {
30684
+ this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
30685
+ this.opts.log?.warn(`dispatch ack failed for task ${data.id}, releasing for re-drive: ${String(err)}`);
30686
+ return false;
30604
30687
  });
30605
30688
  });
30606
30689
  } catch (err) {
@@ -30608,14 +30691,19 @@ var ParallAgentGateway = class {
30608
30691
  }
30609
30692
  });
30610
30693
  ws.on("dispatch.new", async (data) => {
30611
- if (data.event_type === "task_comment") {
30694
+ if (data.event_type === "task_assign") {
30695
+ if (!data.task_id)
30696
+ return;
30697
+ try {
30698
+ await this.handleTaskAssignmentRedrive(data);
30699
+ } catch (err) {
30700
+ this.opts.log?.error(`task assignment re-drive failed for ${data.task_id}: ${String(err)}`);
30701
+ }
30702
+ } else if (data.event_type === "task_comment") {
30612
30703
  if (!data.source_id || !data.task_id)
30613
30704
  return;
30614
30705
  try {
30615
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.handleTaskComment(data.source_id, data.task_id ?? "", data.actor_id, data.delivery_reason), () => {
30616
- this.opts.client.ackDispatchByID(this.opts.config.org_id, data.id).catch(() => {
30617
- });
30618
- });
30706
+ await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.handleTaskComment(data.source_id, data.task_id ?? "", data.actor_id, data.delivery_reason), () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)));
30619
30707
  } catch (err) {
30620
30708
  this.opts.log?.error(`task comment dispatch failed for ${data.source_id}: ${String(err)}`);
30621
30709
  }
@@ -30623,10 +30711,7 @@ var ParallAgentGateway = class {
30623
30711
  if (!data.source_id)
30624
30712
  return;
30625
30713
  try {
30626
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.handleWikiComment(data.source_id, data.actor_id, data.delivery_reason), () => {
30627
- this.opts.client.ackDispatchByID(this.opts.config.org_id, data.id).catch(() => {
30628
- });
30629
- });
30714
+ await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.handleWikiComment(data.source_id, data.actor_id, data.delivery_reason), () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)));
30630
30715
  } catch (err) {
30631
30716
  this.opts.log?.error(`wiki comment dispatch failed for ${data.source_id}: ${String(err)}`);
30632
30717
  }
@@ -30637,10 +30722,7 @@ var ParallAgentGateway = class {
30637
30722
  await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleTaskDispatch(data.task_id ?? "", data.source_id ?? data.task_id ?? "", {
30638
30723
  allowCreator: true,
30639
30724
  dispatchEventId
30640
- }), () => {
30641
- this.opts.client.ackDispatchByID(this.opts.config.org_id, data.id).catch(() => {
30642
- });
30643
- });
30725
+ }), () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)));
30644
30726
  } catch (err) {
30645
30727
  this.opts.log?.error(`task update dispatch failed for ${data.task_id}: ${String(err)}`);
30646
30728
  }
@@ -30648,10 +30730,7 @@ var ParallAgentGateway = class {
30648
30730
  if (!data.source_id)
30649
30731
  return;
30650
30732
  try {
30651
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.fetchAndHandleScheduleFire(data.source_id, data.actor_id), () => {
30652
- this.opts.client.ackDispatchByID(this.opts.config.org_id, data.id).catch(() => {
30653
- });
30654
- });
30733
+ await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.fetchAndHandleScheduleFire(data.source_id, data.actor_id), () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)));
30655
30734
  } catch (err) {
30656
30735
  this.opts.log?.error(`schedule fire dispatch failed for ${data.source_id}: ${String(err)}`);
30657
30736
  }
@@ -30659,10 +30738,7 @@ var ParallAgentGateway = class {
30659
30738
  if (!data.source_id)
30660
30739
  return;
30661
30740
  try {
30662
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.fetchAndHandleExternalTriggerRun(data.source_id), () => {
30663
- this.opts.client.ackDispatchByID(this.opts.config.org_id, data.id).catch(() => {
30664
- });
30665
- });
30741
+ await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.fetchAndHandleExternalTriggerRun(data.source_id), () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)));
30666
30742
  } catch (err) {
30667
30743
  this.opts.log?.error(`external trigger dispatch failed for ${data.source_id}: ${String(err)}`);
30668
30744
  }
@@ -30670,10 +30746,7 @@ var ParallAgentGateway = class {
30670
30746
  if (!data.source_id)
30671
30747
  return;
30672
30748
  try {
30673
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.fetchAndHandleChannelMessage(data.source_id), () => {
30674
- this.opts.client.ackDispatchByID(this.opts.config.org_id, data.id).catch(() => {
30675
- });
30676
- });
30749
+ await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.fetchAndHandleChannelMessage(data.source_id), () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)));
30677
30750
  } catch (err) {
30678
30751
  this.opts.log?.error(`channel message dispatch failed for ${data.source_id}: ${String(err)}`);
30679
30752
  }
@@ -30681,10 +30754,7 @@ var ParallAgentGateway = class {
30681
30754
  if (!data.source_id)
30682
30755
  return;
30683
30756
  try {
30684
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.fetchAndHandleApprovalDecided(data.source_id, data.actor_id, data.chat_id ?? null), () => {
30685
- this.opts.client.ackDispatchByID(this.opts.config.org_id, data.id).catch(() => {
30686
- });
30687
- });
30757
+ await this.consumeTypedDispatch({ dispatchEventId: data.id }, () => this.fetchAndHandleApprovalDecided(data.source_id, data.actor_id, data.chat_id ?? null), () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)));
30688
30758
  } catch (err) {
30689
30759
  this.opts.log?.error(`approval decided dispatch failed for ${data.source_id}: ${String(err)}`);
30690
30760
  }
@@ -30694,7 +30764,7 @@ var ParallAgentGateway = class {
30694
30764
  } catch (err) {
30695
30765
  this.opts.log?.error(`message re-drive failed for ${data.source_id}: ${String(err)}`);
30696
30766
  }
30697
- } else if (data.event_type !== "message" && data.event_type !== "task_assign") {
30767
+ } else if (data.event_type !== "message") {
30698
30768
  this.opts.log?.info(`dispatch.new with unhandled event_type=${String(data.event_type)} (id=${data.id}) \u2014 no-op`);
30699
30769
  }
30700
30770
  });
@@ -30762,6 +30832,54 @@ var ParallAgentGateway = class {
30762
30832
  consumeTypedDispatch(ref, run, ack) {
30763
30833
  return consumeTypedDispatch(this.laneFlowHost(), ref, run, ack);
30764
30834
  }
30835
+ // Typed completion must wait until the administrative ack has either
30836
+ // committed or failed. Errors stay best-effort: a failed ack leaves the row
30837
+ // received, so Complete releases and re-drives it safely. The boolean
30838
+ // outcome feeds the typed-consume backoff — an ack that failed must count
30839
+ // as a failed consume, or an ack outage would clear the backoff entry and
30840
+ // let the release re-drive spin at wire speed.
30841
+ ackDispatchEvent(dispatchEventId, onFailure) {
30842
+ return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => true, (err) => {
30843
+ onFailure?.();
30844
+ this.opts.log?.warn(`dispatch ack failed for ${dispatchEventId}, releasing for re-drive: ${String(err)}`);
30845
+ return false;
30846
+ });
30847
+ }
30848
+ clearTypedDispatchDedupe(item) {
30849
+ switch (item.event_type) {
30850
+ case "task_assign":
30851
+ case "task_update":
30852
+ if (item.task_id) {
30853
+ const prefix = `${item.task_id}:`;
30854
+ for (const key of this.dispatchedTasks) {
30855
+ if (key.startsWith(prefix))
30856
+ this.dispatchedTasks.delete(key);
30857
+ }
30858
+ }
30859
+ break;
30860
+ case "task_comment":
30861
+ case "wiki_comment":
30862
+ if (item.source_id)
30863
+ this.dispatchedTasks.delete(`comment:${item.source_id}`);
30864
+ break;
30865
+ case "schedule.fire":
30866
+ if (item.source_id)
30867
+ this.dispatchedTasks.delete(`schedule_run:${item.source_id}`);
30868
+ break;
30869
+ case "external_trigger":
30870
+ if (item.source_id)
30871
+ this.dispatchedTasks.delete(`external_trigger_run:${item.source_id}`);
30872
+ break;
30873
+ case "channel_message":
30874
+ if (item.source_id)
30875
+ this.dispatchedMessages.delete(`channel_message:${item.source_id}`);
30876
+ break;
30877
+ case "approval_decided":
30878
+ if (item.source_id)
30879
+ this.dispatchedTasks.delete(`approval:${item.source_id}`);
30880
+ break;
30881
+ }
30882
+ }
30765
30883
  buildDispatchContext(event, sessionKey) {
30766
30884
  const binding = this.sessionBindings.get(sessionKey);
30767
30885
  return {
@@ -31728,6 +31846,17 @@ var ParallAgentGateway = class {
31728
31846
  chat_id: item.chat_id
31729
31847
  });
31730
31848
  }
31849
+ // A task assignment's first delivery rides task.assigned, but a typed lane
31850
+ // released without an effect is re-driven as dispatch.new. Reuse the exact
31851
+ // typed claim path used by catch-up so that recovery does not require a
31852
+ // runtime reconnect.
31853
+ async handleTaskAssignmentRedrive(item) {
31854
+ if (!item.task_id)
31855
+ return;
31856
+ await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
31857
+ dispatchEventId
31858
+ }), (dispatchEventId) => this.ackDispatchEvent(dispatchEventId ?? item.id, () => this.clearTypedDispatchDedupe(item)));
31859
+ }
31731
31860
  consumeMessageWorkItem(item) {
31732
31861
  return consumeMessageWorkItem(this.laneFlowHost(), item);
31733
31862
  }
@@ -32036,6 +32165,8 @@ var ParallAgentGateway = class {
32036
32165
  provider = void 0;
32037
32166
  }
32038
32167
  }
32168
+ const keys = this.opts.getCapabilityKeys?.() ?? [];
32169
+ const cliCapable = provider ? keys.includes(`${provider}-cli`) : keys.some((k) => k.endsWith("-cli"));
32039
32170
  const event = {
32040
32171
  type: "channel_message",
32041
32172
  targetId: conv.id,
@@ -32050,6 +32181,7 @@ var ParallAgentGateway = class {
32050
32181
  channelConversationType: conv.conversation_type || void 0,
32051
32182
  channelExternalConversationId: conv.external_conversation_id,
32052
32183
  channelExternalMessageId: msg.external_message_id,
32184
+ channelCliCapable: cliCapable,
32053
32185
  ackSourceType: "channel_message",
32054
32186
  ackSourceId: msg.id
32055
32187
  };
@@ -32193,10 +32325,7 @@ var ParallAgentGateway = class {
32193
32325
  }
32194
32326
  processed++;
32195
32327
  try {
32196
- const ackItem = () => {
32197
- this.opts.client.ackDispatchByID(this.opts.config.org_id, item.id).catch(() => {
32198
- });
32199
- };
32328
+ const ackItem = () => this.ackDispatchEvent(item.id, () => this.clearTypedDispatchDedupe(item));
32200
32329
  if (item.event_type === "task_assign" && item.task_id) {
32201
32330
  try {
32202
32331
  await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
@@ -32389,6 +32518,28 @@ ${fullSummary}` : fullSummary;
32389
32518
  // ts/agent-core/dist/platform-config.js
32390
32519
  import * as fs3 from "node:fs";
32391
32520
  import * as path3 from "node:path";
32521
+ function extractCapabilities(config) {
32522
+ const agents = config.agents ?? {};
32523
+ const raw = agents.capabilities;
32524
+ if (!Array.isArray(raw))
32525
+ return [];
32526
+ const out = [];
32527
+ for (const entry of raw) {
32528
+ if (typeof entry !== "object" || entry === null)
32529
+ continue;
32530
+ const e = entry;
32531
+ if (typeof e.key !== "string" || !e.key)
32532
+ continue;
32533
+ if (typeof e.fragment !== "string" || !e.fragment)
32534
+ continue;
32535
+ out.push({
32536
+ key: e.key,
32537
+ source: typeof e.source === "string" ? e.source : "",
32538
+ fragment: e.fragment
32539
+ });
32540
+ }
32541
+ return out;
32542
+ }
32392
32543
  function isPlatformManagedProfile(profile) {
32393
32544
  return profile?.machine_id != null || profile?.model_management === "platform";
32394
32545
  }
@@ -32512,13 +32663,96 @@ function createPlatformConfigManager(opts) {
32512
32663
  },
32513
32664
  rawConfig() {
32514
32665
  return currentRawConfig;
32666
+ },
32667
+ capabilities() {
32668
+ return currentRawConfig ? extractCapabilities(currentRawConfig) : [];
32515
32669
  }
32516
32670
  };
32517
32671
  }
32518
32672
 
32519
- // ts/agent-core/dist/skills/index.js
32673
+ // ts/agent-core/dist/channel-capability.js
32520
32674
  import * as fs4 from "node:fs";
32521
32675
  import * as path4 from "node:path";
32676
+ import { fileURLToPath } from "node:url";
32677
+ var CAPABILITY_FEISHU_CLI = "feishu-cli";
32678
+ var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
32679
+ function capabilityBinDir(stateDir) {
32680
+ return path4.join(stateDir, "bin");
32681
+ }
32682
+ function channelExecEntryPath() {
32683
+ const selfDir = path4.dirname(fileURLToPath(import.meta.url));
32684
+ const sibling = path4.join(selfDir, "parall-channel-exec.js");
32685
+ if (fs4.existsSync(sibling))
32686
+ return sibling;
32687
+ return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
32688
+ }
32689
+ function materializeChannelCapabilities(stateDir, capabilities, log2) {
32690
+ try {
32691
+ reconcileFeishuCli(stateDir, capabilities, log2);
32692
+ } catch (err) {
32693
+ log2?.warn(`channel capability materialization failed: ${String(err)}`);
32694
+ }
32695
+ }
32696
+ function reconcileFeishuCli(stateDir, capabilities, log2) {
32697
+ const binDir = capabilityBinDir(stateDir);
32698
+ const posixPath = path4.join(binDir, "lark-cli");
32699
+ const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
32700
+ const hadPointer = fs4.existsSync(posixPath);
32701
+ if (!granted && !hadPointer)
32702
+ return;
32703
+ fs4.mkdirSync(binDir, { recursive: true });
32704
+ const entry = channelExecEntryPath();
32705
+ const nodeExec = process.execPath;
32706
+ writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log2);
32707
+ writePointerIfChanged(path4.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log2);
32708
+ }
32709
+ function writePointerIfChanged(filePath, content, log2) {
32710
+ let existing = null;
32711
+ try {
32712
+ existing = fs4.readFileSync(filePath, "utf8");
32713
+ } catch {
32714
+ existing = null;
32715
+ }
32716
+ if (existing !== content) {
32717
+ fs4.writeFileSync(filePath, content, { mode: 493 });
32718
+ log2?.info(`channel capability: pointer materialized (${path4.basename(filePath)})`);
32719
+ }
32720
+ fs4.chmodSync(filePath, 493);
32721
+ }
32722
+ function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
32723
+ return [
32724
+ "#!/bin/sh",
32725
+ `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32726
+ "# Credential + exec logic lives in the agent-core package; revocation is",
32727
+ "# enforced by the platform mint endpoint, so this pointer stays constant.",
32728
+ // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
32729
+ // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
32730
+ // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
32731
+ // the mint. The pointer is a platform-authored trust-boundary artifact whose
32732
+ // whole job is a CONTROLLED launch of the broker (absolute node, magic
32733
+ // guard, skip-dir); this closes the same env-hijack class for node startup
32734
+ // that the absolute node path closes for PATH, keeping the launch deterministic.
32735
+ "unset NODE_OPTIONS NODE_PATH",
32736
+ // "$@" preserves argv exactly (this is the agent's main path via git-bash).
32737
+ `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
32738
+ ""
32739
+ ].join("\n");
32740
+ }
32741
+ function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
32742
+ return [
32743
+ "@echo off",
32744
+ `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32745
+ // Clear Node preload-hijack vars before launching node (see the sh pointer).
32746
+ 'set "NODE_OPTIONS="',
32747
+ 'set "NODE_PATH="',
32748
+ `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
32749
+ ""
32750
+ ].join("\r\n");
32751
+ }
32752
+
32753
+ // ts/agent-core/dist/skills/index.js
32754
+ import * as fs5 from "node:fs";
32755
+ import * as path5 from "node:path";
32522
32756
 
32523
32757
  // ts/agent-core/dist/skills/parall-platform.js
32524
32758
  var PARALL_PLATFORM_SKILL = `# Parall Platform
@@ -32599,11 +32833,11 @@ settled questions or repeat known mistakes. This searches live org data
32599
32833
  can see.
32600
32834
 
32601
32835
  \`\`\`bash
32602
- # Semantic + keyword search across messages, tasks, and wiki
32836
+ # Semantic + keyword search across messages, tasks, wiki, and comments
32603
32837
  parall search "auth v5 upgrade"
32604
32838
 
32605
- # Restrict entity types (m=message, t=task, w=wiki). --channel narrows the
32606
- # MESSAGE hits to one chat (tasks/wiki are unaffected by it).
32839
+ # Restrict entity types (m=message, t=task, w=wiki, c=comment). --channel
32840
+ # narrows the MESSAGE hits to one chat (tasks/wiki/comments are unaffected).
32607
32841
  parall search "auth v5 upgrade" --types m,w --channel prll://cht_eng
32608
32842
 
32609
32843
  # Time-box to recent activity (RFC3339 or YYYY-MM-DD). Narrows messages + tasks;
@@ -32724,6 +32958,8 @@ Every entity is addressable with a \`prll://\` URI. Common prefixes you'll see i
32724
32958
  | \`prll://usr_\` | User (human or agent) | parall-platform |
32725
32959
  | \`prll://cht_\` | Chat | parall-platform |
32726
32960
  | \`prll://msg_\` | Message | parall-platform |
32961
+ | \`prll://cmt_\` | Comment (on tasks, wiki pages, changesets) | by target: task comment \u2192 parall-tasks, wiki/changeset comment \u2192 parall-wiki |
32962
+ | \`prll://ase_\` | Agent session | parall-platform |
32727
32963
  | \`prll://tsk_\` | Task | parall-tasks |
32728
32964
  | \`prll://prj_\` | Project | parall-tasks |
32729
32965
  | \`prll://sch_\` | Schedule (time trigger) | parall-schedules |
@@ -32759,7 +32995,24 @@ parall refs graph prll://tsk_xxx --depth 2
32759
32995
 
32760
32996
  \`refs graph\` traverses both directions (inbound + outbound) and returns \`nodes\`
32761
32997
  and \`edges\` with each node's hop \`depth\`. \`truncated: true\` means a size cap clipped
32762
- the result \u2014 narrow it with a smaller \`--depth\`.
32998
+ the result \u2014 narrow it with a smaller \`--depth\`. Edges carry \`context\` \u2014 the
32999
+ author's annotation from \`[context](prll://...)\` \u2014 telling you *why* two
33000
+ entities are linked, not just that they are.
33001
+
33002
+ The graph returns bare node URIs (no titles). The usual two-step: \`refs graph\`
33003
+ for topology, then batch-\`refs resolve\` the node URIs you care about for
33004
+ titles/status. If graph rejects your URI with a path/anchor error, strip it to
33005
+ the entity root (\`prll://wik_xxx/docs/a.md\` \u2192 \`prll://wik_xxx\`) and re-query \u2014
33006
+ but note this WIDENS the query to the whole entity, not that one file: the
33007
+ graph seeds from the wiki id, so a specific file's outbound links may sit
33008
+ deeper in the result (or past the size caps). For refs pointing AT one file
33009
+ (inbound), \`refs backlinks\` on the full file URI is precise. There is no
33010
+ precise query for one file's OUTBOUND edges today \u2014 the widened root graph is
33011
+ best-effort for those, or read the file itself for its \`prll://\` links.
33012
+ Wiki-file nodes inside a graph *result* do legitimately carry paths.
33013
+
33014
+ \`refs backlinks\` items include a \`snippet\` of the referencing content \u2014 often
33015
+ enough to judge relevance without fetching the source entity.
32763
33016
 
32764
33017
  CLI success output is JSON. Errors print a JSON line (\`{"error","status","code",...}\`) and, on a \`PERMISSION_DENIED\`, may add a plain-text \`Request approval:\` line \u2014 read both.
32765
33018
  `;
@@ -33273,7 +33526,7 @@ Results are JSON on stdout; failures print an error.
33273
33526
  var SKILLS = [
33274
33527
  {
33275
33528
  name: "parall-platform",
33276
- description: "Parall platform queries and lightweight agent provisioning: list org members, agents, chats, read message history, check identity, or create another agent. Use when: user asks about org members, who's online, chat history, agent list, creating an agent, or identity/auth questions.",
33529
+ description: "Parall platform queries and lightweight agent provisioning: list org members, agents, chats, read message history, check identity, create another agent, or walk the prll:// reference graph (resolve URIs, backlinks, multi-hop graph). Use when: user asks about org members, who's online, chat history, agent list, creating an agent, identity/auth questions, or you need to find what an entity is connected to / who references it.",
33277
33530
  content: PARALL_PLATFORM_SKILL
33278
33531
  },
33279
33532
  {
@@ -33303,13 +33556,13 @@ var SKILLS = [
33303
33556
  }
33304
33557
  ];
33305
33558
  function writeSkillFiles(targetDir) {
33306
- fs4.mkdirSync(targetDir, { recursive: true });
33559
+ fs5.mkdirSync(targetDir, { recursive: true });
33307
33560
  for (const skill of SKILLS) {
33308
- fs4.writeFileSync(path4.join(targetDir, `${skill.name}.md`), skill.content, "utf8");
33561
+ fs5.writeFileSync(path5.join(targetDir, `${skill.name}.md`), skill.content, "utf8");
33309
33562
  }
33310
33563
  }
33311
33564
  function buildSkillReferences(workspaceDir) {
33312
- const dir = path4.join(workspaceDir, ".parall", "skills");
33565
+ const dir = path5.join(workspaceDir, ".parall", "skills");
33313
33566
  const lines = SKILLS.map((s) => `- ${s.description.split(":")[0]}: \`${dir}/${s.name}.md\``);
33314
33567
  return `## Platform Skills (read on demand)
33315
33568
 
@@ -33319,7 +33572,7 @@ ${lines.join("\n")}
33319
33572
 
33320
33573
  // ts/codex-agent/dist/config.js
33321
33574
  import * as os2 from "node:os";
33322
- import * as path5 from "node:path";
33575
+ import * as path6 from "node:path";
33323
33576
  function requireEnv(env, name) {
33324
33577
  const value = env[name]?.trim();
33325
33578
  if (!value) {
@@ -33328,15 +33581,15 @@ function requireEnv(env, name) {
33328
33581
  return value;
33329
33582
  }
33330
33583
  function resolvePath(value) {
33331
- return path5.isAbsolute(value) ? value : path5.resolve(process.cwd(), value);
33584
+ return path6.isAbsolute(value) ? value : path6.resolve(process.cwd(), value);
33332
33585
  }
33333
33586
  function resolveCodexAgentConfig(env = process.env) {
33334
33587
  const apiUrl = requireEnv(env, "PRLL_API_URL");
33335
33588
  const apiKey = requireEnv(env, "PRLL_API_KEY");
33336
33589
  const orgId = requireEnv(env, "PRLL_ORG_ID");
33337
- const codexHome = resolvePath(env.PRLL_CODEX_HOME?.trim() || env.CODEX_HOME?.trim() || path5.join(env.HOME || os2.homedir(), ".codex"));
33338
- const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() || path5.join(env.HOME || os2.homedir(), ".parall-agent"));
33339
- const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() || path5.join(stateDir, "workspace"));
33590
+ const codexHome = resolvePath(env.PRLL_CODEX_HOME?.trim() || env.CODEX_HOME?.trim() || path6.join(env.HOME || os2.homedir(), ".codex"));
33591
+ const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() || path6.join(env.HOME || os2.homedir(), ".parall-agent"));
33592
+ const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() || path6.join(stateDir, "workspace"));
33340
33593
  return {
33341
33594
  apiUrl,
33342
33595
  apiKey,
@@ -33392,31 +33645,32 @@ function buildCodexRuntimeKey(agentUserId) {
33392
33645
  }
33393
33646
  function sessionStateFilePathForRuntime(stateDir, runtimeKey) {
33394
33647
  const fileName = Buffer.from(runtimeKey).toString("base64url");
33395
- return path5.join(stateDir, "threads", `${fileName}.json`);
33648
+ return path6.join(stateDir, "threads", `${fileName}.json`);
33396
33649
  }
33397
33650
  function contextFilePathForSession(stateDir, sessionKey) {
33398
33651
  const fileName = Buffer.from(sessionKey).toString("base64url");
33399
- return path5.join(stateDir, "dispatch-context", `${fileName}.json`);
33652
+ return path6.join(stateDir, "dispatch-context", `${fileName}.json`);
33400
33653
  }
33401
33654
  function dispatchContextDirPath(stateDir) {
33402
33655
  return dispatchLaneContextDir(stateDir);
33403
33656
  }
33404
33657
  function stepIdFilePathForSession(stateDir, sessionKey) {
33405
33658
  const fileName = Buffer.from(sessionKey).toString("base64url");
33406
- return path5.join(stateDir, "step-ids", `${fileName}.txt`);
33659
+ return path6.join(stateDir, "step-ids", `${fileName}.txt`);
33407
33660
  }
33408
33661
 
33409
33662
  // ts/codex-agent/dist/dispatch.js
33410
33663
  import { execSync as execSync2, spawn } from "node:child_process";
33411
33664
  import { randomUUID } from "node:crypto";
33412
- import * as fs6 from "node:fs";
33665
+ import * as fs7 from "node:fs";
33666
+ import * as path8 from "node:path";
33413
33667
 
33414
33668
  // ts/agent-core/dist/internal/attachment-input.js
33415
33669
  import { execSync } from "node:child_process";
33416
33670
  import { constants } from "node:fs";
33417
33671
  import * as fsSync from "node:fs";
33418
- import * as fs5 from "node:fs/promises";
33419
- import * as path6 from "node:path";
33672
+ import * as fs6 from "node:fs/promises";
33673
+ import * as path7 from "node:path";
33420
33674
  var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
33421
33675
  var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
33422
33676
  var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
@@ -33446,11 +33700,11 @@ async function prepareLocalImageAttachments(event, context2, opts) {
33446
33700
  };
33447
33701
  }
33448
33702
  const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
33449
- const messageDir = path6.join(rootDir, sanitizePathSegment(event.messageId));
33703
+ const messageDir = path7.join(rootDir, sanitizePathSegment(event.messageId));
33450
33704
  await ensurePathIsNotSymlink(messageDir);
33451
- await fs5.mkdir(messageDir, { recursive: true });
33705
+ await fs6.mkdir(messageDir, { recursive: true });
33452
33706
  await ensurePathIsNotSymlink(messageDir);
33453
- const activeMessageDir = path6.resolve(messageDir);
33707
+ const activeMessageDir = path7.resolve(messageDir);
33454
33708
  activeAttachmentDirs.add(activeMessageDir);
33455
33709
  const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
33456
33710
  const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
@@ -33467,7 +33721,7 @@ async function prepareLocalImageAttachments(event, context2, opts) {
33467
33721
  const notes = [];
33468
33722
  let downloadedBytes = 0;
33469
33723
  for (const att of imageAttachments) {
33470
- const localPath = path6.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
33724
+ const localPath = path7.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
33471
33725
  const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
33472
33726
  const fetchFresh = async () => {
33473
33727
  const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
@@ -33524,7 +33778,7 @@ async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
33524
33778
  return { body: appendLocalAttachmentRefs(body, attachments), attachments };
33525
33779
  }
33526
33780
  function pinLocalAttachmentPaths(images) {
33527
- const dirs = new Set(images.map((image) => path6.resolve(path6.dirname(image.localPath))));
33781
+ const dirs = new Set(images.map((image) => path7.resolve(path7.dirname(image.localPath))));
33528
33782
  for (const dir of dirs) {
33529
33783
  activeAttachmentDirs.add(dir);
33530
33784
  }
@@ -33539,7 +33793,7 @@ function pinLocalAttachmentPaths(images) {
33539
33793
  };
33540
33794
  }
33541
33795
  function attachmentRootDir(workspaceDir) {
33542
- return path6.join(path6.resolve(workspaceDir), ".parall", "attachments");
33796
+ return path7.join(path7.resolve(workspaceDir), ".parall", "attachments");
33543
33797
  }
33544
33798
  function ensureLocalAttachmentGitExclude(workingDirectory) {
33545
33799
  try {
@@ -33548,8 +33802,8 @@ function ensureLocalAttachmentGitExclude(workingDirectory) {
33548
33802
  encoding: "utf8",
33549
33803
  stdio: ["ignore", "pipe", "ignore"]
33550
33804
  }).trim();
33551
- const excludePath = path6.isAbsolute(rel) ? rel : path6.join(workingDirectory, rel);
33552
- fsSync.mkdirSync(path6.dirname(excludePath), { recursive: true });
33805
+ const excludePath = path7.isAbsolute(rel) ? rel : path7.join(workingDirectory, rel);
33806
+ fsSync.mkdirSync(path7.dirname(excludePath), { recursive: true });
33553
33807
  const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
33554
33808
  if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
33555
33809
  return;
@@ -33585,18 +33839,18 @@ function scheduleAttachmentMaintenance(rootDir, opts) {
33585
33839
  return run;
33586
33840
  }
33587
33841
  async function ensureAttachmentRootDir(workspaceDir) {
33588
- const workspaceRoot = path6.resolve(workspaceDir);
33589
- const parallDir = path6.join(workspaceRoot, ".parall");
33842
+ const workspaceRoot = path7.resolve(workspaceDir);
33843
+ const parallDir = path7.join(workspaceRoot, ".parall");
33590
33844
  const rootDir = attachmentRootDir(workspaceRoot);
33591
- await fs5.mkdir(workspaceRoot, { recursive: true });
33845
+ await fs6.mkdir(workspaceRoot, { recursive: true });
33592
33846
  await ensurePathIsNotSymlink(parallDir);
33593
- await fs5.mkdir(parallDir, { recursive: true, mode: 448 });
33847
+ await fs6.mkdir(parallDir, { recursive: true, mode: 448 });
33594
33848
  await ensurePathIsNotSymlink(parallDir);
33595
33849
  await ensurePathIsNotSymlink(rootDir);
33596
- await fs5.mkdir(rootDir, { recursive: true, mode: 448 });
33850
+ await fs6.mkdir(rootDir, { recursive: true, mode: 448 });
33597
33851
  await ensurePathIsNotSymlink(rootDir);
33598
- const realWorkspace = await fs5.realpath(workspaceRoot);
33599
- const realRoot = await fs5.realpath(rootDir);
33852
+ const realWorkspace = await fs6.realpath(workspaceRoot);
33853
+ const realRoot = await fs6.realpath(rootDir);
33600
33854
  if (!isPathInside(realRoot, realWorkspace)) {
33601
33855
  throw new Error(`attachment root escapes workspace: ${rootDir}`);
33602
33856
  }
@@ -33604,7 +33858,7 @@ async function ensureAttachmentRootDir(workspaceDir) {
33604
33858
  }
33605
33859
  async function ensurePathIsNotSymlink(filePath) {
33606
33860
  try {
33607
- const stat = await fs5.lstat(filePath);
33861
+ const stat = await fs6.lstat(filePath);
33608
33862
  if (stat.isSymbolicLink()) {
33609
33863
  throw new Error(`refusing to use symlinked attachment path ${filePath}`);
33610
33864
  }
@@ -33615,8 +33869,8 @@ async function ensurePathIsNotSymlink(filePath) {
33615
33869
  }
33616
33870
  }
33617
33871
  function isPathInside(childPath, parentPath) {
33618
- const rel = path6.relative(parentPath, childPath);
33619
- return rel === "" || !!rel && !rel.startsWith("..") && !path6.isAbsolute(rel);
33872
+ const rel = path7.relative(parentPath, childPath);
33873
+ return rel === "" || !!rel && !rel.startsWith("..") && !path7.isAbsolute(rel);
33620
33874
  }
33621
33875
  async function existingUsableFile(filePath, expectedSize, rootDir) {
33622
33876
  try {
@@ -33627,30 +33881,30 @@ async function existingUsableFile(filePath, expectedSize, rootDir) {
33627
33881
  }
33628
33882
  }
33629
33883
  async function localFileStatInsideRoot(filePath, rootDir) {
33630
- const stat = await fs5.lstat(filePath);
33884
+ const stat = await fs6.lstat(filePath);
33631
33885
  if (stat.isSymbolicLink()) {
33632
33886
  throw new Error(`refusing to use symlinked attachment file ${filePath}`);
33633
33887
  }
33634
33888
  if (!stat.isFile()) {
33635
33889
  throw new Error(`attachment path is not a file ${filePath}`);
33636
33890
  }
33637
- const realRoot = await fs5.realpath(rootDir);
33638
- const realFile = await fs5.realpath(filePath);
33891
+ const realRoot = await fs6.realpath(rootDir);
33892
+ const realFile = await fs6.realpath(filePath);
33639
33893
  if (!isPathInside(realFile, realRoot)) {
33640
33894
  throw new Error(`attachment file escapes workspace: ${filePath}`);
33641
33895
  }
33642
33896
  return stat;
33643
33897
  }
33644
33898
  async function localDirectoryStatInsideRoot(dirPath, rootDir) {
33645
- const stat = await fs5.lstat(dirPath);
33899
+ const stat = await fs6.lstat(dirPath);
33646
33900
  if (stat.isSymbolicLink()) {
33647
33901
  throw new Error(`refusing to use symlinked attachment directory ${dirPath}`);
33648
33902
  }
33649
33903
  if (!stat.isDirectory()) {
33650
33904
  throw new Error(`attachment path is not a directory ${dirPath}`);
33651
33905
  }
33652
- const realRoot = await fs5.realpath(rootDir);
33653
- const realDir = await fs5.realpath(dirPath);
33906
+ const realRoot = await fs6.realpath(rootDir);
33907
+ const realDir = await fs6.realpath(dirPath);
33654
33908
  if (!isPathInside(realDir, realRoot)) {
33655
33909
  throw new Error(`attachment directory escapes workspace: ${dirPath}`);
33656
33910
  }
@@ -33658,7 +33912,7 @@ async function localDirectoryStatInsideRoot(dirPath, rootDir) {
33658
33912
  }
33659
33913
  async function openLocalFileInsideRoot(filePath, rootDir) {
33660
33914
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
33661
- const file = await fs5.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
33915
+ const file = await fs6.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
33662
33916
  let keepOpen = false;
33663
33917
  try {
33664
33918
  const openedStat = await file.stat();
@@ -33674,8 +33928,8 @@ async function openLocalFileInsideRoot(filePath, rootDir) {
33674
33928
  }
33675
33929
  }
33676
33930
  async function openLocalTempFileInsideRoot(filePath, rootDir) {
33677
- await localDirectoryStatInsideRoot(path6.dirname(filePath), rootDir);
33678
- const file = await fs5.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
33931
+ await localDirectoryStatInsideRoot(path7.dirname(filePath), rootDir);
33932
+ const file = await fs6.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
33679
33933
  let keepOpen = false;
33680
33934
  try {
33681
33935
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
@@ -33700,7 +33954,7 @@ async function assertLocalFileIdentity(filePath, rootDir, expected) {
33700
33954
  async function removeLocalFileIfInside(filePath, rootDir) {
33701
33955
  try {
33702
33956
  await localFileStatInsideRoot(filePath, rootDir);
33703
- await fs5.rm(filePath, { force: true });
33957
+ await fs6.rm(filePath, { force: true });
33704
33958
  } catch {
33705
33959
  }
33706
33960
  }
@@ -33713,7 +33967,7 @@ function sameFile(a, b) {
33713
33967
  async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
33714
33968
  let entries;
33715
33969
  try {
33716
- entries = await fs5.readdir(rootDir, { withFileTypes: true });
33970
+ entries = await fs6.readdir(rootDir, { withFileTypes: true });
33717
33971
  } catch {
33718
33972
  return;
33719
33973
  }
@@ -33721,15 +33975,15 @@ async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
33721
33975
  await Promise.all(entries.map(async (entry) => {
33722
33976
  if (!entry.isDirectory())
33723
33977
  return;
33724
- const fullPath = path6.join(rootDir, entry.name);
33978
+ const fullPath = path7.join(rootDir, entry.name);
33725
33979
  try {
33726
- if (preserveDirs?.has(path6.resolve(fullPath)))
33980
+ if (preserveDirs?.has(path7.resolve(fullPath)))
33727
33981
  return;
33728
- const stat = await fs5.lstat(fullPath);
33982
+ const stat = await fs6.lstat(fullPath);
33729
33983
  if (!stat.isDirectory())
33730
33984
  return;
33731
33985
  if (stat.mtimeMs < cutoff) {
33732
- await fs5.rm(fullPath, { recursive: true, force: true });
33986
+ await fs6.rm(fullPath, { recursive: true, force: true });
33733
33987
  }
33734
33988
  } catch (err) {
33735
33989
  log2?.warn?.(`agent-core: failed to clean attachment temp dir ${fullPath}: ${String(err)}`);
@@ -33741,7 +33995,7 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33741
33995
  return;
33742
33996
  let entries;
33743
33997
  try {
33744
- entries = await fs5.readdir(rootDir, { withFileTypes: true });
33998
+ entries = await fs6.readdir(rootDir, { withFileTypes: true });
33745
33999
  } catch {
33746
34000
  return;
33747
34001
  }
@@ -33750,9 +34004,9 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33750
34004
  for (const entry of entries) {
33751
34005
  if (!entry.isDirectory())
33752
34006
  continue;
33753
- const fullPath = path6.join(rootDir, entry.name);
34007
+ const fullPath = path7.join(rootDir, entry.name);
33754
34008
  try {
33755
- const stat = await fs5.lstat(fullPath);
34009
+ const stat = await fs6.lstat(fullPath);
33756
34010
  if (!stat.isDirectory())
33757
34011
  continue;
33758
34012
  const size = await directorySize(fullPath);
@@ -33768,10 +34022,10 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33768
34022
  for (const dir of dirs) {
33769
34023
  if (total <= maxBytes)
33770
34024
  break;
33771
- if (preserveDirs?.has(path6.resolve(dir.path)))
34025
+ if (preserveDirs?.has(path7.resolve(dir.path)))
33772
34026
  continue;
33773
34027
  try {
33774
- await fs5.rm(dir.path, { recursive: true, force: true });
34028
+ await fs6.rm(dir.path, { recursive: true, force: true });
33775
34029
  total -= dir.size;
33776
34030
  } catch (err) {
33777
34031
  log2?.warn?.(`agent-core: failed to prune attachment cache dir ${dir.path}: ${String(err)}`);
@@ -33780,12 +34034,12 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33780
34034
  }
33781
34035
  async function directorySize(dirPath) {
33782
34036
  let total = 0;
33783
- const entries = await fs5.readdir(dirPath, { withFileTypes: true });
34037
+ const entries = await fs6.readdir(dirPath, { withFileTypes: true });
33784
34038
  for (const entry of entries) {
33785
- const fullPath = path6.join(dirPath, entry.name);
34039
+ const fullPath = path7.join(dirPath, entry.name);
33786
34040
  let stat;
33787
34041
  try {
33788
- stat = await fs5.lstat(fullPath);
34042
+ stat = await fs6.lstat(fullPath);
33789
34043
  } catch {
33790
34044
  continue;
33791
34045
  }
@@ -33800,10 +34054,10 @@ async function directorySize(dirPath) {
33800
34054
  return total;
33801
34055
  }
33802
34056
  function activeDirsForRoot(rootDir) {
33803
- const root = path6.resolve(rootDir);
34057
+ const root = path7.resolve(rootDir);
33804
34058
  const dirs = /* @__PURE__ */ new Set();
33805
34059
  for (const dir of activeAttachmentDirs) {
33806
- if (dir === root || dir.startsWith(`${root}${path6.sep}`)) {
34060
+ if (dir === root || dir.startsWith(`${root}${path7.sep}`)) {
33807
34061
  dirs.add(dir);
33808
34062
  }
33809
34063
  }
@@ -33900,9 +34154,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
33900
34154
  }
33901
34155
  writtenStat = await file.stat();
33902
34156
  await closeFile();
33903
- await localDirectoryStatInsideRoot(path6.dirname(filePath), rootDir);
34157
+ await localDirectoryStatInsideRoot(path7.dirname(filePath), rootDir);
33904
34158
  await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
33905
- await fs5.rename(tmpPath, filePath);
34159
+ await fs6.rename(tmpPath, filePath);
33906
34160
  completed = true;
33907
34161
  return written;
33908
34162
  } finally {
@@ -33918,9 +34172,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
33918
34172
  }
33919
34173
  }
33920
34174
  function localFileName(attachmentId, fileName, mimeType) {
33921
- const safeName = sanitizePathSegment(path6.basename(fileName || attachmentId));
33922
- const ext = path6.extname(safeName) || extensionForMime(mimeType);
33923
- const stem = path6.basename(safeName, path6.extname(safeName)) || attachmentId;
34175
+ const safeName = sanitizePathSegment(path7.basename(fileName || attachmentId));
34176
+ const ext = path7.extname(safeName) || extensionForMime(mimeType);
34177
+ const stem = path7.basename(safeName, path7.extname(safeName)) || attachmentId;
33924
34178
  return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
33925
34179
  }
33926
34180
  function extensionForMime(mimeType) {
@@ -34443,6 +34697,7 @@ var CodexAppServerAdapter = class {
34443
34697
  }
34444
34698
  (this.opts.log ?? context2.log)?.warn?.(`pending steer invalidated (subprocess died); falling through to normal dispatch`);
34445
34699
  }
34700
+ await this.applyPendingRestart(context2.log);
34446
34701
  await this.ensureStarted(context2.log);
34447
34702
  const client = this.client;
34448
34703
  if (!client) {
@@ -34656,6 +34911,24 @@ var CodexAppServerAdapter = class {
34656
34911
  this.opts.log?.warn?.(`thread/fork failed: ${errToString(err)}`);
34657
34912
  return null;
34658
34913
  }
34914
+ /**
34915
+ * Lazily restart the app-server before the NEXT turn: the workspace
34916
+ * config.toml (developer_instructions, carrying capability fragments) is
34917
+ * loaded at process start, so a changed fragment set needs a respawn to
34918
+ * reach the prompt. Deferred to the next dispatch with no active turns —
34919
+ * never kills an in-flight turn; thread state survives via thread/resume.
34920
+ */
34921
+ requestProcessRestart() {
34922
+ this.restartRequested = true;
34923
+ }
34924
+ restartRequested = false;
34925
+ async applyPendingRestart(log2) {
34926
+ if (!this.restartRequested || this.activeTurns.size > 0)
34927
+ return;
34928
+ this.restartRequested = false;
34929
+ (log2 ?? this.opts.log)?.info?.("restarting codex app-server to pick up updated developer_instructions");
34930
+ await this.stop();
34931
+ }
34659
34932
  async stop() {
34660
34933
  this.stopping = true;
34661
34934
  const proc = this.proc;
@@ -34665,6 +34938,7 @@ var CodexAppServerAdapter = class {
34665
34938
  this.initialized = false;
34666
34939
  this.activeTurnIds.clear();
34667
34940
  this.pendingInjections.clear();
34941
+ this.resumedThreadIds.clear();
34668
34942
  if (client)
34669
34943
  client.dispose(new Error("adapter stopped"));
34670
34944
  if (proc && proc.exitCode === null && proc.signalCode === null) {
@@ -34707,6 +34981,11 @@ var CodexAppServerAdapter = class {
34707
34981
  FORCE_COLOR: "0",
34708
34982
  NO_COLOR: "1"
34709
34983
  };
34984
+ if (this.opts.capabilityBinDir) {
34985
+ const pathKey = IS_WIN32 ? Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH" : "PATH";
34986
+ const existing = env[pathKey];
34987
+ env[pathKey] = existing ? `${this.opts.capabilityBinDir}${path8.delimiter}${existing}` : this.opts.capabilityBinDir;
34988
+ }
34710
34989
  if (this.opts.contextFilePath) {
34711
34990
  env.PRLL_CONTEXT_FILE = this.opts.contextFilePath;
34712
34991
  }
@@ -34858,7 +35137,7 @@ var TurnSink = class {
34858
35137
  }
34859
35138
  };
34860
35139
  function ensureGitRepo(workingDirectory) {
34861
- fs6.mkdirSync(workingDirectory, { recursive: true });
35140
+ fs7.mkdirSync(workingDirectory, { recursive: true });
34862
35141
  try {
34863
35142
  execSync2("git rev-parse --is-inside-work-tree", { cwd: workingDirectory, stdio: "pipe" });
34864
35143
  ensureLocalAttachmentGitExclude(workingDirectory);
@@ -34928,8 +35207,8 @@ function errToString(err) {
34928
35207
  }
34929
35208
 
34930
35209
  // ts/codex-agent/dist/session-manager.js
34931
- import * as fs7 from "node:fs";
34932
- import * as path7 from "node:path";
35210
+ import * as fs8 from "node:fs";
35211
+ import * as path9 from "node:path";
34933
35212
  var CodexSessionManager = class {
34934
35213
  mainSessionKey;
34935
35214
  stateFilePath;
@@ -34966,14 +35245,14 @@ var CodexSessionManager = class {
34966
35245
  clearMainThread() {
34967
35246
  this.threadIds.delete(this.mainSessionKey);
34968
35247
  try {
34969
- fs7.rmSync(this.stateFilePath, { force: true });
35248
+ fs8.rmSync(this.stateFilePath, { force: true });
34970
35249
  } catch (error) {
34971
35250
  this.logger?.warn(`codex-agent: failed to clear main thread state at ${this.stateFilePath}: ${String(error)}`);
34972
35251
  }
34973
35252
  }
34974
35253
  restore() {
34975
35254
  try {
34976
- const raw = fs7.readFileSync(this.stateFilePath, "utf8");
35255
+ const raw = fs8.readFileSync(this.stateFilePath, "utf8");
34977
35256
  const parsed = JSON.parse(raw);
34978
35257
  if (parsed.runtimeKey === this.mainSessionKey && typeof parsed.threadId === "string" && parsed.threadId.trim()) {
34979
35258
  this.threadIds.set(this.mainSessionKey, parsed.threadId.trim());
@@ -34986,10 +35265,10 @@ var CodexSessionManager = class {
34986
35265
  }
34987
35266
  persist(threadId) {
34988
35267
  try {
34989
- fs7.mkdirSync(path7.dirname(this.stateFilePath), { recursive: true });
35268
+ fs8.mkdirSync(path9.dirname(this.stateFilePath), { recursive: true });
34990
35269
  const tmpPath = `${this.stateFilePath}.tmp`;
34991
- fs7.writeFileSync(tmpPath, JSON.stringify({ runtimeKey: this.mainSessionKey, threadId }, null, 2));
34992
- fs7.renameSync(tmpPath, this.stateFilePath);
35270
+ fs8.writeFileSync(tmpPath, JSON.stringify({ runtimeKey: this.mainSessionKey, threadId }, null, 2));
35271
+ fs8.renameSync(tmpPath, this.stateFilePath);
34993
35272
  } catch (error) {
34994
35273
  this.logger?.warn(`codex-agent: failed to persist thread state at ${this.stateFilePath}: ${String(error)}`);
34995
35274
  }
@@ -34997,8 +35276,8 @@ var CodexSessionManager = class {
34997
35276
  };
34998
35277
 
34999
35278
  // ts/codex-agent/dist/workspace.js
35000
- import * as fs8 from "node:fs";
35001
- import * as path8 from "node:path";
35279
+ import * as fs9 from "node:fs";
35280
+ import * as path10 from "node:path";
35002
35281
 
35003
35282
  // ts/node_modules/.pnpm/smol-toml@1.6.1/node_modules/smol-toml/dist/error.js
35004
35283
  function getLineColFromPtr(string, ptr) {
@@ -35691,13 +35970,226 @@ function parse(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
35691
35970
  }
35692
35971
 
35693
35972
  // ts/codex-agent/dist/workspace.js
35973
+ var CONFIG_LOCK_TIMINGS = {
35974
+ staleMs: 1e4,
35975
+ waitMs: 15e3,
35976
+ retryMs: 25
35977
+ };
35978
+ var SLEEP_SIGNAL = new Int32Array(new SharedArrayBuffer(4));
35979
+ function sleepSync(ms) {
35980
+ Atomics.wait(SLEEP_SIGNAL, 0, 0, ms);
35981
+ }
35982
+ function withConfigLock(codexHome, log2, fn) {
35983
+ const queueDir = path10.join(codexHome, "config.toml.lock.d");
35984
+ let ticketName = bakeryEnqueue(queueDir);
35985
+ let ticketPath = ticketName ? path10.join(queueDir, ticketName) : "";
35986
+ let acquired = false;
35987
+ let heldPath = "";
35988
+ const deadline = Date.now() + CONFIG_LOCK_TIMINGS.waitMs;
35989
+ while (ticketName && Date.now() < deadline) {
35990
+ let names;
35991
+ try {
35992
+ names = fs9.readdirSync(queueDir).sort();
35993
+ } catch {
35994
+ break;
35995
+ }
35996
+ if (!names.includes(ticketName)) {
35997
+ ticketName = bakeryEnqueue(queueDir);
35998
+ if (!ticketName)
35999
+ break;
36000
+ ticketPath = path10.join(queueDir, ticketName);
36001
+ continue;
36002
+ }
36003
+ const now = Date.now();
36004
+ let rescan = false;
36005
+ let blocked = false;
36006
+ let head;
36007
+ for (const name of names) {
36008
+ const entryPath = path10.join(queueDir, name);
36009
+ if (name.startsWith("held-")) {
36010
+ const enteredAt = Number.parseInt(name.slice(5, 20), 10);
36011
+ if (Number.isFinite(enteredAt) && now - enteredAt > CONFIG_LOCK_TIMINGS.staleMs) {
36012
+ try {
36013
+ fs9.unlinkSync(entryPath);
36014
+ } catch {
36015
+ }
36016
+ rescan = true;
36017
+ break;
36018
+ }
36019
+ blocked = true;
36020
+ break;
36021
+ }
36022
+ let mtimeMs;
36023
+ try {
36024
+ mtimeMs = fs9.statSync(entryPath).mtimeMs;
36025
+ } catch {
36026
+ rescan = true;
36027
+ break;
36028
+ }
36029
+ if (now - mtimeMs > CONFIG_LOCK_TIMINGS.staleMs) {
36030
+ try {
36031
+ fs9.unlinkSync(entryPath);
36032
+ } catch {
36033
+ }
36034
+ rescan = true;
36035
+ break;
36036
+ }
36037
+ if (name.startsWith("choosing-")) {
36038
+ blocked = true;
36039
+ break;
36040
+ }
36041
+ if (name.startsWith("t-")) {
36042
+ head = name;
36043
+ break;
36044
+ }
36045
+ }
36046
+ if (rescan)
36047
+ continue;
36048
+ if (!blocked && head === ticketName) {
36049
+ CONFIG_LOCK_TEST_HOOKS.beforeTicketEntry?.();
36050
+ const heldName = `held-${String(Date.now()).padStart(15, "0")}-${ticketName.slice(2)}`;
36051
+ const candidateHeldPath = path10.join(queueDir, heldName);
36052
+ try {
36053
+ fs9.renameSync(ticketPath, candidateHeldPath);
36054
+ } catch {
36055
+ continue;
36056
+ }
36057
+ heldPath = candidateHeldPath;
36058
+ acquired = true;
36059
+ break;
36060
+ }
36061
+ try {
36062
+ const t = /* @__PURE__ */ new Date();
36063
+ fs9.utimesSync(ticketPath, t, t);
36064
+ } catch {
36065
+ }
36066
+ sleepSync(CONFIG_LOCK_TIMINGS.retryMs);
36067
+ }
36068
+ if (!acquired) {
36069
+ log2?.warn(`could not acquire ${queueDir}; writing config.toml without lock`);
36070
+ if (ticketName) {
36071
+ try {
36072
+ fs9.unlinkSync(ticketPath);
36073
+ } catch {
36074
+ }
36075
+ }
36076
+ }
36077
+ try {
36078
+ fn();
36079
+ } finally {
36080
+ if (acquired) {
36081
+ try {
36082
+ fs9.unlinkSync(heldPath);
36083
+ } catch {
36084
+ }
36085
+ }
36086
+ }
36087
+ }
36088
+ var CONFIG_LOCK_TEST_HOOKS = {};
36089
+ function bakeryEnqueue(queueDir) {
36090
+ for (let attempt = 0; attempt < 3; attempt++) {
36091
+ const token = `${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
36092
+ const markerPath = path10.join(queueDir, `choosing-${token}`);
36093
+ try {
36094
+ fs9.mkdirSync(queueDir, { recursive: true });
36095
+ CONFIG_LOCK_TEST_HOOKS.beforeChoosingMarker?.();
36096
+ fs9.writeFileSync(markerPath, "", { flag: "wx" });
36097
+ } catch {
36098
+ return null;
36099
+ }
36100
+ try {
36101
+ let maxSeq = 0;
36102
+ for (const name of fs9.readdirSync(queueDir)) {
36103
+ if (!name.startsWith("t-"))
36104
+ continue;
36105
+ const seq = Number.parseInt(name.slice(2, 12), 10);
36106
+ if (Number.isFinite(seq) && seq > maxSeq)
36107
+ maxSeq = seq;
36108
+ }
36109
+ const ticketName = `t-${String(maxSeq + 1).padStart(10, "0")}-${token}`;
36110
+ const ticketPath = path10.join(queueDir, ticketName);
36111
+ CONFIG_LOCK_TEST_HOOKS.beforeTicketPublish?.();
36112
+ fs9.renameSync(markerPath, ticketPath);
36113
+ try {
36114
+ const t = /* @__PURE__ */ new Date();
36115
+ fs9.utimesSync(ticketPath, t, t);
36116
+ } catch {
36117
+ }
36118
+ return ticketName;
36119
+ } catch (err) {
36120
+ try {
36121
+ fs9.unlinkSync(markerPath);
36122
+ } catch {
36123
+ }
36124
+ if (err.code === "ENOENT")
36125
+ continue;
36126
+ return null;
36127
+ }
36128
+ }
36129
+ return null;
36130
+ }
36131
+ function writeConfigAtomic(filePath, content) {
36132
+ const realPath = resolveWriteTarget(filePath);
36133
+ let mode;
36134
+ try {
36135
+ mode = fs9.statSync(realPath).mode & 511;
36136
+ } catch {
36137
+ }
36138
+ const tmpPath = `${realPath}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
36139
+ let tmpCreated = false;
36140
+ try {
36141
+ fs9.writeFileSync(tmpPath, content, { encoding: "utf8", mode: 384, flag: "wx" });
36142
+ tmpCreated = true;
36143
+ if (mode !== void 0)
36144
+ fs9.chmodSync(tmpPath, mode);
36145
+ fs9.renameSync(tmpPath, realPath);
36146
+ } catch (err) {
36147
+ if (tmpCreated || err.code !== "EEXIST") {
36148
+ try {
36149
+ fs9.unlinkSync(tmpPath);
36150
+ } catch {
36151
+ }
36152
+ }
36153
+ throw err;
36154
+ }
36155
+ }
36156
+ function resolveWriteTarget(filePath) {
36157
+ try {
36158
+ return fs9.realpathSync(filePath);
36159
+ } catch (err) {
36160
+ if (err.code !== "ENOENT")
36161
+ throw err;
36162
+ }
36163
+ const seen = /* @__PURE__ */ new Set();
36164
+ let p = path10.resolve(filePath);
36165
+ for (let depth = 0; depth < 40; depth++) {
36166
+ if (seen.has(p)) {
36167
+ throw new Error(`symlink cycle at ${p} while resolving ${filePath}`);
36168
+ }
36169
+ seen.add(p);
36170
+ let link;
36171
+ try {
36172
+ link = fs9.readlinkSync(p);
36173
+ } catch (err) {
36174
+ const code = err.code;
36175
+ if (code === "ENOENT" || code === "EINVAL")
36176
+ return p;
36177
+ throw err;
36178
+ }
36179
+ p = path10.resolve(path10.dirname(p), link);
36180
+ }
36181
+ throw new Error(`symlink chain deeper than 40 while resolving ${filePath}`);
36182
+ }
35694
36183
  function ensureWorkspaceTrusted(codexHome, workspaceDir, log2) {
35695
- const configPath = path8.join(codexHome, "config.toml");
35696
- const normalizedPath = path8.resolve(workspaceDir);
36184
+ withConfigLock(codexHome, log2, () => ensureWorkspaceTrustedLocked(codexHome, workspaceDir, log2));
36185
+ }
36186
+ function ensureWorkspaceTrustedLocked(codexHome, workspaceDir, log2) {
36187
+ const configPath = path10.join(codexHome, "config.toml");
36188
+ const normalizedPath = path10.resolve(workspaceDir);
35697
36189
  try {
35698
36190
  let content = "";
35699
36191
  try {
35700
- content = fs8.readFileSync(configPath, "utf8");
36192
+ content = fs9.readFileSync(configPath, "utf8");
35701
36193
  } catch (err) {
35702
36194
  if (err.code !== "ENOENT")
35703
36195
  throw err;
@@ -35712,8 +36204,13 @@ function ensureWorkspaceTrusted(codexHome, workspaceDir, log2) {
35712
36204
  }
35713
36205
  }
35714
36206
  const projects = parsed?.projects;
35715
- if (projects?.[normalizedPath]?.trust_level === "trusted")
36207
+ const existingTrust = projects?.[normalizedPath]?.trust_level;
36208
+ if (existingTrust === "trusted")
36209
+ return;
36210
+ if (existingTrust !== void 0) {
36211
+ log2?.warn(`Codex config marks ${normalizedPath} as trust_level=${JSON.stringify(existingTrust)}; respecting the explicit decision \u2014 project-level developer_instructions will not load for this workspace`);
35716
36212
  return;
36213
+ }
35717
36214
  const escapedPath = normalizedPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
35718
36215
  const sectionHeader = `[projects."${escapedPath}"]`;
35719
36216
  const trustLine = 'trust_level = "trusted"';
@@ -35737,14 +36234,14 @@ ${trustLine}
35737
36234
  content = content.substring(0, afterHeader) + trustLine + "\n" + content.substring(afterHeader);
35738
36235
  }
35739
36236
  }
35740
- fs8.writeFileSync(configPath, content, "utf8");
36237
+ writeConfigAtomic(configPath, content);
35741
36238
  } else if (projects?.[normalizedPath] !== void 0) {
35742
36239
  log2?.warn(`Codex config.toml has non-canonical header for ${normalizedPath}; skipping trust write`);
35743
36240
  } else if (projects && !content.includes("[projects.")) {
35744
36241
  log2?.warn(`Codex config.toml uses inline table for projects; skipping trust write for ${normalizedPath}`);
35745
36242
  } else {
35746
- fs8.mkdirSync(codexHome, { recursive: true });
35747
- fs8.appendFileSync(configPath, `
36243
+ fs9.mkdirSync(codexHome, { recursive: true });
36244
+ fs9.appendFileSync(configPath, `
35748
36245
  ${sectionHeader}
35749
36246
  ${trustLine}
35750
36247
  `, "utf8");
@@ -35761,12 +36258,15 @@ function isParallProxyMode(env = process.env) {
35761
36258
  return baseUrl === apiUrl || baseUrl.startsWith(`${apiUrl}/`);
35762
36259
  }
35763
36260
  function ensureParallProvider(codexHome, apiUrl, log2) {
35764
- const configPath = path8.join(codexHome, "config.toml");
36261
+ withConfigLock(codexHome, log2, () => ensureParallProviderLocked(codexHome, apiUrl));
36262
+ }
36263
+ function ensureParallProviderLocked(codexHome, apiUrl) {
36264
+ const configPath = path10.join(codexHome, "config.toml");
35765
36265
  const baseUrl = apiUrl.replace(/\/$/, "") + "/api/llm/v1";
35766
36266
  try {
35767
36267
  let content = "";
35768
36268
  try {
35769
- content = fs8.readFileSync(configPath, "utf8");
36269
+ content = fs9.readFileSync(configPath, "utf8");
35770
36270
  } catch (err) {
35771
36271
  if (err.code !== "ENOENT")
35772
36272
  throw err;
@@ -35797,8 +36297,8 @@ function ensureParallProvider(codexHome, apiUrl, log2) {
35797
36297
  } else {
35798
36298
  content = content.trimEnd() + "\n\n" + providerBlock + "\n";
35799
36299
  }
35800
- fs8.mkdirSync(codexHome, { recursive: true });
35801
- fs8.writeFileSync(configPath, content, "utf8");
36300
+ fs9.mkdirSync(codexHome, { recursive: true });
36301
+ writeConfigAtomic(configPath, content);
35802
36302
  } catch (err) {
35803
36303
  throw new Error(`failed to write Parall provider config: ${String(err)}`);
35804
36304
  }
@@ -35807,26 +36307,33 @@ function findSectionEnd(content, fromIndex) {
35807
36307
  const nextHeader = content.indexOf("\n[", fromIndex);
35808
36308
  return nextHeader === -1 ? content.length : nextHeader;
35809
36309
  }
35810
- function ensureCodexWorkspace(workspaceDir, log2, agentIdentity) {
35811
- const systemPrompt = [
36310
+ function writeCodexSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
36311
+ const parts = [
35812
36312
  buildIdentity(agentIdentity),
35813
36313
  BRIDGE_WORKSPACE_INSTRUCTIONS,
35814
36314
  PRLL_BEHAVIOR,
35815
- PRLL_REFERENCE_GUIDE,
35816
- buildSkillReferences(workspaceDir)
35817
- ].join("\n\n");
35818
- fs8.mkdirSync(workspaceDir, { recursive: true });
35819
- const parallDir = path8.join(workspaceDir, ".parall");
35820
- fs8.mkdirSync(parallDir, { recursive: true });
35821
- fs8.writeFileSync(path8.join(parallDir, "system-prompt.md"), systemPrompt, "utf8");
35822
- writeSkillFiles(path8.join(parallDir, "skills"));
35823
- const codexConfigDir = path8.join(workspaceDir, ".codex");
35824
- fs8.mkdirSync(codexConfigDir, { recursive: true });
36315
+ PRLL_REFERENCE_GUIDE
36316
+ ];
36317
+ if (capabilityFragments && capabilityFragments.length > 0) {
36318
+ parts.push(capabilityFragments.join("\n\n"));
36319
+ }
36320
+ parts.push(buildSkillReferences(workspaceDir));
36321
+ const systemPrompt = parts.join("\n\n");
36322
+ const parallDir = path10.join(workspaceDir, ".parall");
36323
+ fs9.mkdirSync(parallDir, { recursive: true });
36324
+ fs9.writeFileSync(path10.join(parallDir, "system-prompt.md"), systemPrompt, "utf8");
36325
+ const codexConfigDir = path10.join(workspaceDir, ".codex");
36326
+ fs9.mkdirSync(codexConfigDir, { recursive: true });
35825
36327
  const toml = `developer_instructions = """
35826
36328
  ${systemPrompt.replace(/\\/g, "\\\\").replace(/"""/g, '\\"""')}
35827
36329
  """
35828
36330
  `;
35829
- fs8.writeFileSync(path8.join(codexConfigDir, "config.toml"), toml, "utf8");
36331
+ fs9.writeFileSync(path10.join(codexConfigDir, "config.toml"), toml, "utf8");
36332
+ }
36333
+ function ensureCodexWorkspace(workspaceDir, log2, agentIdentity, capabilityFragments) {
36334
+ fs9.mkdirSync(workspaceDir, { recursive: true });
36335
+ writeCodexSystemPrompt(workspaceDir, agentIdentity, capabilityFragments);
36336
+ writeSkillFiles(path10.join(workspaceDir, ".parall", "skills"));
35830
36337
  }
35831
36338
 
35832
36339
  // ts/codex-agent/dist/index.js
@@ -35880,11 +36387,11 @@ async function main() {
35880
36387
  ensureParallProvider(config.codexHome, config.apiUrl, agentLog);
35881
36388
  agentLog.info("parall custom provider configured (Responses API HTTP/SSE mode)");
35882
36389
  }
35883
- ensureCodexWorkspace(config.workspaceDir, agentLog, {
36390
+ const agentIdentity = {
35884
36391
  userId: agentUserId,
35885
36392
  displayName: me.display_name,
35886
36393
  description: me.agent_profile?.description ?? void 0
35887
- });
36394
+ };
35888
36395
  const runtimeKey = config.runtimeKey || buildCodexRuntimeKey(agentUserId);
35889
36396
  const mainContextFilePath = contextFilePathForSession(config.stateDir, runtimeKey);
35890
36397
  const sessionStateFilePath = sessionStateFilePathForRuntime(config.stateDir, runtimeKey);
@@ -35901,6 +36408,14 @@ async function main() {
35901
36408
  log: agentLog
35902
36409
  });
35903
36410
  const platformDefaults = await configMgr.fetch();
36411
+ const applyChannelCapabilities = () => {
36412
+ const caps = configMgr.capabilities();
36413
+ materializeChannelCapabilities(config.stateDir, caps, agentLog);
36414
+ return caps.map((c) => c.fragment);
36415
+ };
36416
+ const bootCapabilityFragments = applyChannelCapabilities();
36417
+ let lastCapabilityFragments = bootCapabilityFragments.join("\n\n");
36418
+ ensureCodexWorkspace(config.workspaceDir, agentLog, agentIdentity, bootCapabilityFragments);
35904
36419
  const platformModelOverride = deriveModelIsPin(platformDefaults, me.agent_profile);
35905
36420
  const resolvedModel = resolveRuntimeModel(platformModelOverride, platformDefaults.model, config.model);
35906
36421
  const resolvedEffort = platformDefaults.thinkingEffort ?? config.reasoningEffort;
@@ -35920,7 +36435,8 @@ async function main() {
35920
36435
  log: agentLog,
35921
36436
  contextFilePath: mainContextFilePath,
35922
36437
  contextDirPath: dispatchContextDirPath(config.stateDir),
35923
- useParallProvider
36438
+ useParallProvider,
36439
+ capabilityBinDir: capabilityBinDir(config.stateDir)
35924
36440
  });
35925
36441
  const refreshPlatformConfig = async () => {
35926
36442
  const updated = await configMgr.fetch();
@@ -35937,6 +36453,19 @@ async function main() {
35937
36453
  model: resolveRuntimeModel(isPin, updated.model, config.model) ?? null,
35938
36454
  reasoningEffort: updated.thinkingEffort ?? config.reasoningEffort ?? null
35939
36455
  });
36456
+ const fragments = applyChannelCapabilities();
36457
+ const joinedFragments = fragments.join("\n\n");
36458
+ let promptWritten = true;
36459
+ try {
36460
+ writeCodexSystemPrompt(config.workspaceDir, agentIdentity, fragments);
36461
+ } catch (err) {
36462
+ promptWritten = false;
36463
+ agentLog.warn(`system prompt refresh write failed (retrying next refresh): ${String(err)}`);
36464
+ }
36465
+ if (promptWritten && joinedFragments !== lastCapabilityFragments) {
36466
+ lastCapabilityFragments = joinedFragments;
36467
+ adapter.requestProcessRestart();
36468
+ }
35940
36469
  };
35941
36470
  const gateway = new ParallAgentGateway({
35942
36471
  accountId: agentUserId,
@@ -35960,6 +36489,9 @@ async function main() {
35960
36489
  },
35961
36490
  dispatchAdapter: adapter,
35962
36491
  log: agentLog,
36492
+ // Live capability view for hint routing: the channel reply hint points
36493
+ // at the vendor CLI only while the grant is active.
36494
+ getCapabilityKeys: () => configMgr.capabilities().map((c) => c.key),
35963
36495
  shutdownDeadlineMs: parseShutdownDeadlineMs(process.env.PRLL_SHUTDOWN_DEADLINE_MS),
35964
36496
  forkDeadlineMs: parseForkDeadlineMs(process.env.PRLL_FORK_DEADLINE_MS),
35965
36497
  dispatchDeadlineMs: parseDispatchDeadlineMs(process.env.PRLL_DISPATCH_DEADLINE_MS),