@parall/daemon 1.42.1 → 1.44.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 path10 of paths) {
17721
+ for (const path11 of paths) {
17722
17722
  try {
17723
- const result = await fs_1.promises.readFile(path10, { 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, path10) {
21126
+ function appendResourcePathToUrl(url, path11) {
21127
21127
  try {
21128
21128
  new URL(url);
21129
21129
  } catch (_a) {
@@ -21133,11 +21133,11 @@ function appendResourcePathToUrl(url, path10) {
21133
21133
  if (!url.endsWith("/")) {
21134
21134
  url = url + "/";
21135
21135
  }
21136
- url += path10;
21136
+ url += path11;
21137
21137
  try {
21138
21138
  new URL(url);
21139
21139
  } catch (_b) {
21140
- diag2.warn("Configuration: Provided URL appended with '" + path10 + "' 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(path10) {
27704
- return path10.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(path10) {
27030
+ async ensureFreshToken(path11) {
27732
27031
  if (!this.token || !this.getRefreshToken)
27733
27032
  return;
27734
- const pathSuffix = path10.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, path10, body, query, retried = false, opts) {
27065
+ async request(method, path11, body, query, retried = false, opts) {
27767
27066
  if (!retried) {
27768
- await this.ensureFreshToken(path10);
27067
+ await this.ensureFreshToken(path11);
27769
27068
  }
27770
- let url = `${this.baseUrlFor(path10)}${path10}`;
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 = path10.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, path10, 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, path10, body, retried = false) {
27134
+ async multipartRequest(method, path11, body, retried = false) {
27836
27135
  if (!retried) {
27837
- await this.ensureFreshToken(path10);
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(path10)}${path10}`, {
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 = path10.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, path10, 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, path10) {
28563
- return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path10 }, 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) {
@@ -28645,7 +27944,6 @@ var ParallClient = class _ParallClient {
28645
27944
  async steerDispatch(orgId, req) {
28646
27945
  return this.request("POST", ENDPOINTS.DISPATCH_STEER(orgId), req);
28647
27946
  }
28648
- /** End a turn: no_action sweep of the lane's members + lane release + re-drive check. */
28649
27947
  async completeDispatch(orgId, req) {
28650
27948
  return this.request("POST", ENDPOINTS.DISPATCH_COMPLETE(orgId), req);
28651
27949
  }
@@ -28653,6 +27951,10 @@ var ParallClient = class _ParallClient {
28653
27951
  * End a turn for a lane-less runtime: resolve the turn's folded WorkItems
28654
27952
  * by source — broad-cover to the turn's reply Effect when one exists,
28655
27953
  * no_action sweep otherwise. Idempotent.
27954
+ *
27955
+ * @deprecated Legacy ok-only alias — use {@link completeDispatch} with the
27956
+ * `sources` form, which also carries `turn_outcome`. The endpoint retires
27957
+ * at S3b (dispatch-convergence-design.md §3).
28656
27958
  */
28657
27959
  async completeDispatchSources(orgId, req) {
28658
27960
  return this.request("POST", ENDPOINTS.DISPATCH_COMPLETE_SOURCES(orgId), req);
@@ -28681,7 +27983,7 @@ var ParallClient = class _ParallClient {
28681
27983
  if (currentVersion !== void 0) {
28682
27984
  extra["If-None-Match"] = currentVersion;
28683
27985
  }
28684
- const headers = this.buildHeaders(extra);
27986
+ const headers = this.buildHeaders(ENDPOINTS.PLATFORM_CONFIG, extra);
28685
27987
  let res;
28686
27988
  try {
28687
27989
  res = await fetch(url, {
@@ -29129,8 +28431,8 @@ var ParallClient = class _ParallClient {
29129
28431
  async deleteWikiRestriction(orgId, wikiId, restrictionId) {
29130
28432
  await this.request("DELETE", ENDPOINTS.WIKI_RESTRICTION(orgId, wikiId, restrictionId));
29131
28433
  }
29132
- async getWikiAccessStatus(orgId, wikiId, path10) {
29133
- return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path10 ? { path: path10 } : void 0);
28434
+ async getWikiAccessStatus(orgId, wikiId, path11) {
28435
+ return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path11 ? { path: path11 } : void 0);
29134
28436
  }
29135
28437
  async createWikiAccessRequest(orgId, wikiId, data) {
29136
28438
  await this.request("POST", ENDPOINTS.WIKI_ACCESS_REQUESTS(orgId, wikiId), data);
@@ -29139,14 +28441,14 @@ var ParallClient = class _ParallClient {
29139
28441
  async getWikiCommits(orgId, wikiId, params) {
29140
28442
  return this.request("GET", ENDPOINTS.WIKI_COMMITS(orgId, wikiId), void 0, params);
29141
28443
  }
29142
- async getWikiFileCommits(orgId, wikiId, path10, params) {
28444
+ async getWikiFileCommits(orgId, wikiId, path11, params) {
29143
28445
  return this.request("GET", ENDPOINTS.WIKI_FILE_COMMITS(orgId, wikiId), void 0, {
29144
- path: path10,
28446
+ path: path11,
29145
28447
  ...params
29146
28448
  });
29147
28449
  }
29148
- async getWikiBlame(orgId, wikiId, path10, ref) {
29149
- return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path10, ref });
28450
+ async getWikiBlame(orgId, wikiId, path11, ref) {
28451
+ return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path11, ref });
29150
28452
  }
29151
28453
  // ---- Wiki Operations (audit log) ----
29152
28454
  async getWikiOperations(orgId, wikiId, params) {
@@ -29499,702 +28801,1527 @@ var ParallWs = class {
29499
28801
  get state() {
29500
28802
  return this._state;
29501
28803
  }
29502
- async connect() {
29503
- this.intentionalClose = false;
29504
- this.setupBrowserListeners();
29505
- this.setState("connecting");
29506
- let ticket;
29507
- try {
29508
- ticket = await this.options.getTicket();
29509
- } catch (err) {
29510
- if (isBrowserRuntime() && isRetryableNetworkError(err)) {
29511
- console.warn("Failed to get WS ticket:", err);
28804
+ async connect() {
28805
+ this.intentionalClose = false;
28806
+ this.setupBrowserListeners();
28807
+ this.setState("connecting");
28808
+ let ticket;
28809
+ try {
28810
+ ticket = await this.options.getTicket();
28811
+ } catch (err) {
28812
+ if (isBrowserRuntime() && isRetryableNetworkError(err)) {
28813
+ console.warn("Failed to get WS ticket:", err);
28814
+ } else {
28815
+ console.error("Failed to get WS ticket:", err);
28816
+ }
28817
+ if (this.options.reconnect) {
28818
+ this.scheduleReconnect();
28819
+ } else {
28820
+ this.setState("disconnected");
28821
+ }
28822
+ return;
28823
+ }
28824
+ const wsUrl = ticket.ws_url || this.options.wsUrl;
28825
+ if (!wsUrl) {
28826
+ console.error("No WS URL available");
28827
+ this.setState("disconnected");
28828
+ return;
28829
+ }
28830
+ const url = new URL(wsUrl);
28831
+ url.searchParams.set("ticket", ticket.ticket);
28832
+ if (this.lastSeq > 0) {
28833
+ url.searchParams.set("last_seq", String(this.lastSeq));
28834
+ }
28835
+ this.ws = new WebSocket(url.toString());
28836
+ const ws = this.ws;
28837
+ const connectTimeout = setTimeout(() => {
28838
+ if (this._state === "connected" || this.intentionalClose)
28839
+ return;
28840
+ ws.onclose = null;
28841
+ ws.onopen = null;
28842
+ ws.onerror = null;
28843
+ try {
28844
+ ws.close();
28845
+ } catch {
28846
+ }
28847
+ if (ws !== this.ws)
28848
+ return;
28849
+ if (this.options.reconnect) {
28850
+ this.scheduleReconnect();
28851
+ } else {
28852
+ this.setState("disconnected");
28853
+ }
28854
+ }, 15e3);
28855
+ this.ws.onopen = () => {
28856
+ clearTimeout(connectTimeout);
28857
+ this.reconnectAttempts = 0;
28858
+ this.lastReceivedAt = Date.now();
28859
+ this.setState("connected");
28860
+ };
28861
+ this.ws.onmessage = (event) => {
28862
+ try {
28863
+ const frame = JSON.parse(event.data);
28864
+ this.handleFrame(frame);
28865
+ } catch {
28866
+ }
28867
+ };
28868
+ this.ws.onclose = () => {
28869
+ clearTimeout(connectTimeout);
28870
+ this.stopHeartbeat();
28871
+ this.clearProbe();
28872
+ if (this.intentionalClose) {
28873
+ this.setState("disconnected");
28874
+ return;
28875
+ }
28876
+ if (this.options.reconnect) {
28877
+ this.scheduleReconnect();
28878
+ } else {
28879
+ this.setState("disconnected");
28880
+ }
28881
+ };
28882
+ this.ws.onerror = () => {
28883
+ };
28884
+ }
28885
+ disconnect() {
28886
+ this.intentionalClose = true;
28887
+ this.stopHeartbeat();
28888
+ this.clearReconnect();
28889
+ this.clearProbe();
28890
+ this.teardownBrowserListeners();
28891
+ if (this.ws) {
28892
+ this.ws.close();
28893
+ this.ws = null;
28894
+ }
28895
+ this.setState("disconnected");
28896
+ }
28897
+ // ---- Client -> Server messages ----
28898
+ /** Tell the server which chats the user is currently viewing (no auth implications). */
28899
+ watch(chatIds) {
28900
+ this.send({ type: WS_EVENTS.WATCH, data: { chat_ids: chatIds } });
28901
+ }
28902
+ sendTyping(chatId, action, threadRootId) {
28903
+ this.send({
28904
+ type: WS_EVENTS.TYPING,
28905
+ data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
28906
+ });
28907
+ }
28908
+ /** Send an agent heartbeat with telemetry data. */
28909
+ sendAgentHeartbeat(sessionId, telemetry) {
28910
+ this.send({
28911
+ type: WS_EVENTS.AGENT_HEARTBEAT,
28912
+ data: { session_id: sessionId, telemetry }
28913
+ });
28914
+ }
28915
+ sendEvent(type, data) {
28916
+ this.send({ type, data });
28917
+ }
28918
+ // ---- Event listeners ----
28919
+ on(event, handler) {
28920
+ let set = this.listeners.get(event);
28921
+ if (!set) {
28922
+ set = /* @__PURE__ */ new Set();
28923
+ this.listeners.set(event, set);
28924
+ }
28925
+ set.add(handler);
28926
+ return () => {
28927
+ set.delete(handler);
28928
+ };
28929
+ }
28930
+ off(event, handler) {
28931
+ this.listeners.get(event)?.delete(handler);
28932
+ }
28933
+ onStateChange(handler) {
28934
+ this.stateListeners.add(handler);
28935
+ return () => {
28936
+ this.stateListeners.delete(handler);
28937
+ };
28938
+ }
28939
+ // ---- Internal ----
28940
+ send(frame) {
28941
+ if (this.ws?.readyState === WebSocket.OPEN) {
28942
+ this.ws.send(JSON.stringify(frame));
28943
+ }
28944
+ }
28945
+ handleFrame(frame) {
28946
+ this.lastReceivedAt = Date.now();
28947
+ this.clearProbe();
28948
+ if (frame.seq !== void 0) {
28949
+ this.lastSeq = frame.seq;
28950
+ }
28951
+ if (frame.type === WS_EVENTS.HELLO) {
28952
+ const interval = frame.data.heartbeat_interval;
28953
+ this.startHeartbeat(interval);
28954
+ }
28955
+ const handlers = this.listeners.get(frame.type);
28956
+ if (handlers) {
28957
+ for (const handler of handlers) {
28958
+ handler(frame.data, frame.seq);
28959
+ }
28960
+ }
28961
+ }
28962
+ startHeartbeat(intervalSec) {
28963
+ this.stopHeartbeat();
28964
+ if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
28965
+ console.error("Invalid heartbeat interval from server:", intervalSec);
28966
+ return;
28967
+ }
28968
+ this.heartbeatIntervalMs = intervalSec * 1e3;
28969
+ this.heartbeatTimer = setInterval(() => {
28970
+ if (this.lastReceivedAt > 0 && Date.now() - this.lastReceivedAt > this.heartbeatIntervalMs * 1.5) {
28971
+ this.probeConnection();
28972
+ return;
28973
+ }
28974
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
28975
+ }, intervalSec * 1e3);
28976
+ }
28977
+ stopHeartbeat() {
28978
+ if (this.heartbeatTimer) {
28979
+ clearInterval(this.heartbeatTimer);
28980
+ this.heartbeatTimer = null;
28981
+ }
28982
+ }
28983
+ scheduleReconnect() {
28984
+ this.setState("reconnecting");
28985
+ this.clearReconnect();
28986
+ const base = Math.min(this.options.reconnectInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
28987
+ const delay = base * (0.5 + Math.random() * 0.5);
28988
+ this.reconnectAttempts++;
28989
+ this.reconnectTimer = setTimeout(() => {
28990
+ this.connect();
28991
+ }, delay);
28992
+ }
28993
+ clearReconnect() {
28994
+ if (this.reconnectTimer) {
28995
+ clearTimeout(this.reconnectTimer);
28996
+ this.reconnectTimer = null;
28997
+ }
28998
+ }
28999
+ /** Force-close a dead/stale connection and trigger reconnect. */
29000
+ forceReconnect() {
29001
+ this.stopHeartbeat();
29002
+ this.clearReconnect();
29003
+ this.clearProbe();
29004
+ if (this.ws) {
29005
+ this.ws.onclose = null;
29006
+ this.ws.onopen = null;
29007
+ this.ws.onerror = null;
29008
+ this.ws.onmessage = null;
29009
+ try {
29010
+ this.ws.close();
29011
+ } catch {
29012
+ }
29013
+ this.ws = null;
29014
+ }
29015
+ if (this.options.reconnect && !this.intentionalClose) {
29016
+ this.scheduleReconnect();
29017
+ } else {
29018
+ this.setState("disconnected");
29019
+ }
29020
+ }
29021
+ // ---- Browser event listeners for proactive reconnection ----
29022
+ setupBrowserListeners() {
29023
+ if (this.browserListenersActive)
29024
+ return;
29025
+ this.browserListenersActive = true;
29026
+ if (typeof document !== "undefined") {
29027
+ document.addEventListener("visibilitychange", this.handleVisibilityChange);
29028
+ }
29029
+ if (typeof window !== "undefined") {
29030
+ window.addEventListener("online", this.handleOnline);
29031
+ }
29032
+ }
29033
+ teardownBrowserListeners() {
29034
+ if (!this.browserListenersActive)
29035
+ return;
29036
+ this.browserListenersActive = false;
29037
+ if (typeof document !== "undefined") {
29038
+ document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29039
+ }
29040
+ if (typeof window !== "undefined") {
29041
+ window.removeEventListener("online", this.handleOnline);
29042
+ }
29043
+ }
29044
+ /**
29045
+ * Send a ping and arm a short timeout. If no frame arrives within 5s the
29046
+ * connection is assumed dead and force-reconnected. Any received frame
29047
+ * (including the pong) cancels the timer via clearProbe() in handleFrame.
29048
+ */
29049
+ probeConnection() {
29050
+ if (this.probeTimer)
29051
+ return;
29052
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29053
+ this.probeTimer = setTimeout(() => {
29054
+ this.forceReconnect();
29055
+ }, 5e3);
29056
+ }
29057
+ clearProbe() {
29058
+ if (this.probeTimer) {
29059
+ clearTimeout(this.probeTimer);
29060
+ this.probeTimer = null;
29061
+ }
29062
+ }
29063
+ /** Tab returned to foreground — verify connection or accelerate reconnect. */
29064
+ handleVisibilityChange = () => {
29065
+ if (typeof document !== "undefined" && document.hidden)
29066
+ return;
29067
+ if (this._state === "connected") {
29068
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29069
+ this.forceReconnect();
29512
29070
  } else {
29513
- console.error("Failed to get WS ticket:", err);
29071
+ this.probeConnection();
29514
29072
  }
29515
- if (this.options.reconnect) {
29516
- this.scheduleReconnect();
29073
+ } else if (this._state === "reconnecting") {
29074
+ this.clearReconnect();
29075
+ this.reconnectAttempts = 0;
29076
+ this.connect();
29077
+ }
29078
+ };
29079
+ /** Network restored — accelerate reconnection. */
29080
+ handleOnline = () => {
29081
+ if (this.intentionalClose)
29082
+ return;
29083
+ if (this._state === "connected") {
29084
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29085
+ this.forceReconnect();
29517
29086
  } else {
29518
- this.setState("disconnected");
29087
+ this.probeConnection();
29519
29088
  }
29520
- return;
29089
+ } else if (this._state === "reconnecting") {
29090
+ this.clearReconnect();
29091
+ this.reconnectAttempts = 0;
29092
+ this.connect();
29521
29093
  }
29522
- const wsUrl = ticket.ws_url || this.options.wsUrl;
29523
- if (!wsUrl) {
29524
- console.error("No WS URL available");
29525
- this.setState("disconnected");
29526
- return;
29094
+ };
29095
+ setState(state) {
29096
+ this._state = state;
29097
+ for (const listener of this.stateListeners) {
29098
+ listener(state);
29527
29099
  }
29528
- const url = new URL(wsUrl);
29529
- url.searchParams.set("ticket", ticket.ticket);
29530
- if (this.lastSeq > 0) {
29531
- url.searchParams.set("last_seq", String(this.lastSeq));
29100
+ }
29101
+ };
29102
+
29103
+ // ts/agent-core/dist/lane-ledger.js
29104
+ var LedgerUnsupportedError = class extends Error {
29105
+ };
29106
+ function isStaleLane(err) {
29107
+ return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
29108
+ }
29109
+ function isEndpointMissing(err) {
29110
+ return err instanceof ApiError && err.status === 404 && !err.code;
29111
+ }
29112
+ var LaneLedger = class {
29113
+ opts;
29114
+ lanes = /* @__PURE__ */ new Map();
29115
+ constructor(opts) {
29116
+ this.opts = opts;
29117
+ }
29118
+ get contextDir() {
29119
+ return this.opts.contextDir;
29120
+ }
29121
+ /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
29122
+ handles(event) {
29123
+ return event.type === "message" && event.targetId.startsWith("cht_");
29124
+ }
29125
+ laneKeyFor(event) {
29126
+ if (event.type !== "message" && event.dispatchEventId) {
29127
+ return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29532
29128
  }
29533
- this.ws = new WebSocket(url.toString());
29534
- const ws = this.ws;
29535
- const connectTimeout = setTimeout(() => {
29536
- if (this._state === "connected" || this.intentionalClose)
29537
- return;
29538
- ws.onclose = null;
29539
- ws.onopen = null;
29540
- ws.onerror = null;
29129
+ return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29130
+ }
29131
+ getForEvent(event) {
29132
+ return this.lanes.get(this.laneKeyFor(event));
29133
+ }
29134
+ laneContextPath(lane) {
29135
+ return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29136
+ }
29137
+ /**
29138
+ * Claim (or reuse) the lane for a group of same-lane message events and
29139
+ * fold every group member into it. Returns 'foreign' when a healthy
29140
+ * incumbent (another pod) holds the resource — the caller must not
29141
+ * dispatch; the events stay pending server-side and re-drive after the
29142
+ * incumbent completes.
29143
+ */
29144
+ async ensureLane(events) {
29145
+ const trigger = events[events.length - 1];
29146
+ const laneKey = this.laneKeyFor(trigger);
29147
+ let lane = this.lanes.get(laneKey);
29148
+ if (!lane) {
29149
+ const targetUri = `prll://${trigger.targetId}`;
29150
+ let res;
29541
29151
  try {
29542
- ws.close();
29543
- } catch {
29152
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29153
+ target_uri: targetUri,
29154
+ thread_root_id: trigger.threadRootId,
29155
+ limit: 100
29156
+ });
29157
+ } catch (err) {
29158
+ if (isEndpointMissing(err))
29159
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29160
+ throw err;
29544
29161
  }
29545
- if (ws !== this.ws)
29546
- return;
29547
- if (this.options.reconnect) {
29548
- this.scheduleReconnect();
29549
- } else {
29550
- this.setState("disconnected");
29162
+ if (!res.claimed || !res.lane) {
29163
+ if (res.reason === "empty") {
29164
+ this.opts.log?.warn(`claim for ${targetUri} came back empty \u2014 nothing foldable; leaving to the reconciler`);
29165
+ } else {
29166
+ this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
29167
+ }
29168
+ return null;
29551
29169
  }
29552
- }, 15e3);
29553
- this.ws.onopen = () => {
29554
- clearTimeout(connectTimeout);
29555
- this.reconnectAttempts = 0;
29556
- this.lastReceivedAt = Date.now();
29557
- this.setState("connected");
29558
- };
29559
- this.ws.onmessage = (event) => {
29560
- try {
29561
- const frame = JSON.parse(event.data);
29562
- this.handleFrame(frame);
29563
- } catch {
29170
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29171
+ lane = {
29172
+ laneKey,
29173
+ lane: res.lane,
29174
+ targetUri,
29175
+ threadRootId: trigger.threadRootId,
29176
+ folded: /* @__PURE__ */ new Map(),
29177
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29178
+ };
29179
+ for (const ev of res.events ?? []) {
29180
+ lane.folded.set(ev.source_id, ev.id);
29564
29181
  }
29565
- };
29566
- this.ws.onclose = () => {
29567
- clearTimeout(connectTimeout);
29568
- this.stopHeartbeat();
29569
- this.clearProbe();
29570
- if (this.intentionalClose) {
29571
- this.setState("disconnected");
29572
- return;
29182
+ this.lanes.set(laneKey, lane);
29183
+ }
29184
+ for (const ev of events) {
29185
+ if (lane.folded.has(ev.messageId))
29186
+ continue;
29187
+ try {
29188
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29189
+ lane: lane.lane,
29190
+ target_uri: lane.targetUri,
29191
+ thread_root_id: lane.threadRootId,
29192
+ ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
29193
+ });
29194
+ lane.folded.set(ev.messageId, res.dispatch_event_id);
29195
+ } catch (err) {
29196
+ if (isStaleLane(err)) {
29197
+ this.lanes.delete(laneKey);
29198
+ return null;
29199
+ }
29200
+ this.opts.log?.warn(`steer fold failed for ${ev.messageId} \u2014 failing closed, releasing lane: ${String(err)}`);
29201
+ await this.release(laneKey);
29202
+ return null;
29573
29203
  }
29574
- if (this.options.reconnect) {
29575
- this.scheduleReconnect();
29204
+ }
29205
+ return lane;
29206
+ }
29207
+ /**
29208
+ * Fold a live mid-turn message into its active lane BEFORE injecting it
29209
+ * into the running turn. Injection without a successful fold is forbidden —
29210
+ * an un-folded injected message would be re-driven after complete and the
29211
+ * model would handle it twice.
29212
+ */
29213
+ async steerLive(event) {
29214
+ const laneKey = this.laneKeyFor(event);
29215
+ const lane = this.lanes.get(laneKey);
29216
+ if (!lane)
29217
+ return false;
29218
+ if (lane.folded.has(event.messageId))
29219
+ return true;
29220
+ try {
29221
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29222
+ lane: lane.lane,
29223
+ target_uri: lane.targetUri,
29224
+ thread_root_id: lane.threadRootId,
29225
+ ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
29226
+ });
29227
+ lane.folded.set(event.messageId, res.dispatch_event_id);
29228
+ return true;
29229
+ } catch (err) {
29230
+ if (isStaleLane(err)) {
29231
+ this.lanes.delete(laneKey);
29576
29232
  } else {
29577
- this.setState("disconnected");
29233
+ this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
29578
29234
  }
29579
- };
29580
- this.ws.onerror = () => {
29581
- };
29235
+ return false;
29236
+ }
29582
29237
  }
29583
- disconnect() {
29584
- this.intentionalClose = true;
29585
- this.stopHeartbeat();
29586
- this.clearReconnect();
29587
- this.clearProbe();
29588
- this.teardownBrowserListeners();
29589
- if (this.ws) {
29590
- this.ws.close();
29591
- this.ws = null;
29238
+ /**
29239
+ * Complete the lane when no local work remains for it: the server sweeps
29240
+ * still-leased members as no_action, releases the occupancy row, and
29241
+ * re-drives any same-target pending work. A STALE_LANE answer means a
29242
+ * takeover already owns the resource — local state is dropped either way.
29243
+ */
29244
+ /**
29245
+ * Record that the turn on this lane surfaced a runtime error. The flow
29246
+ * settles an errored lane immediately (dispatchLaneGroup returns 'failed'
29247
+ * after a forced complete), so the bit normally lives for one turn only —
29248
+ * it is the transport between the gateway's per-session error signal and
29249
+ * this lane's complete request.
29250
+ */
29251
+ markTurnError(laneKey) {
29252
+ const lane = this.lanes.get(laneKey);
29253
+ if (lane)
29254
+ lane.turnError = true;
29255
+ }
29256
+ async completeIfIdle(laneKey, hasMoreLocal) {
29257
+ const lane = this.lanes.get(laneKey);
29258
+ if (!lane || hasMoreLocal)
29259
+ return;
29260
+ this.lanes.delete(laneKey);
29261
+ this.removeLaneContext(lane);
29262
+ try {
29263
+ const res = await this.opts.client.completeDispatch(this.opts.orgId, {
29264
+ lane: lane.lane,
29265
+ target_uri: lane.targetUri,
29266
+ thread_root_id: lane.threadRootId,
29267
+ // An error turn releases its members for retry instead of sweeping
29268
+ // them as handled (ignored by older servers).
29269
+ turn_outcome: lane.turnError ? "error" : "ok"
29270
+ });
29271
+ if (res.swept_no_action > 0 || res.redriven) {
29272
+ this.opts.log?.info(`lane complete for ${lane.targetUri}: swept ${res.swept_no_action} no_action, redriven=${res.redriven}`);
29273
+ }
29274
+ } catch (err) {
29275
+ if (isStaleLane(err)) {
29276
+ this.opts.log?.info(`lane complete skipped for ${lane.targetUri} \u2014 taken over`);
29277
+ return;
29278
+ }
29279
+ this.opts.log?.warn(`lane complete failed for ${lane.targetUri}: ${String(err)}`);
29592
29280
  }
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 } });
29599
29281
  }
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
- });
29282
+ /**
29283
+ * Renew one lane by its key — the external runtime-activity hook for
29284
+ * adapters whose tool traffic bypasses the RuntimeEvent stream (openclaw
29285
+ * hooks). Scoped to the session's own lane: renewing every lane would let
29286
+ * one busy fork keep an unrelated stalled fork's lane leased forever.
29287
+ */
29288
+ renewByKey(laneKey) {
29289
+ const lane = this.lanes.get(laneKey);
29290
+ if (lane)
29291
+ this.maybeRenew(lane);
29605
29292
  }
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 }
29293
+ /**
29294
+ * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
29295
+ * so a chatty turn doesn't spam the server. Without this, a legitimately
29296
+ * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
29297
+ * write misfired with STALE_LANE — the design doc's "long turns renew via
29298
+ * step writes". Fire-and-forget: a failed renewal is surfaced by the next
29299
+ * write's incumbency check anyway.
29300
+ */
29301
+ maybeRenew(lane) {
29302
+ const now = Date.now();
29303
+ const ttl = lane.leaseTtlMs ?? 10 * 6e4;
29304
+ const until = lane.leaseUntilMs ?? now;
29305
+ if (until - now > ttl / 2)
29306
+ return;
29307
+ lane.leaseUntilMs = now + ttl;
29308
+ void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
29309
+ lane: lane.lane,
29310
+ target_uri: lane.targetUri,
29311
+ thread_root_id: lane.threadRootId
29312
+ }).then((res) => {
29313
+ const until2 = Date.parse(res?.lease_until ?? "");
29314
+ if (!Number.isNaN(until2))
29315
+ lane.leaseUntilMs = until2;
29316
+ }).catch((err) => {
29317
+ if (isStaleLane(err)) {
29318
+ this.lanes.delete(lane.laneKey);
29319
+ this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
29320
+ return;
29321
+ }
29322
+ this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
29611
29323
  });
29612
29324
  }
29613
- sendEvent(type, data) {
29614
- this.send({ type, data });
29615
- }
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);
29325
+ /**
29326
+ * Release a lane's unresolved members back to pending (dispatch error /
29327
+ * shutdown) so the next pod re-claims immediately instead of waiting out
29328
+ * the lease.
29329
+ */
29330
+ async release(laneKey) {
29331
+ const lane = this.lanes.get(laneKey);
29332
+ if (!lane)
29333
+ return;
29334
+ this.lanes.delete(laneKey);
29335
+ this.removeLaneContext(lane);
29336
+ try {
29337
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane);
29338
+ } catch (err) {
29339
+ this.opts.log?.warn(`lane release failed for ${lane.targetUri}: ${String(err)}`);
29622
29340
  }
29623
- set.add(handler);
29624
- return () => {
29625
- set.delete(handler);
29626
- };
29627
29341
  }
29628
- off(event, handler) {
29629
- this.listeners.get(event)?.delete(handler);
29342
+ async releaseAll() {
29343
+ const keys = [...this.lanes.keys()];
29344
+ for (const key of keys) {
29345
+ await this.release(key);
29346
+ }
29630
29347
  }
29631
- onStateChange(handler) {
29632
- this.stateListeners.add(handler);
29633
- return () => {
29634
- this.stateListeners.delete(handler);
29635
- };
29348
+ /** True when any lane is currently active (used by shutdown logging). */
29349
+ get activeCount() {
29350
+ return this.lanes.size;
29636
29351
  }
29637
- // ---- Internal ----
29638
- send(frame) {
29639
- if (this.ws?.readyState === WebSocket.OPEN) {
29640
- this.ws.send(JSON.stringify(frame));
29352
+ /**
29353
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
29354
+ * by WorkItem id or by source identity (the live task.assigned event has no
29355
+ * WorkItem id). Returns null when a healthy incumbent (another pod) holds
29356
+ * it or the WorkItem is already resolved — the caller must skip processing.
29357
+ */
29358
+ async claimTyped(ref) {
29359
+ let res;
29360
+ try {
29361
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29362
+ dispatch_event_id: ref.dispatchEventId,
29363
+ source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
29364
+ source_id: ref.dispatchEventId ? void 0 : ref.sourceId
29365
+ });
29366
+ } catch (err) {
29367
+ if (isEndpointMissing(err))
29368
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29369
+ throw err;
29641
29370
  }
29371
+ if (!res.claimed || !res.lane || !res.events?.length)
29372
+ return null;
29373
+ const workItem = res.events[0];
29374
+ const targetUri = `dsp:${workItem.id}`;
29375
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29376
+ const lane = {
29377
+ laneKey: laneKeyForTarget(targetUri),
29378
+ lane: res.lane,
29379
+ targetUri,
29380
+ folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
29381
+ typedDispatchEventId: workItem.id,
29382
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29383
+ };
29384
+ this.lanes.set(lane.laneKey, lane);
29385
+ return lane;
29642
29386
  }
29643
- handleFrame(frame) {
29644
- this.lastReceivedAt = Date.now();
29645
- this.clearProbe();
29646
- if (frame.seq !== void 0) {
29647
- this.lastSeq = frame.seq;
29648
- }
29649
- if (frame.type === WS_EVENTS.HELLO) {
29650
- const interval = frame.data.heartbeat_interval;
29651
- this.startHeartbeat(interval);
29652
- }
29653
- const handlers = this.listeners.get(frame.type);
29654
- if (handlers) {
29655
- for (const handler of handlers) {
29656
- handler(frame.data, frame.seq);
29387
+ /**
29388
+ * Remove the per-lane context file (and its CLI sidecar) when the lane
29389
+ * ends. A leftover file would make a later cross-context send to the same
29390
+ * target bind a dead lane token and misfire with STALE_LANE instead of
29391
+ * taking the plain non-ledger path.
29392
+ */
29393
+ removeLaneContext(lane) {
29394
+ const contextPath = this.laneContextPath(lane);
29395
+ for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
29396
+ try {
29397
+ fs.rmSync(p, { force: true });
29398
+ } catch {
29657
29399
  }
29658
29400
  }
29659
29401
  }
29660
- startHeartbeat(intervalSec) {
29661
- this.stopHeartbeat();
29662
- if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
29663
- console.error("Invalid heartbeat interval from server:", intervalSec);
29664
- return;
29402
+ };
29403
+
29404
+ // ts/agent-core/dist/gateway-lane-flow.js
29405
+ async function dispatchLaneGroup(host, opts) {
29406
+ const ledger = host.laneLedger;
29407
+ const event = opts.events[opts.events.length - 1];
29408
+ let lane;
29409
+ try {
29410
+ lane = await ledger.ensureLane(opts.events);
29411
+ } catch (err) {
29412
+ if (!(err instanceof LedgerUnsupportedError))
29413
+ throw err;
29414
+ host.disableLedger("claim endpoint missing");
29415
+ await host.emitDispatchReceived(event);
29416
+ const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29417
+ if (!dispatched2)
29418
+ return "shutdown";
29419
+ for (const ev of opts.events) {
29420
+ host.opts.client.ackDispatch(host.opts.config.org_id, {
29421
+ source_type: ev.ackSourceType ?? "message",
29422
+ source_id: ev.ackSourceId ?? ev.messageId
29423
+ }).catch(() => {
29424
+ });
29665
29425
  }
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);
29426
+ return "dispatched";
29674
29427
  }
29675
- stopHeartbeat() {
29676
- if (this.heartbeatTimer) {
29677
- clearInterval(this.heartbeatTimer);
29678
- this.heartbeatTimer = null;
29428
+ if (!lane) {
29429
+ for (const ev of opts.events) {
29430
+ host.dispatchedMessages.delete(ev.messageId);
29679
29431
  }
29432
+ return "foreign";
29680
29433
  }
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);
29434
+ host.noteSessionLane(opts.sessionKey, lane.laneKey);
29435
+ let dispatched = false;
29436
+ try {
29437
+ dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29438
+ } catch (err) {
29439
+ host.noteSessionLane(opts.sessionKey, null);
29440
+ await ledger.release(lane.laneKey).catch(() => {
29441
+ });
29442
+ throw err;
29443
+ } finally {
29444
+ if (dispatched)
29445
+ host.noteSessionLane(opts.sessionKey, null);
29690
29446
  }
29691
- clearReconnect() {
29692
- if (this.reconnectTimer) {
29693
- clearTimeout(this.reconnectTimer);
29694
- this.reconnectTimer = null;
29695
- }
29447
+ if (!dispatched) {
29448
+ return "shutdown";
29696
29449
  }
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;
29707
- try {
29708
- this.ws.close();
29709
- } catch {
29710
- }
29711
- this.ws = null;
29450
+ if (host.consumeTurnError(opts.sessionKey)) {
29451
+ ledger.markTurnError(lane.laneKey);
29452
+ for (const msgId of lane.folded.keys()) {
29453
+ host.dispatchedMessages.delete(msgId);
29712
29454
  }
29713
- if (this.options.reconnect && !this.intentionalClose) {
29714
- this.scheduleReconnect();
29715
- } else {
29716
- this.setState("disconnected");
29455
+ try {
29456
+ host.opts.dispatchAdapter.abortDispatch?.(opts.sessionKey);
29457
+ } catch {
29717
29458
  }
29459
+ await ledger.completeIfIdle(lane.laneKey, false);
29460
+ return "failed";
29718
29461
  }
29719
- // ---- Browser event listeners for proactive reconnection ----
29720
- setupBrowserListeners() {
29721
- if (this.browserListenersActive)
29462
+ const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
29463
+ await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
29464
+ return "dispatched";
29465
+ }
29466
+ var TYPED_BACKOFF_BASE_MS = 2e3;
29467
+ var TYPED_BACKOFF_CAP_MS = 5 * 6e4;
29468
+ var TYPED_BACKOFF_MAP_CAP = 512;
29469
+ async function consumeTypedDispatch(host, ref, run, ack) {
29470
+ const backoffKey = ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`;
29471
+ const armed = host.typedRedriveBackoff.get(backoffKey);
29472
+ if (armed) {
29473
+ const waitMs = armed.until - Date.now();
29474
+ if (waitMs > 0) {
29475
+ host.opts.log?.info(`typed dispatch ${backoffKey} backing off ${Math.ceil(waitMs / 1e3)}s after ${armed.failures} failed consume(s)`);
29476
+ await new Promise((resolve3) => {
29477
+ const timer = setTimeout(resolve3, waitMs);
29478
+ timer.unref?.();
29479
+ });
29480
+ }
29481
+ if (host.shuttingDown)
29482
+ return;
29483
+ }
29484
+ const settleAck = (ackResult) => ackResult !== false;
29485
+ const settle = (acked2) => {
29486
+ if (acked2) {
29487
+ host.typedRedriveBackoff.delete(backoffKey);
29722
29488
  return;
29723
- this.browserListenersActive = true;
29724
- if (typeof document !== "undefined") {
29725
- document.addEventListener("visibilitychange", this.handleVisibilityChange);
29726
29489
  }
29727
- if (typeof window !== "undefined") {
29728
- window.addEventListener("online", this.handleOnline);
29490
+ const failures = (host.typedRedriveBackoff.get(backoffKey)?.failures ?? 0) + 1;
29491
+ const backoffMs = Math.min(TYPED_BACKOFF_CAP_MS, TYPED_BACKOFF_BASE_MS * 2 ** (failures - 1));
29492
+ if (host.typedRedriveBackoff.delete(backoffKey) === false && host.typedRedriveBackoff.size >= TYPED_BACKOFF_MAP_CAP) {
29493
+ const oldest = host.typedRedriveBackoff.keys().next().value;
29494
+ if (oldest !== void 0)
29495
+ host.typedRedriveBackoff.delete(oldest);
29496
+ }
29497
+ host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
29498
+ };
29499
+ const runLegacy = async () => {
29500
+ let acked2 = false;
29501
+ try {
29502
+ if (await run(ref.dispatchEventId)) {
29503
+ acked2 = settleAck(await ack(ref.dispatchEventId));
29504
+ }
29505
+ } finally {
29506
+ settle(acked2);
29729
29507
  }
29508
+ };
29509
+ if (!host.laneLedger || host.ledgerDisabled) {
29510
+ await runLegacy();
29511
+ return;
29730
29512
  }
29731
- teardownBrowserListeners() {
29732
- if (!this.browserListenersActive)
29513
+ let lane;
29514
+ try {
29515
+ lane = await host.laneLedger.claimTyped(ref);
29516
+ } catch (err) {
29517
+ if (err instanceof LedgerUnsupportedError) {
29518
+ host.disableLedger("claim endpoint missing");
29519
+ await runLegacy();
29733
29520
  return;
29734
- this.browserListenersActive = false;
29735
- if (typeof document !== "undefined") {
29736
- document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29737
29521
  }
29738
- if (typeof window !== "undefined") {
29739
- window.removeEventListener("online", this.handleOnline);
29522
+ throw err;
29523
+ }
29524
+ if (!lane) {
29525
+ host.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} not claimable (held elsewhere or already resolved) \u2014 skipping`);
29526
+ return;
29527
+ }
29528
+ let acked = false;
29529
+ try {
29530
+ if (await run(lane.typedDispatchEventId)) {
29531
+ acked = settleAck(await ack(lane.typedDispatchEventId));
29740
29532
  }
29533
+ } finally {
29534
+ settle(acked);
29535
+ await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
29536
+ });
29741
29537
  }
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)
29538
+ }
29539
+ async function consumeMessageWorkItem(host, item) {
29540
+ if (host.shuttingDown)
29541
+ return;
29542
+ if (!host.tryClaimMessage(item.source_id))
29543
+ return;
29544
+ const ackItem = () => {
29545
+ host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
29546
+ });
29547
+ };
29548
+ let msg = null;
29549
+ try {
29550
+ msg = await host.opts.client.getMessage(item.source_id);
29551
+ } catch (err) {
29552
+ const status = err?.status;
29553
+ if (status !== 404) {
29554
+ host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
29555
+ host.dispatchedMessages.delete(item.source_id);
29749
29556
  return;
29750
- this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29751
- this.probeTimer = setTimeout(() => {
29752
- this.forceReconnect();
29753
- }, 5e3);
29557
+ }
29754
29558
  }
29755
- clearProbe() {
29756
- if (this.probeTimer) {
29757
- clearTimeout(this.probeTimer);
29758
- this.probeTimer = null;
29559
+ if (!msg || msg.sender_id === host.opts.agentUserId) {
29560
+ host.dispatchedMessages.delete(item.source_id);
29561
+ ackItem();
29562
+ return;
29563
+ }
29564
+ const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
29565
+ if (decision.action === "retry") {
29566
+ host.dispatchedMessages.delete(item.source_id);
29567
+ return;
29568
+ }
29569
+ if (decision.action === "skip") {
29570
+ host.dispatchedMessages.delete(item.source_id);
29571
+ ackItem();
29572
+ return;
29573
+ }
29574
+ decision.event.dispatchEventId = item.id;
29575
+ const laneResolved = host.usesLaneLedger(decision.event);
29576
+ try {
29577
+ const dispatched = await host.handleInboundEvent(decision.event);
29578
+ if (dispatched) {
29579
+ if (!laneResolved)
29580
+ ackItem();
29581
+ } else {
29582
+ host.dispatchedMessages.delete(item.source_id);
29759
29583
  }
29584
+ } catch (err) {
29585
+ host.dispatchedMessages.delete(item.source_id);
29586
+ throw err;
29760
29587
  }
29761
- /** Tab returned to foreground — verify connection or accelerate reconnect. */
29762
- handleVisibilityChange = () => {
29763
- if (typeof document !== "undefined" && document.hidden)
29764
- return;
29765
- if (this._state === "connected") {
29766
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29767
- this.forceReconnect();
29768
- } else {
29769
- this.probeConnection();
29770
- }
29771
- } else if (this._state === "reconnecting") {
29772
- this.clearReconnect();
29773
- this.reconnectAttempts = 0;
29774
- this.connect();
29588
+ }
29589
+
29590
+ // ts/agent-core/dist/session-state.js
29591
+ function normalizeSessionKey(sessionKey) {
29592
+ return sessionKey.toLowerCase();
29593
+ }
29594
+ var sessionChatIdMap = /* @__PURE__ */ new Map();
29595
+ var sessionMessageIdMap = /* @__PURE__ */ new Map();
29596
+ var dispatchMessageIdMap = /* @__PURE__ */ new Map();
29597
+ var dispatchNoReplyMap = /* @__PURE__ */ new Map();
29598
+ function setSessionChatId(sessionKey, chatId) {
29599
+ sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
29600
+ }
29601
+ function setSessionMessageId(sessionKey, messageId) {
29602
+ sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29603
+ }
29604
+ function clearSessionMessageId(sessionKey) {
29605
+ sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
29606
+ }
29607
+ function setDispatchMessageId(sessionKey, messageId) {
29608
+ dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29609
+ }
29610
+ function clearDispatchMessageId(sessionKey) {
29611
+ dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
29612
+ }
29613
+ function setDispatchNoReply(sessionKey, noReply) {
29614
+ dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
29615
+ }
29616
+ function clearDispatchNoReply(sessionKey) {
29617
+ dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
29618
+ }
29619
+ var dispatchMetricsMap = /* @__PURE__ */ new Map();
29620
+ function resetDispatchMetrics(sessionKey) {
29621
+ dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
29622
+ deliver_text_chunks: 0,
29623
+ deliver_text_chars: 0,
29624
+ message_send_attempts: 0,
29625
+ message_send_successes: 0,
29626
+ no_reply_called: false,
29627
+ tool_call_count: 0,
29628
+ started_at: Date.now()
29629
+ });
29630
+ }
29631
+ function getDispatchMetrics(sessionKey) {
29632
+ return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29633
+ }
29634
+ function clearDispatchMetrics(sessionKey) {
29635
+ dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
29636
+ }
29637
+ function recordDeliverText(sessionKey, charCount) {
29638
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29639
+ if (!m)
29640
+ return;
29641
+ m.deliver_text_chunks++;
29642
+ m.deliver_text_chars += charCount;
29643
+ }
29644
+ function recordMessageSend(sessionKey, success) {
29645
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29646
+ if (!m)
29647
+ return;
29648
+ m.message_send_attempts++;
29649
+ if (success)
29650
+ m.message_send_successes++;
29651
+ }
29652
+ function recordNoReply(sessionKey) {
29653
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29654
+ if (!m)
29655
+ return;
29656
+ m.no_reply_called = true;
29657
+ }
29658
+ function recordToolCall(sessionKey) {
29659
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29660
+ if (!m)
29661
+ return;
29662
+ m.tool_call_count++;
29663
+ }
29664
+
29665
+ // ts/agent-core/dist/routing.js
29666
+ var MAX_CONCURRENT_FORKS = 20;
29667
+ var defaultRoutingStrategy = (event, state) => {
29668
+ if (state.mainCurrentTargetId === event.targetId) {
29669
+ return { action: "buffer-main" };
29670
+ }
29671
+ const existingForkKey = state.activeForks.get(event.targetId);
29672
+ if (existingForkKey)
29673
+ return { action: "buffer-fork", forkKey: existingForkKey };
29674
+ if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
29675
+ return { action: "buffer-main" };
29676
+ }
29677
+ return { action: "new-fork" };
29678
+ };
29679
+ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
29680
+ const existingForkKey = state.activeForks.get(event.targetId);
29681
+ if (existingForkKey)
29682
+ return { action: "buffer-fork", forkKey: existingForkKey };
29683
+ if (!state.mainDispatching)
29684
+ return { action: "main" };
29685
+ return strategy(event, state);
29686
+ }
29687
+
29688
+ // ts/agent-core/dist/event-format.js
29689
+ function sanitizeMeta(value) {
29690
+ return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
29691
+ }
29692
+ function buildEventBody(event) {
29693
+ const lines = [];
29694
+ if (event.type === "message") {
29695
+ lines.push(`[Event: message.new]`);
29696
+ const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29697
+ lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
29698
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29699
+ lines.push(`[Message ID: prll://${event.messageId}]`);
29700
+ if (event.threadRootId) {
29701
+ const threadMeta = [
29702
+ `prll://${event.threadRootId}`,
29703
+ event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
29704
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
29705
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
29706
+ ].filter(Boolean).join(" | ");
29707
+ lines.push(`[Thread: ${threadMeta}]`);
29775
29708
  }
29776
- };
29777
- /** Network restored accelerate reconnection. */
29778
- handleOnline = () => {
29779
- if (this.intentionalClose)
29780
- return;
29781
- if (this._state === "connected") {
29782
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29783
- this.forceReconnect();
29784
- } else {
29785
- this.probeConnection();
29709
+ if (event.unreadCount != null && event.unreadCount > 1) {
29710
+ const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
29711
+ const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
29712
+ let line = `[Unread: ${countStr} messages${sinceStr}]`;
29713
+ if (event.unreadCount > 50)
29714
+ line += ` \u2014 fetch recent context with --limit, not all`;
29715
+ lines.push(line);
29716
+ }
29717
+ if (event.noReply)
29718
+ lines.push(`[Hint: no_reply]`);
29719
+ if (event.attachments?.length) {
29720
+ for (const att of event.attachments) {
29721
+ const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
29722
+ lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
29786
29723
  }
29787
- } else if (this._state === "reconnecting") {
29788
- this.clearReconnect();
29789
- this.reconnectAttempts = 0;
29790
- this.connect();
29791
29724
  }
29792
- };
29793
- setState(state) {
29794
- this._state = state;
29795
- for (const listener of this.stateListeners) {
29796
- listener(state);
29725
+ lines.push("", event.body);
29726
+ } else if (event.type === "task_comment") {
29727
+ lines.push(`[Event: task.comment.created]`);
29728
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29729
+ lines.push(`[Task: ${taskLabel}]`);
29730
+ if (event.deliveryReason)
29731
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29732
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29733
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29734
+ lines.push("", event.body);
29735
+ } else if (event.type === "wiki_comment") {
29736
+ lines.push(`[Event: wiki.comment.created]`);
29737
+ const target = event.replyTargetUri ?? `prll://${event.targetId}`;
29738
+ if (event.targetType === "changeset") {
29739
+ lines.push(`[Wiki Changeset: ${target}]`);
29740
+ } else {
29741
+ lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
29797
29742
  }
29798
- }
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;
29816
- }
29817
- get contextDir() {
29818
- return this.opts.contextDir;
29819
- }
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_");
29823
- }
29824
- laneKeyFor(event) {
29825
- if (event.type !== "message" && event.dispatchEventId) {
29826
- return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29743
+ if (event.deliveryReason)
29744
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29745
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29746
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29747
+ lines.push("", event.body);
29748
+ } else if (event.type === "approval") {
29749
+ lines.push(`[Event: approval.decided]`);
29750
+ lines.push(`[Approval: prll://${event.messageId}]`);
29751
+ lines.push(`[Chat: prll://${event.targetId}]`);
29752
+ lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
29753
+ lines.push("", event.body);
29754
+ } else if (event.type === "schedule") {
29755
+ lines.push(`[Event: schedule.fired]`);
29756
+ lines.push(`[Schedule: prll://${event.targetId}]`);
29757
+ lines.push(`[Run: prll://${event.messageId}]`);
29758
+ if (event.scheduledFireAt)
29759
+ lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
29760
+ if (event.attachedUri)
29761
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29762
+ lines.push("", event.body);
29763
+ } else if (event.type === "channel_message") {
29764
+ lines.push(`[Event: channel.message]`);
29765
+ const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
29766
+ const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
29767
+ lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
29768
+ lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
29769
+ if (event.channelExternalMessageId) {
29770
+ lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
29827
29771
  }
29828
- return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29829
- }
29830
- getForEvent(event) {
29831
- return this.lanes.get(this.laneKeyFor(event));
29832
- }
29833
- laneContextPath(lane) {
29834
- return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29835
- }
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);
29876
- }
29877
- this.lanes.set(laneKey, lane);
29772
+ 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.]`);
29773
+ lines.push("", event.body);
29774
+ } else if (event.type === "external_trigger") {
29775
+ lines.push(`[Event: external.trigger]`);
29776
+ lines.push(`[Trigger: prll://${event.targetId}]`);
29777
+ lines.push(`[Run: prll://${event.messageId}]`);
29778
+ if (event.externalConnectionId) {
29779
+ const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
29780
+ lines.push(`[Connection: ${label}]`);
29878
29781
  }
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
- }
29782
+ if (event.externalIngressEventId)
29783
+ lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
29784
+ if (event.attachedUri)
29785
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29786
+ if (event.externalConnectionSourceType) {
29787
+ lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
29899
29788
  }
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;
29789
+ if (event.externalIngressEventType) {
29790
+ lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
29931
29791
  }
29792
+ lines.push("", event.body);
29793
+ } else {
29794
+ lines.push(`[Event: task.assigned]`);
29795
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29796
+ lines.push(`[Task: ${taskLabel}]`);
29797
+ lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
29798
+ lines.push("", event.body);
29932
29799
  }
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)}`);
29800
+ return lines.join("\n") + buildSendMessageHint(event);
29801
+ }
29802
+ function buildEventBodyForForkResult(event) {
29803
+ return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
29804
+ }
29805
+ function buildSendMessageHint(event) {
29806
+ if (event.noReply)
29807
+ return "";
29808
+ if (event.type === "wiki_comment" && event.replyTargetUri) {
29809
+ const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
29810
+ return `
29811
+ <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>`;
29812
+ }
29813
+ if (event.targetId.startsWith("cht_")) {
29814
+ if (event.threadRootId) {
29815
+ return `
29816
+ <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>`;
29960
29817
  }
29818
+ return `
29819
+ <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>`;
29961
29820
  }
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
- });
29821
+ if (event.targetId.startsWith("tsk_")) {
29822
+ return `
29823
+ <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>`;
29993
29824
  }
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
- }
29825
+ if (event.targetId.startsWith("sch_")) {
29826
+ return `
29827
+ <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
30010
29828
  }
30011
- async releaseAll() {
30012
- const keys = [...this.lanes.keys()];
30013
- for (const key of keys) {
30014
- await this.release(key);
29829
+ if (event.type === "channel_message") {
29830
+ if (event.channelCliCapable) {
29831
+ const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
29832
+ const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
29833
+ return `
29834
+ <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>`;
30015
29835
  }
29836
+ const platform = event.channelProvider ?? "the external platform";
29837
+ return `
29838
+ <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>`;
30016
29839
  }
30017
- /** True when any lane is currently active (used by shutdown logging). */
30018
- get activeCount() {
30019
- return this.lanes.size;
29840
+ if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
29841
+ return `
29842
+ <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>`;
30020
29843
  }
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;
29844
+ return "";
29845
+ }
29846
+ function buildForkScopePrefix(event) {
29847
+ const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29848
+ 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.
29849
+
29850
+ 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.
29851
+
29852
+ End with a brief "Fork summary" of actions taken and decisions made.]
29853
+
29854
+ `;
29855
+ }
29856
+ function buildForkResultPrefix(results) {
29857
+ if (!results.length)
29858
+ return "";
29859
+ const blocks = results.map((result) => {
29860
+ const lines = [];
29861
+ for (const body of result.eventBodies) {
29862
+ lines.push(body);
30039
29863
  }
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;
30055
- }
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
- }
29864
+ lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
29865
+ 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."}]`);
29866
+ if (result.actions.length)
29867
+ lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
29868
+ if (result.historyPath)
29869
+ lines.push(`[Fork history: ${result.historyPath}]`);
29870
+ return lines.join("\n");
29871
+ });
29872
+ return blocks.join("\n\n") + "\n\n---\n\n";
29873
+ }
29874
+
29875
+ // ts/agent-core/dist/prompt-fragments.js
29876
+ var PRLL_IDENTITY_BASE = `## You on Parall
29877
+
29878
+ Parall is a shared workspace where humans and agents work side by side as equals.
29879
+ You are a participant here, not a service. You hold tasks, own decisions, and are
29880
+ accountable for the work you take on \u2014 the same way a human teammate is.
29881
+
29882
+ The people and agents around you are collaborators, not users to serve. Be honest,
29883
+ be direct, and care about the outcome of the work \u2014 not just the request in front
29884
+ of you.`;
29885
+ function sanitizeProfileField(value) {
29886
+ return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
29887
+ }
29888
+ function sanitizeProfileBlock(value) {
29889
+ return value.replace(/\r\n?/g, "\n").trim();
29890
+ }
29891
+ function buildIdentity(agent) {
29892
+ if (!agent)
29893
+ return PRLL_IDENTITY_BASE;
29894
+ const name = sanitizeProfileField(agent.displayName);
29895
+ const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
29896
+ lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
29897
+ if (agent.description) {
29898
+ const description = sanitizeProfileBlock(agent.description);
29899
+ if (description) {
29900
+ lines.push("", "### Your Agent Profile", "", description);
30069
29901
  }
30070
29902
  }
30071
- };
29903
+ lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
29904
+ return lines.join("\n");
29905
+ }
29906
+ var PRLL_BEHAVIOR = `## How to work here
29907
+
29908
+ ### Move work forward
29909
+ Don't wait for instructions. If you see the next step, take it. If something is
29910
+ ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
29911
+ \u2014 don't go silent. Initiative is expected.
29912
+
29913
+ Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
29914
+ requests, verifying something landed. When a thing needs future attention and
29915
+ nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
29916
+
29917
+ ### Work in the open
29918
+ Nothing you do exists until the system can see it. Your progress, decisions,
29919
+ blockers, and results need to live in tasks, comments, messages, or wiki pages
29920
+ \u2014 otherwise the organization is blind to your work, and so is the next agent
29921
+ who picks up where you left off. Leave traces as you go, not at the end.
29922
+
29923
+ For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
29924
+ when status materially changes, close it when done, and link the origin that
29925
+ triggered it. Decompose multi-step work into subtasks and keep their statuses
29926
+ current \u2014 progress should be auditable without watching the work happen.
29927
+ Details: load the \`parall-tasks\` skill.
29928
+
29929
+ ### Done means landed
29930
+ Producing output does not complete a task. Work counts as done only when it has
29931
+ cleared its remaining gates \u2014 review, merge, deployment, the requester's
29932
+ verification. Until then keep the status honest (\`in_progress\` or
29933
+ \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
29934
+ self-reminder if nothing else will prompt follow-up). Never mark done what a
29935
+ human still has to accept.
29936
+
29937
+ ### Sessions, forks, and what survives
29938
+ Sessions end and context compacts. Anything that must survive \u2014 decisions,
29939
+ progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
29940
+ read the workspace, not this conversation.
29941
+
29942
+ Some events are handled by parallel fork sessions \u2014 short-lived copies of the
29943
+ same agent identity with separate context. In a fork: leave a written trace of
29944
+ what was done or deliberately not done (other sessions cannot see fork
29945
+ context), and do not start long-running processes \u2014 they die with the fork.
29946
+ When an event is marked fork-handled: do not re-handle it; verify its outcome
29947
+ instead of assuming it.
29948
+
29949
+ ### Communicate like a teammate
29950
+ Match the conversation \u2014 concise in chat, thorough in docs, plain language over
29951
+ jargon. Say what matters; stop when you're done. Don't narrate every tool call
29952
+ or pad replies to seem thorough.
29953
+
29954
+ Match the language of the person you're replying to. If someone writes in
29955
+ Chinese, reply in Chinese. If in English, reply in English. Never force a
29956
+ language switch unless explicitly asked.
29957
+
29958
+ Do not promise delivery times ("in an hour", "by tonight") unless the work is
29959
+ driven by an explicit schedule. Scope visibly; report when actually done.
29960
+
29961
+ ### Keep topics in threads
29962
+ Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
29963
+ Present \u2192 that thread is the context; reply there, passing the same root as
29964
+ \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
29965
+ never treat it as continuing your most recent thread. The sender's newest
29966
+ message is the anchor \u2014 never route a reply back into an older thread just
29967
+ because the topic used to live there.
29968
+
29969
+ Reply where the event lives: a thread message gets a thread reply, a
29970
+ top-level message gets a top-level reply. But in group chats, your later
29971
+ follow-up on that topic \u2014 progress updates, analysis, links, verification you
29972
+ post afterwards \u2014 belongs in a thread rooted at the topic's message
29973
+ (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
29974
+ the main channel stays scannable. Post follow-up at top level only when
29975
+ starting a genuinely new topic, making a channel-wide announcement, or when
29976
+ explicitly asked. Never post the same update in both the thread and the main
29977
+ channel \u2014 thread replies surface in the thread panel; no need to duplicate
29978
+ for visibility.
29979
+
29980
+ In DMs, reply top-level by default; use a thread only to continue one that
29981
+ already exists.
30072
29982
 
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";
29983
+ ### Group chats: mentions and unaddressed work
29984
+ An @mention is a direct request \u2014 act on it. A group message delivered to you
29985
+ without an @mention means the chat's routing lets you see the conversation:
29986
+ decide whether a reply adds value; silence is the default.
29987
+
29988
+ A message without an @mention is not an open invitation. Judge from context
29989
+ who the work belongs to \u2014 the named domain, the topic's owner, whoever is
29990
+ already on it. If it belongs to someone else, leave it. If genuinely unclear,
29991
+ ask or claim in one line ("taking this unless someone else has it") before
29992
+ starting \u2014 asking first beats duplicated or misdirected work.
29993
+
29994
+ ### Verify before you act
29995
+ Events can be redelivered \u2014 before acting, check whether it was already
29996
+ handled (your own recent replies, task comments); if handled, do nothing.
29997
+ Sends can fail silently, and creates can error after succeeding server-side \u2014
29998
+ check the chat or entity before retrying. Never blind-retry a mutating call.
29999
+
30000
+ ### Gather the full picture first
30001
+ When a request is vague, an entity may already exist, or work may already be
30002
+ underway \u2014 gather context before acting: search (\`parall search "..."\`),
30003
+ check existing tasks/chats/wiki, read the surrounding conversation. Act on the
30004
+ full picture, not the fragment that arrived in the event.
30005
+
30006
+ ### Report only work that ran
30007
+ If a scheduled job, scan, or tool call did not actually run \u2014 restarted
30008
+ session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
30009
+ or approximate results of work that did not execute.
30010
+
30011
+ ### Respect what's shared
30012
+ You have broad latitude inside your own work. But actions that are visible to
30013
+ others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
30014
+ wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
30015
+ acting, unless you've been explicitly authorized.
30016
+
30017
+ ### Shared workspace
30018
+ Other agents share this workspace. Before starting work, check whether someone
30019
+ \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
30020
+
30021
+ ### Permissions and approvals
30022
+ You have real permissions based on your roles (chat member/admin, org member).
30023
+ If you lack permission for an action, the API returns PERMISSION_DENIED with the
30024
+ \`action\` and \`resource_uri\` that were denied. The server decides whether that
30025
+ action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
30026
+ fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
30027
+ it to ask someone with permission. If it is NOT approvable, the output says so;
30028
+ ask a human with permission instead of requesting approval. A
30029
+ \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
30030
+ (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
30031
+ \`dm\` for a user). Don't retry or work around a denial; only request approval
30032
+ after an actual denial, never preemptively.
30033
+
30034
+ ### When in doubt
30035
+ Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
30036
+ credibility is what you bring to the workspace \u2014 protect it.`;
30037
+ var PRLL_REFERENCE_GUIDE = `## Parall References
30038
+
30039
+ Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
30040
+ entities when you create or update tasks, comments, messages, and wiki files.
30041
+
30042
+ All three forms work \u2014 pick whichever fits:
30043
+
30044
+ prll://tsk_abc bare URI (auto-linked)
30045
+ [](prll://tsk_abc) empty context (renders resolved title)
30046
+ [relevant context](prll://tsk_abc) with author annotation
30047
+
30048
+ Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
30049
+ resolves and renders the entity title automatically.
30050
+
30051
+ ### URI format
30052
+
30053
+ \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
30054
+
30055
+ **Entities** \u2014 the entity ID is the authority:
30056
+
30057
+ prll://usr_xxx user prll://prj_xxx project
30058
+ prll://tsk_xxx task prll://wik_xxx wiki
30059
+ prll://msg_xxx message prll://cmt_xxx comment
30060
+ prll://cht_xxx chat prll://tcm_xxx task comment (legacy)
30061
+ prll://att_xxx attachment prll://ase_xxx agent session
30062
+ prll://sch_xxx schedule prll://srn_xxx schedule run
30063
+
30064
+ **Wiki** \u2014 path is file path, fragment is a typed anchor:
30065
+
30066
+ prll://wik_xxx/docs/guide.md file
30067
+ prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
30068
+ prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
30069
+
30070
+ Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
30071
+ Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
30072
+
30073
+ **Chat message range**:
30074
+
30075
+ prll://cht_xxx#range=msg_01HA,msg_01HZ
30076
+
30077
+ **Field access** \u2014 path selects a field (omit to reference the entity itself):
30078
+
30079
+ prll://tsk_xxx/description#Implementation heading within task description
30080
+
30081
+ ### Unread context
30082
+
30083
+ When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
30084
+ This shows messages since your last interaction \u2014 your read cursor advances after each
30085
+ dispatch, so context you skip now won't appear as unread next time. Use
30086
+ \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
30087
+ counts (50+), fetch only recent messages rather than everything.
30088
+
30089
+ Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
30090
+ Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
30091
+ catch up on the thread.
30092
+
30093
+ ### Reading context on demand
30094
+
30095
+ An event only carries the single triggering message. If you're mentioned in a
30096
+ group chat and lack context, pull what you need from the chat \u2014 don't guess:
30097
+
30098
+ parall messages list cht_xxx --limit 20 --before msg_xxx
30099
+ parall messages get msg_xxx
30100
+ parall chats get cht_xxx
30101
+
30102
+ Rule of thumb: in a group chat mention, the conversation that led up to you
30103
+ being called almost always matters \u2014 read it before replying. In a DM, your
30104
+ session already has continuity, so skip the fetch unless something is unclear.
30105
+
30106
+ Same pattern for any other entity referenced in the event: \`tasks get\`,
30107
+ \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
30108
+ When one entity isn't enough \u2014 you need what's *around* it \u2014 walk the
30109
+ reference graph instead of guessing (see "Walk the reference graph" below).
30110
+
30111
+ ### Find context with search first
30112
+
30113
+ Reach for unified semantic search before paging chat history:
30114
+
30115
+ parall search "pricing decision june" --limit 10
30116
+
30117
+ It spans messages, tasks, wiki, and comments. Page \`messages list\` only for the
30118
+ verbatim recent flow of one chat, not for discovery.
30119
+
30120
+ ### Walk the reference graph
30121
+
30122
+ References form a traversable graph, and you can query it \u2014 don't stop at
30123
+ fetching entities one by one:
30124
+
30125
+ # entity metadata (title, status, preview)
30126
+ parall refs resolve prll://tsk_xxx prll://wik_xxx
30127
+ # who references this entity
30128
+ parall refs backlinks prll://tsk_xxx
30129
+ # connected sub-graph around it
30130
+ parall refs graph prll://tsk_xxx --depth 2
30131
+
30132
+ Use \`refs backlinks\` when you need "where is this discussed / used"; use
30133
+ \`refs graph\` when you need the full picture around an entity (related tasks,
30134
+ docs, conversations \u2014 edges carry the author's annotation for why they linked).
30135
+ Then \`refs resolve\` the interesting node URIs in one batch to get titles and
30136
+ status. \`refs graph\` takes entity-level URIs only (\`prll://wik_xxx\`, not
30137
+ \`prll://wik_xxx/docs/a.md\`). All results are filtered to what you can see.
30138
+ Details: parall-platform skill.
30139
+
30140
+ ### File attachments
30141
+
30142
+ Messages may include attachments. They appear in events as:
30143
+
30144
+ [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
30145
+
30146
+ To download an attachment, use the CLI:
30147
+
30148
+ parall files download att_xxx --output /tmp/screenshot.png
30149
+
30150
+ To send a file:
30151
+
30152
+ parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
30153
+
30154
+ Or upload first and reuse across chats:
30155
+
30156
+ parall files upload /tmp/report.pdf
30157
+ parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
30158
+ parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
30159
+
30160
+ 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 \`$(...)\`.
30161
+
30162
+ ### When to reference
30163
+
30164
+ - **Origin** \u2014 always link the message or task that triggered your work
30165
+ - **Design docs / wiki** \u2014 link specs and guides relevant to the work
30166
+ - **Related tasks** \u2014 link parent, sibling, or blocking tasks
30167
+ - **People** \u2014 link assignees or stakeholders when mentioning them
30168
+ - **Conversations** \u2014 link a chat or message range as context
30169
+
30170
+ ### Why this matters
30171
+
30172
+ Other agents and humans read your output. References build a navigable context graph \u2014
30173
+ in multi-agent workflows, your references are the map that the next agent follows.`;
30174
+ function renderLocalAttachmentSection(section) {
30175
+ if (section.images.length === 0 && section.notes.length === 0)
30176
+ return "";
30177
+ const lines = ["[Local attachment files]"];
30178
+ for (const image of section.images) {
30179
+ lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
30113
30180
  }
30114
- const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
30115
- await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
30116
- return "dispatched";
30181
+ lines.push(...section.notes);
30182
+ return lines.join("\n");
30183
+ }
30184
+ function sanitizePromptMeta(value) {
30185
+ return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
30186
+ }
30187
+ function formatBytes(bytes) {
30188
+ if (bytes >= 1048576)
30189
+ return `${(bytes / 1048576).toFixed(1)}MB`;
30190
+ if (bytes >= 1024)
30191
+ return `${Math.round(bytes / 1024)}KB`;
30192
+ return `${bytes}B`;
30193
+ }
30194
+
30195
+ // ts/agent-core/dist/bridge-workspace.js
30196
+ var BRIDGE_WORKSPACE_INSTRUCTIONS = `# Agent workspace
30197
+
30198
+ You are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.
30199
+
30200
+ ## Message Model
30201
+
30202
+ Incoming events are rendered as structured \`[Event: ...]\` blocks.
30203
+ Each event includes \`[Chat: ... (prll://cht_xxx)]\` \u2014 use that chat ID (or full URI) when replying.
30204
+
30205
+ **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.
30206
+ 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.
30207
+
30208
+ ## Parall CLI
30209
+
30210
+ 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.
30211
+
30212
+ - \`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)
30213
+ - \`parall dm prll://usr_xxx --text-file - [--no-reply]\` \u2014 direct message another user
30214
+ - \`parall tasks update prll://tsk_xxx --status in_progress\` \u2014 task state
30215
+ - \`parall no-reply [--reason "..."]\` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)
30216
+
30217
+ **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:
30218
+
30219
+ \`\`\`bash
30220
+ parall messages send prll://cht_xxx --text-file - <<'EOF'
30221
+ That costs $1,000, and $(whoami) stays literal. I'm on it.
30222
+ EOF
30223
+ \`\`\`
30224
+
30225
+ Keep \`--text "..."\` for short literals with no \`$\`, backtick, or apostrophe.
30226
+
30227
+ 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.
30228
+
30229
+ CLI errors are agent-readable \u2014 read them; they usually name the next step.
30230
+
30231
+ ## Attachments
30232
+
30233
+ 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.
30234
+
30235
+ 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 ...\`.
30236
+
30237
+ ## Guardrails
30238
+
30239
+ - 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.
30240
+ - 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.
30241
+ - 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.
30242
+ - Keep CLI replies concise and task-focused.
30243
+
30244
+ See \`docs/engineering-design/agent-dm-loop-prevention.md\` \xA7 Layer 0 for why plain text is never auto-projected.
30245
+
30246
+ ## Approval Flow
30247
+
30248
+ 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:
30249
+
30250
+ 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.
30251
+ 2. Request approval: \`parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"\`
30252
+ 3. A card will appear in the specified chat for someone with permission to approve
30253
+ 4. Check the result: \`parall approvals get prll://<id>\` or wait: \`parall approvals wait prll://<id> --timeout 300\`
30254
+ 5. List available actions: \`parall approvals actions\`
30255
+
30256
+ Only request approval when you've actually been denied permission. Don't request approval preemptively.
30257
+ `;
30258
+ function extractShellCommand(input) {
30259
+ if (!input || typeof input !== "object")
30260
+ return void 0;
30261
+ const command = input.command;
30262
+ return typeof command === "string" && command.trim() ? command.trim() : void 0;
30117
30263
  }
30118
- async function consumeTypedDispatch(host, ref, run, ack) {
30119
- if (!host.laneLedger || host.ledgerDisabled) {
30120
- if (await run(ref.dispatchEventId))
30121
- await 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
- await 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
- await ack(lane.typedDispatchEventId);
30143
- } finally {
30144
- await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
30145
- });
30264
+ function parseParallCliInvocation(command) {
30265
+ const tokens = command.replace(/\s+/g, " ").trim().split(" ");
30266
+ let i = 0;
30267
+ if (tokens[i] === "parall") {
30268
+ i++;
30269
+ } else if (tokens[i] === "npx") {
30270
+ i++;
30271
+ while (i < tokens.length && tokens[i].startsWith("-"))
30272
+ i++;
30273
+ if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
30274
+ return null;
30275
+ i++;
30276
+ } else if (tokens[i] === "pnpm") {
30277
+ i++;
30278
+ if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
30279
+ i++;
30280
+ if (i >= tokens.length || tokens[i] !== "parall")
30281
+ return null;
30282
+ i++;
30283
+ } else {
30284
+ return null;
30146
30285
  }
30286
+ return tokens.slice(i).filter((t) => !t.startsWith("-"));
30147
30287
  }
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
- });
30288
+ function isParallSendCommand(command) {
30289
+ if (!command)
30290
+ return false;
30291
+ const sub = parseParallCliInvocation(command);
30292
+ if (!sub || sub.length === 0)
30293
+ return false;
30294
+ return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
30295
+ }
30296
+ function isParallNoReplyCommand(command) {
30297
+ if (!command)
30298
+ return false;
30299
+ const sub = parseParallCliInvocation(command);
30300
+ return sub?.[0] === "no-reply";
30301
+ }
30302
+
30303
+ // ts/agent-core/dist/dispatch-adapter.js
30304
+ function buildErrorStepContent(message) {
30305
+ return { text: message, suppressed: false, status: "error" };
30306
+ }
30307
+
30308
+ // ts/agent-core/dist/logger.js
30309
+ function createLogger(prefix) {
30310
+ return {
30311
+ info: (msg) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30312
+ warn: (msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30313
+ error: (msg) => console.error(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30314
+ child: (sub) => createLogger(`${prefix}:${sub}`)
30156
30315
  };
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;
30196
- }
30197
30316
  }
30317
+ function childLogger(logger, sub) {
30318
+ return logger.child ? logger.child(sub) : logger;
30319
+ }
30320
+
30321
+ // ts/agent-core/dist/gateway-base.js
30322
+ import * as os from "node:os";
30323
+ import * as fs2 from "node:fs";
30324
+ import * as path2 from "node:path";
30198
30325
 
30199
30326
  // ts/agent-core/dist/telemetry.js
30200
30327
  init_esm();
@@ -30476,6 +30603,9 @@ var ParallAgentGateway = class {
30476
30603
  // (stable mapping; avoids one connection fetch per inbound message).
30477
30604
  channelConnectionProviders = /* @__PURE__ */ new Map();
30478
30605
  dispatchedMessages = /* @__PURE__ */ new Set();
30606
+ // Per-WorkItem failure backoff for typed dispatch consumption — see
30607
+ // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
30608
+ typedRedriveBackoff = /* @__PURE__ */ new Map();
30479
30609
  forkStates = /* @__PURE__ */ new Map();
30480
30610
  dispatchState = {
30481
30611
  mainDispatching: false,
@@ -30600,7 +30730,11 @@ var ParallAgentGateway = class {
30600
30730
  return this.opts.client.ackDispatch(this.opts.config.org_id, {
30601
30731
  source_type: "task_activity",
30602
30732
  source_id: data.id
30603
- }).then(() => void 0, () => void 0);
30733
+ }).then(() => true, (err) => {
30734
+ this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
30735
+ this.opts.log?.warn(`dispatch ack failed for task ${data.id}, releasing for re-drive: ${String(err)}`);
30736
+ return false;
30737
+ });
30604
30738
  });
30605
30739
  } catch (err) {
30606
30740
  this.opts.log?.error(`task dispatch failed for ${data.id}: ${String(err)}`);
@@ -30707,6 +30841,44 @@ var ParallAgentGateway = class {
30707
30841
  this.dispatchedMessages.add(id);
30708
30842
  return true;
30709
30843
  }
30844
+ /**
30845
+ * Lane currently being dispatched per session — lets external activity
30846
+ * signals renew exactly the caller's lane (renewing all lanes would keep
30847
+ * an unrelated stalled fork's lane leased forever).
30848
+ */
30849
+ sessionActiveLanes = /* @__PURE__ */ new Map();
30850
+ noteSessionLane(sessionKey, laneKey) {
30851
+ if (laneKey == null)
30852
+ this.sessionActiveLanes.delete(sessionKey);
30853
+ else
30854
+ this.sessionActiveLanes.set(sessionKey, laneKey);
30855
+ }
30856
+ /**
30857
+ * External runtime-activity signal for adapters whose tool activity does
30858
+ * not flow through the RuntimeEvent stream (openclaw hooks call this from
30859
+ * the tool-call lifecycle): renews the session's OWN active ledger lane so
30860
+ * a long tool call cannot outlive the lease and get dethroned mid-turn.
30861
+ * No-op without an active ledger lane for the session.
30862
+ */
30863
+ touchRuntimeActivity(sessionKey) {
30864
+ if (this.ledgerDisabled)
30865
+ return;
30866
+ const laneKey = this.sessionActiveLanes.get(sessionKey);
30867
+ if (laneKey)
30868
+ this.laneLedger?.renewByKey(laneKey);
30869
+ }
30870
+ /** Sessions whose in-flight turn surfaced a runtime error event. */
30871
+ turnErrorSessions = /* @__PURE__ */ new Set();
30872
+ /**
30873
+ * Consume (read-and-clear) the error marker for sessionKey's last turn.
30874
+ * Feeds complete's turn_outcome so an error turn's lane members are
30875
+ * released for retry instead of no_action-swept (design §3). Consuming
30876
+ * (rather than peeking) keeps one-shot fork session keys from accumulating
30877
+ * in the set forever.
30878
+ */
30879
+ consumeTurnError(sessionKey) {
30880
+ return this.turnErrorSessions.delete(sessionKey);
30881
+ }
30710
30882
  async emitDispatchReceived(event) {
30711
30883
  const sourceType = event.ackSourceType ?? (event.type === "task" ? "task_activity" : "message");
30712
30884
  const sourceId = event.ackSourceId ?? event.messageId;
@@ -30750,11 +30922,15 @@ var ParallAgentGateway = class {
30750
30922
  }
30751
30923
  // Typed completion must wait until the administrative ack has either
30752
30924
  // committed or failed. Errors stay best-effort: a failed ack leaves the row
30753
- // received, so Complete releases and re-drives it safely.
30925
+ // received, so Complete releases and re-drives it safely. The boolean
30926
+ // outcome feeds the typed-consume backoff — an ack that failed must count
30927
+ // as a failed consume, or an ack outage would clear the backoff entry and
30928
+ // let the release re-drive spin at wire speed.
30754
30929
  ackDispatchEvent(dispatchEventId, onFailure) {
30755
- return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => void 0, (err) => {
30930
+ return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => true, (err) => {
30756
30931
  onFailure?.();
30757
30932
  this.opts.log?.warn(`dispatch ack failed for ${dispatchEventId}, releasing for re-drive: ${String(err)}`);
30933
+ return false;
30758
30934
  });
30759
30935
  }
30760
30936
  clearTypedDispatchDedupe(item) {
@@ -31052,6 +31228,7 @@ var ParallAgentGateway = class {
31052
31228
  this.pendingRestartNotification = null;
31053
31229
  }
31054
31230
  resetDispatchMetrics(sessionKey);
31231
+ this.turnErrorSessions.delete(sessionKey);
31055
31232
  return runWithSessionKey(sessionKey, async () => {
31056
31233
  let dispatchSpan = null;
31057
31234
  setSessionChatId(sessionKey, event.targetId);
@@ -31159,6 +31336,9 @@ var ParallAgentGateway = class {
31159
31336
  } else if (runtimeEvent.type === "tool_result" && pendingSendCallIds.delete(runtimeEvent.callId)) {
31160
31337
  recordMessageSend(sessionKey, !runtimeEvent.error);
31161
31338
  }
31339
+ if (runtimeEvent.type === "error") {
31340
+ this.turnErrorSessions.add(sessionKey);
31341
+ }
31162
31342
  await this.createRuntimeStep(binding.agentSessionId, event, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2);
31163
31343
  }
31164
31344
  if (!binding) {
@@ -31306,13 +31486,23 @@ var ParallAgentGateway = class {
31306
31486
  body: buildForkScopePrefix(last) + buildEventBody(last),
31307
31487
  earlier,
31308
31488
  captureText: batchText,
31309
- hasMoreLocal: () => fork.queue.length > 0
31489
+ // Per-LANE residue check (parity with the main-buffer path):
31490
+ // the fork queue can hold several lanes (channel + thread of
31491
+ // the same chat). A whole-queue check would defer THIS lane's
31492
+ // complete behind another lane's items and never revisit it —
31493
+ // its members would sit received until lease expiry.
31494
+ hasMoreLocal: () => fork.queue.some((it) => this.dispatchGroupKey(it.event) === this.dispatchGroupKey(last))
31310
31495
  });
31311
31496
  if (outcome === "foreign") {
31312
31497
  for (const item of items)
31313
31498
  item.resolve(false);
31314
31499
  break;
31315
31500
  }
31501
+ if (outcome === "failed") {
31502
+ for (const item of items)
31503
+ item.resolve(false);
31504
+ continue;
31505
+ }
31316
31506
  dispatched = outcome === "dispatched";
31317
31507
  } else {
31318
31508
  dispatched = await this.runDispatch(last, fork.fork.sessionKey, buildForkScopePrefix(last) + buildEventBody(last), earlier, batchText);
@@ -31346,6 +31536,7 @@ var ParallAgentGateway = class {
31346
31536
  remaining.resolve(false);
31347
31537
  }
31348
31538
  } finally {
31539
+ this.turnErrorSessions.delete(fork.fork.sessionKey);
31349
31540
  if (fork.deadlineTimer) {
31350
31541
  clearTimeout(fork.deadlineTimer);
31351
31542
  fork.deadlineTimer = null;
@@ -31458,6 +31649,10 @@ var ParallAgentGateway = class {
31458
31649
  this.dispatchState.pendingForkResults.unshift(...pendingFork);
31459
31650
  continue;
31460
31651
  }
31652
+ if (outcome === "failed") {
31653
+ this.dispatchState.pendingForkResults.unshift(...pendingFork);
31654
+ continue;
31655
+ }
31461
31656
  continue;
31462
31657
  }
31463
31658
  try {
@@ -31561,7 +31756,7 @@ var ParallAgentGateway = class {
31561
31756
  }
31562
31757
  this.dispatchState.mainBuffer.push(event);
31563
31758
  if (this.usesLaneLedger(event)) {
31564
- if (this.mainCurrentGroupKey === this.dispatchGroupKey(event) && await this.laneLedger?.steerLive(event) && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, buildEventBody(event))) {
31759
+ if (this.mainCurrentGroupKey === this.dispatchGroupKey(event) && this.opts.dispatchAdapter.enqueueDuringDispatch != null && await this.laneLedger?.steerLive(event) && await this.opts.dispatchAdapter.enqueueDuringDispatch(this.opts.runtimeKey, buildEventBody(event))) {
31565
31760
  this.opts.log?.info(`steer folded+injected for ${event.messageId} (will drain for bookkeeping)`);
31566
31761
  }
31567
31762
  } else if (this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, buildEventBody(event))) {
@@ -31588,12 +31783,14 @@ var ParallAgentGateway = class {
31588
31783
  this.dispatchState.mainBuffer.push(event);
31589
31784
  return false;
31590
31785
  }
31591
- try {
31592
- await this.emitDispatchReceived(event);
31593
- } catch (err) {
31594
- this.opts.log?.warn?.(`mark-received failed for fork dispatch, leaving unacked for retry: ${String(err)}`);
31595
- this.dispatchState.mainBuffer.push(event);
31596
- return false;
31786
+ if (!this.usesLaneLedger(event)) {
31787
+ try {
31788
+ await this.emitDispatchReceived(event);
31789
+ } catch (err) {
31790
+ this.opts.log?.warn?.(`mark-received failed for fork dispatch, leaving unacked for retry: ${String(err)}`);
31791
+ this.dispatchState.mainBuffer.push(event);
31792
+ return false;
31793
+ }
31597
31794
  }
31598
31795
  const fork = await this.opts.dispatchAdapter.forkSession({
31599
31796
  sessionKey: this.opts.runtimeKey,
@@ -32077,6 +32274,8 @@ var ParallAgentGateway = class {
32077
32274
  provider = void 0;
32078
32275
  }
32079
32276
  }
32277
+ const keys = this.opts.getCapabilityKeys?.() ?? [];
32278
+ const cliCapable = provider ? keys.includes(`${provider}-cli`) : keys.some((k) => k.endsWith("-cli"));
32080
32279
  const event = {
32081
32280
  type: "channel_message",
32082
32281
  targetId: conv.id,
@@ -32091,6 +32290,7 @@ var ParallAgentGateway = class {
32091
32290
  channelConversationType: conv.conversation_type || void 0,
32092
32291
  channelExternalConversationId: conv.external_conversation_id,
32093
32292
  channelExternalMessageId: msg.external_message_id,
32293
+ channelCliCapable: cliCapable,
32094
32294
  ackSourceType: "channel_message",
32095
32295
  ackSourceId: msg.id
32096
32296
  };
@@ -32427,6 +32627,28 @@ ${fullSummary}` : fullSummary;
32427
32627
  // ts/agent-core/dist/platform-config.js
32428
32628
  import * as fs3 from "node:fs";
32429
32629
  import * as path3 from "node:path";
32630
+ function extractCapabilities(config) {
32631
+ const agents = config.agents ?? {};
32632
+ const raw = agents.capabilities;
32633
+ if (!Array.isArray(raw))
32634
+ return [];
32635
+ const out = [];
32636
+ for (const entry of raw) {
32637
+ if (typeof entry !== "object" || entry === null)
32638
+ continue;
32639
+ const e = entry;
32640
+ if (typeof e.key !== "string" || !e.key)
32641
+ continue;
32642
+ if (typeof e.fragment !== "string" || !e.fragment)
32643
+ continue;
32644
+ out.push({
32645
+ key: e.key,
32646
+ source: typeof e.source === "string" ? e.source : "",
32647
+ fragment: e.fragment
32648
+ });
32649
+ }
32650
+ return out;
32651
+ }
32430
32652
  function isPlatformManagedProfile(profile) {
32431
32653
  return profile?.machine_id != null || profile?.model_management === "platform";
32432
32654
  }
@@ -32550,13 +32772,96 @@ function createPlatformConfigManager(opts) {
32550
32772
  },
32551
32773
  rawConfig() {
32552
32774
  return currentRawConfig;
32775
+ },
32776
+ capabilities() {
32777
+ return currentRawConfig ? extractCapabilities(currentRawConfig) : [];
32553
32778
  }
32554
32779
  };
32555
32780
  }
32556
32781
 
32557
- // ts/agent-core/dist/skills/index.js
32782
+ // ts/agent-core/dist/channel-capability.js
32558
32783
  import * as fs4 from "node:fs";
32559
32784
  import * as path4 from "node:path";
32785
+ import { fileURLToPath } from "node:url";
32786
+ var CAPABILITY_FEISHU_CLI = "feishu-cli";
32787
+ var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
32788
+ function capabilityBinDir(stateDir) {
32789
+ return path4.join(stateDir, "bin");
32790
+ }
32791
+ function channelExecEntryPath() {
32792
+ const selfDir = path4.dirname(fileURLToPath(import.meta.url));
32793
+ const sibling = path4.join(selfDir, "parall-channel-exec.js");
32794
+ if (fs4.existsSync(sibling))
32795
+ return sibling;
32796
+ return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
32797
+ }
32798
+ function materializeChannelCapabilities(stateDir, capabilities, log2) {
32799
+ try {
32800
+ reconcileFeishuCli(stateDir, capabilities, log2);
32801
+ } catch (err) {
32802
+ log2?.warn(`channel capability materialization failed: ${String(err)}`);
32803
+ }
32804
+ }
32805
+ function reconcileFeishuCli(stateDir, capabilities, log2) {
32806
+ const binDir = capabilityBinDir(stateDir);
32807
+ const posixPath = path4.join(binDir, "lark-cli");
32808
+ const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
32809
+ const hadPointer = fs4.existsSync(posixPath);
32810
+ if (!granted && !hadPointer)
32811
+ return;
32812
+ fs4.mkdirSync(binDir, { recursive: true });
32813
+ const entry = channelExecEntryPath();
32814
+ const nodeExec = process.execPath;
32815
+ writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log2);
32816
+ writePointerIfChanged(path4.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log2);
32817
+ }
32818
+ function writePointerIfChanged(filePath, content, log2) {
32819
+ let existing = null;
32820
+ try {
32821
+ existing = fs4.readFileSync(filePath, "utf8");
32822
+ } catch {
32823
+ existing = null;
32824
+ }
32825
+ if (existing !== content) {
32826
+ fs4.writeFileSync(filePath, content, { mode: 493 });
32827
+ log2?.info(`channel capability: pointer materialized (${path4.basename(filePath)})`);
32828
+ }
32829
+ fs4.chmodSync(filePath, 493);
32830
+ }
32831
+ function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
32832
+ return [
32833
+ "#!/bin/sh",
32834
+ `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32835
+ "# Credential + exec logic lives in the agent-core package; revocation is",
32836
+ "# enforced by the platform mint endpoint, so this pointer stays constant.",
32837
+ // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
32838
+ // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
32839
+ // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
32840
+ // the mint. The pointer is a platform-authored trust-boundary artifact whose
32841
+ // whole job is a CONTROLLED launch of the broker (absolute node, magic
32842
+ // guard, skip-dir); this closes the same env-hijack class for node startup
32843
+ // that the absolute node path closes for PATH, keeping the launch deterministic.
32844
+ "unset NODE_OPTIONS NODE_PATH",
32845
+ // "$@" preserves argv exactly (this is the agent's main path via git-bash).
32846
+ `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
32847
+ ""
32848
+ ].join("\n");
32849
+ }
32850
+ function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
32851
+ return [
32852
+ "@echo off",
32853
+ `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32854
+ // Clear Node preload-hijack vars before launching node (see the sh pointer).
32855
+ 'set "NODE_OPTIONS="',
32856
+ 'set "NODE_PATH="',
32857
+ `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
32858
+ ""
32859
+ ].join("\r\n");
32860
+ }
32861
+
32862
+ // ts/agent-core/dist/skills/index.js
32863
+ import * as fs5 from "node:fs";
32864
+ import * as path5 from "node:path";
32560
32865
 
32561
32866
  // ts/agent-core/dist/skills/parall-platform.js
32562
32867
  var PARALL_PLATFORM_SKILL = `# Parall Platform
@@ -32637,11 +32942,11 @@ settled questions or repeat known mistakes. This searches live org data
32637
32942
  can see.
32638
32943
 
32639
32944
  \`\`\`bash
32640
- # Semantic + keyword search across messages, tasks, and wiki
32945
+ # Semantic + keyword search across messages, tasks, wiki, and comments
32641
32946
  parall search "auth v5 upgrade"
32642
32947
 
32643
- # Restrict entity types (m=message, t=task, w=wiki). --channel narrows the
32644
- # MESSAGE hits to one chat (tasks/wiki are unaffected by it).
32948
+ # Restrict entity types (m=message, t=task, w=wiki, c=comment). --channel
32949
+ # narrows the MESSAGE hits to one chat (tasks/wiki/comments are unaffected).
32645
32950
  parall search "auth v5 upgrade" --types m,w --channel prll://cht_eng
32646
32951
 
32647
32952
  # Time-box to recent activity (RFC3339 or YYYY-MM-DD). Narrows messages + tasks;
@@ -32762,6 +33067,8 @@ Every entity is addressable with a \`prll://\` URI. Common prefixes you'll see i
32762
33067
  | \`prll://usr_\` | User (human or agent) | parall-platform |
32763
33068
  | \`prll://cht_\` | Chat | parall-platform |
32764
33069
  | \`prll://msg_\` | Message | parall-platform |
33070
+ | \`prll://cmt_\` | Comment (on tasks, wiki pages, changesets) | by target: task comment \u2192 parall-tasks, wiki/changeset comment \u2192 parall-wiki |
33071
+ | \`prll://ase_\` | Agent session | parall-platform |
32765
33072
  | \`prll://tsk_\` | Task | parall-tasks |
32766
33073
  | \`prll://prj_\` | Project | parall-tasks |
32767
33074
  | \`prll://sch_\` | Schedule (time trigger) | parall-schedules |
@@ -32797,7 +33104,24 @@ parall refs graph prll://tsk_xxx --depth 2
32797
33104
 
32798
33105
  \`refs graph\` traverses both directions (inbound + outbound) and returns \`nodes\`
32799
33106
  and \`edges\` with each node's hop \`depth\`. \`truncated: true\` means a size cap clipped
32800
- the result \u2014 narrow it with a smaller \`--depth\`.
33107
+ the result \u2014 narrow it with a smaller \`--depth\`. Edges carry \`context\` \u2014 the
33108
+ author's annotation from \`[context](prll://...)\` \u2014 telling you *why* two
33109
+ entities are linked, not just that they are.
33110
+
33111
+ The graph returns bare node URIs (no titles). The usual two-step: \`refs graph\`
33112
+ for topology, then batch-\`refs resolve\` the node URIs you care about for
33113
+ titles/status. If graph rejects your URI with a path/anchor error, strip it to
33114
+ the entity root (\`prll://wik_xxx/docs/a.md\` \u2192 \`prll://wik_xxx\`) and re-query \u2014
33115
+ but note this WIDENS the query to the whole entity, not that one file: the
33116
+ graph seeds from the wiki id, so a specific file's outbound links may sit
33117
+ deeper in the result (or past the size caps). For refs pointing AT one file
33118
+ (inbound), \`refs backlinks\` on the full file URI is precise. There is no
33119
+ precise query for one file's OUTBOUND edges today \u2014 the widened root graph is
33120
+ best-effort for those, or read the file itself for its \`prll://\` links.
33121
+ Wiki-file nodes inside a graph *result* do legitimately carry paths.
33122
+
33123
+ \`refs backlinks\` items include a \`snippet\` of the referencing content \u2014 often
33124
+ enough to judge relevance without fetching the source entity.
32801
33125
 
32802
33126
  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.
32803
33127
  `;
@@ -33311,7 +33635,7 @@ Results are JSON on stdout; failures print an error.
33311
33635
  var SKILLS = [
33312
33636
  {
33313
33637
  name: "parall-platform",
33314
- 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.",
33638
+ 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.",
33315
33639
  content: PARALL_PLATFORM_SKILL
33316
33640
  },
33317
33641
  {
@@ -33341,13 +33665,13 @@ var SKILLS = [
33341
33665
  }
33342
33666
  ];
33343
33667
  function writeSkillFiles(targetDir) {
33344
- fs4.mkdirSync(targetDir, { recursive: true });
33668
+ fs5.mkdirSync(targetDir, { recursive: true });
33345
33669
  for (const skill of SKILLS) {
33346
- fs4.writeFileSync(path4.join(targetDir, `${skill.name}.md`), skill.content, "utf8");
33670
+ fs5.writeFileSync(path5.join(targetDir, `${skill.name}.md`), skill.content, "utf8");
33347
33671
  }
33348
33672
  }
33349
33673
  function buildSkillReferences(workspaceDir) {
33350
- const dir = path4.join(workspaceDir, ".parall", "skills");
33674
+ const dir = path5.join(workspaceDir, ".parall", "skills");
33351
33675
  const lines = SKILLS.map((s) => `- ${s.description.split(":")[0]}: \`${dir}/${s.name}.md\``);
33352
33676
  return `## Platform Skills (read on demand)
33353
33677
 
@@ -33357,7 +33681,7 @@ ${lines.join("\n")}
33357
33681
 
33358
33682
  // ts/claude-agent/dist/config.js
33359
33683
  import * as os2 from "node:os";
33360
- import * as path5 from "node:path";
33684
+ import * as path6 from "node:path";
33361
33685
  function requireEnv(env, name) {
33362
33686
  const value = env[name]?.trim();
33363
33687
  if (!value) {
@@ -33371,15 +33695,15 @@ function parseList(value) {
33371
33695
  return value.split(/[,\n]/).map((item) => item.trim()).filter(Boolean);
33372
33696
  }
33373
33697
  function resolvePath(value) {
33374
- return path5.isAbsolute(value) ? value : path5.resolve(process.cwd(), value);
33698
+ return path6.isAbsolute(value) ? value : path6.resolve(process.cwd(), value);
33375
33699
  }
33376
33700
  function resolveClaudeAgentConfig(env = process.env) {
33377
33701
  const apiUrl = requireEnv(env, "PRLL_API_URL");
33378
33702
  const apiKey = requireEnv(env, "PRLL_API_KEY");
33379
33703
  const orgId = requireEnv(env, "PRLL_ORG_ID");
33380
33704
  const claudeHome = resolvePath(env.PRLL_CLAUDE_HOME?.trim() || env.HOME || os2.homedir());
33381
- const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() || path5.join(claudeHome, ".parall-agent"));
33382
- const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() || path5.join(stateDir, "workspace"));
33705
+ const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() || path6.join(claudeHome, ".parall-agent"));
33706
+ const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() || path6.join(stateDir, "workspace"));
33383
33707
  const additionalDirs = parseList(env.PRLL_CLAUDE_ADD_DIRS).map(resolvePath);
33384
33708
  return {
33385
33709
  apiUrl,
@@ -33414,23 +33738,23 @@ function buildClaudeRuntimeKey(agentUserId) {
33414
33738
  }
33415
33739
  function sessionStateFilePathForRuntime(stateDir, runtimeKey) {
33416
33740
  const fileName = Buffer.from(runtimeKey).toString("base64url");
33417
- return path5.join(stateDir, "sessions", `${fileName}.json`);
33741
+ return path6.join(stateDir, "sessions", `${fileName}.json`);
33418
33742
  }
33419
33743
  function contextFilePathForSession(stateDir, sessionKey) {
33420
33744
  const fileName = Buffer.from(sessionKey).toString("base64url");
33421
- return path5.join(stateDir, "dispatch-context", `${fileName}.json`);
33745
+ return path6.join(stateDir, "dispatch-context", `${fileName}.json`);
33422
33746
  }
33423
33747
  function dispatchContextDirPath(stateDir) {
33424
33748
  return dispatchLaneContextDir(stateDir);
33425
33749
  }
33426
33750
  function stepIdFilePathForSession(stateDir, sessionKey) {
33427
33751
  const fileName = Buffer.from(sessionKey).toString("base64url");
33428
- return path5.join(stateDir, "step-ids", `${fileName}.txt`);
33752
+ return path6.join(stateDir, "step-ids", `${fileName}.txt`);
33429
33753
  }
33430
33754
 
33431
33755
  // ts/claude-agent/dist/dispatch.js
33432
- import * as fs6 from "node:fs";
33433
- import * as path7 from "node:path";
33756
+ import * as fs7 from "node:fs";
33757
+ import * as path8 from "node:path";
33434
33758
  import { randomUUID } from "node:crypto";
33435
33759
  import { execSync as execSync2, spawn } from "node:child_process";
33436
33760
 
@@ -33438,8 +33762,8 @@ import { execSync as execSync2, spawn } from "node:child_process";
33438
33762
  import { execSync } from "node:child_process";
33439
33763
  import { constants } from "node:fs";
33440
33764
  import * as fsSync from "node:fs";
33441
- import * as fs5 from "node:fs/promises";
33442
- import * as path6 from "node:path";
33765
+ import * as fs6 from "node:fs/promises";
33766
+ import * as path7 from "node:path";
33443
33767
  var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
33444
33768
  var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
33445
33769
  var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
@@ -33469,11 +33793,11 @@ async function prepareLocalImageAttachments(event, context2, opts) {
33469
33793
  };
33470
33794
  }
33471
33795
  const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
33472
- const messageDir = path6.join(rootDir, sanitizePathSegment(event.messageId));
33796
+ const messageDir = path7.join(rootDir, sanitizePathSegment(event.messageId));
33473
33797
  await ensurePathIsNotSymlink(messageDir);
33474
- await fs5.mkdir(messageDir, { recursive: true });
33798
+ await fs6.mkdir(messageDir, { recursive: true });
33475
33799
  await ensurePathIsNotSymlink(messageDir);
33476
- const activeMessageDir = path6.resolve(messageDir);
33800
+ const activeMessageDir = path7.resolve(messageDir);
33477
33801
  activeAttachmentDirs.add(activeMessageDir);
33478
33802
  const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
33479
33803
  const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
@@ -33490,7 +33814,7 @@ async function prepareLocalImageAttachments(event, context2, opts) {
33490
33814
  const notes = [];
33491
33815
  let downloadedBytes = 0;
33492
33816
  for (const att of imageAttachments) {
33493
- const localPath = path6.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
33817
+ const localPath = path7.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
33494
33818
  const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
33495
33819
  const fetchFresh = async () => {
33496
33820
  const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
@@ -33547,7 +33871,7 @@ async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
33547
33871
  return { body: appendLocalAttachmentRefs(body, attachments), attachments };
33548
33872
  }
33549
33873
  function pinLocalAttachmentPaths(images) {
33550
- const dirs = new Set(images.map((image) => path6.resolve(path6.dirname(image.localPath))));
33874
+ const dirs = new Set(images.map((image) => path7.resolve(path7.dirname(image.localPath))));
33551
33875
  for (const dir of dirs) {
33552
33876
  activeAttachmentDirs.add(dir);
33553
33877
  }
@@ -33562,7 +33886,7 @@ function pinLocalAttachmentPaths(images) {
33562
33886
  };
33563
33887
  }
33564
33888
  function attachmentRootDir(workspaceDir) {
33565
- return path6.join(path6.resolve(workspaceDir), ".parall", "attachments");
33889
+ return path7.join(path7.resolve(workspaceDir), ".parall", "attachments");
33566
33890
  }
33567
33891
  function ensureLocalAttachmentGitExclude(workingDirectory) {
33568
33892
  try {
@@ -33571,8 +33895,8 @@ function ensureLocalAttachmentGitExclude(workingDirectory) {
33571
33895
  encoding: "utf8",
33572
33896
  stdio: ["ignore", "pipe", "ignore"]
33573
33897
  }).trim();
33574
- const excludePath = path6.isAbsolute(rel) ? rel : path6.join(workingDirectory, rel);
33575
- fsSync.mkdirSync(path6.dirname(excludePath), { recursive: true });
33898
+ const excludePath = path7.isAbsolute(rel) ? rel : path7.join(workingDirectory, rel);
33899
+ fsSync.mkdirSync(path7.dirname(excludePath), { recursive: true });
33576
33900
  const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
33577
33901
  if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
33578
33902
  return;
@@ -33608,18 +33932,18 @@ function scheduleAttachmentMaintenance(rootDir, opts) {
33608
33932
  return run;
33609
33933
  }
33610
33934
  async function ensureAttachmentRootDir(workspaceDir) {
33611
- const workspaceRoot = path6.resolve(workspaceDir);
33612
- const parallDir = path6.join(workspaceRoot, ".parall");
33935
+ const workspaceRoot = path7.resolve(workspaceDir);
33936
+ const parallDir = path7.join(workspaceRoot, ".parall");
33613
33937
  const rootDir = attachmentRootDir(workspaceRoot);
33614
- await fs5.mkdir(workspaceRoot, { recursive: true });
33938
+ await fs6.mkdir(workspaceRoot, { recursive: true });
33615
33939
  await ensurePathIsNotSymlink(parallDir);
33616
- await fs5.mkdir(parallDir, { recursive: true, mode: 448 });
33940
+ await fs6.mkdir(parallDir, { recursive: true, mode: 448 });
33617
33941
  await ensurePathIsNotSymlink(parallDir);
33618
33942
  await ensurePathIsNotSymlink(rootDir);
33619
- await fs5.mkdir(rootDir, { recursive: true, mode: 448 });
33943
+ await fs6.mkdir(rootDir, { recursive: true, mode: 448 });
33620
33944
  await ensurePathIsNotSymlink(rootDir);
33621
- const realWorkspace = await fs5.realpath(workspaceRoot);
33622
- const realRoot = await fs5.realpath(rootDir);
33945
+ const realWorkspace = await fs6.realpath(workspaceRoot);
33946
+ const realRoot = await fs6.realpath(rootDir);
33623
33947
  if (!isPathInside(realRoot, realWorkspace)) {
33624
33948
  throw new Error(`attachment root escapes workspace: ${rootDir}`);
33625
33949
  }
@@ -33627,7 +33951,7 @@ async function ensureAttachmentRootDir(workspaceDir) {
33627
33951
  }
33628
33952
  async function ensurePathIsNotSymlink(filePath) {
33629
33953
  try {
33630
- const stat = await fs5.lstat(filePath);
33954
+ const stat = await fs6.lstat(filePath);
33631
33955
  if (stat.isSymbolicLink()) {
33632
33956
  throw new Error(`refusing to use symlinked attachment path ${filePath}`);
33633
33957
  }
@@ -33638,8 +33962,8 @@ async function ensurePathIsNotSymlink(filePath) {
33638
33962
  }
33639
33963
  }
33640
33964
  function isPathInside(childPath, parentPath) {
33641
- const rel = path6.relative(parentPath, childPath);
33642
- return rel === "" || !!rel && !rel.startsWith("..") && !path6.isAbsolute(rel);
33965
+ const rel = path7.relative(parentPath, childPath);
33966
+ return rel === "" || !!rel && !rel.startsWith("..") && !path7.isAbsolute(rel);
33643
33967
  }
33644
33968
  async function existingUsableFile(filePath, expectedSize, rootDir) {
33645
33969
  try {
@@ -33650,30 +33974,30 @@ async function existingUsableFile(filePath, expectedSize, rootDir) {
33650
33974
  }
33651
33975
  }
33652
33976
  async function localFileStatInsideRoot(filePath, rootDir) {
33653
- const stat = await fs5.lstat(filePath);
33977
+ const stat = await fs6.lstat(filePath);
33654
33978
  if (stat.isSymbolicLink()) {
33655
33979
  throw new Error(`refusing to use symlinked attachment file ${filePath}`);
33656
33980
  }
33657
33981
  if (!stat.isFile()) {
33658
33982
  throw new Error(`attachment path is not a file ${filePath}`);
33659
33983
  }
33660
- const realRoot = await fs5.realpath(rootDir);
33661
- const realFile = await fs5.realpath(filePath);
33984
+ const realRoot = await fs6.realpath(rootDir);
33985
+ const realFile = await fs6.realpath(filePath);
33662
33986
  if (!isPathInside(realFile, realRoot)) {
33663
33987
  throw new Error(`attachment file escapes workspace: ${filePath}`);
33664
33988
  }
33665
33989
  return stat;
33666
33990
  }
33667
33991
  async function localDirectoryStatInsideRoot(dirPath, rootDir) {
33668
- const stat = await fs5.lstat(dirPath);
33992
+ const stat = await fs6.lstat(dirPath);
33669
33993
  if (stat.isSymbolicLink()) {
33670
33994
  throw new Error(`refusing to use symlinked attachment directory ${dirPath}`);
33671
33995
  }
33672
33996
  if (!stat.isDirectory()) {
33673
33997
  throw new Error(`attachment path is not a directory ${dirPath}`);
33674
33998
  }
33675
- const realRoot = await fs5.realpath(rootDir);
33676
- const realDir = await fs5.realpath(dirPath);
33999
+ const realRoot = await fs6.realpath(rootDir);
34000
+ const realDir = await fs6.realpath(dirPath);
33677
34001
  if (!isPathInside(realDir, realRoot)) {
33678
34002
  throw new Error(`attachment directory escapes workspace: ${dirPath}`);
33679
34003
  }
@@ -33681,7 +34005,7 @@ async function localDirectoryStatInsideRoot(dirPath, rootDir) {
33681
34005
  }
33682
34006
  async function openLocalFileInsideRoot(filePath, rootDir) {
33683
34007
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
33684
- const file = await fs5.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
34008
+ const file = await fs6.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
33685
34009
  let keepOpen = false;
33686
34010
  try {
33687
34011
  const openedStat = await file.stat();
@@ -33697,8 +34021,8 @@ async function openLocalFileInsideRoot(filePath, rootDir) {
33697
34021
  }
33698
34022
  }
33699
34023
  async function openLocalTempFileInsideRoot(filePath, rootDir) {
33700
- await localDirectoryStatInsideRoot(path6.dirname(filePath), rootDir);
33701
- const file = await fs5.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
34024
+ await localDirectoryStatInsideRoot(path7.dirname(filePath), rootDir);
34025
+ const file = await fs6.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
33702
34026
  let keepOpen = false;
33703
34027
  try {
33704
34028
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
@@ -33723,7 +34047,7 @@ async function assertLocalFileIdentity(filePath, rootDir, expected) {
33723
34047
  async function removeLocalFileIfInside(filePath, rootDir) {
33724
34048
  try {
33725
34049
  await localFileStatInsideRoot(filePath, rootDir);
33726
- await fs5.rm(filePath, { force: true });
34050
+ await fs6.rm(filePath, { force: true });
33727
34051
  } catch {
33728
34052
  }
33729
34053
  }
@@ -33736,7 +34060,7 @@ function sameFile(a, b) {
33736
34060
  async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
33737
34061
  let entries;
33738
34062
  try {
33739
- entries = await fs5.readdir(rootDir, { withFileTypes: true });
34063
+ entries = await fs6.readdir(rootDir, { withFileTypes: true });
33740
34064
  } catch {
33741
34065
  return;
33742
34066
  }
@@ -33744,15 +34068,15 @@ async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
33744
34068
  await Promise.all(entries.map(async (entry) => {
33745
34069
  if (!entry.isDirectory())
33746
34070
  return;
33747
- const fullPath = path6.join(rootDir, entry.name);
34071
+ const fullPath = path7.join(rootDir, entry.name);
33748
34072
  try {
33749
- if (preserveDirs?.has(path6.resolve(fullPath)))
34073
+ if (preserveDirs?.has(path7.resolve(fullPath)))
33750
34074
  return;
33751
- const stat = await fs5.lstat(fullPath);
34075
+ const stat = await fs6.lstat(fullPath);
33752
34076
  if (!stat.isDirectory())
33753
34077
  return;
33754
34078
  if (stat.mtimeMs < cutoff) {
33755
- await fs5.rm(fullPath, { recursive: true, force: true });
34079
+ await fs6.rm(fullPath, { recursive: true, force: true });
33756
34080
  }
33757
34081
  } catch (err) {
33758
34082
  log2?.warn?.(`agent-core: failed to clean attachment temp dir ${fullPath}: ${String(err)}`);
@@ -33764,7 +34088,7 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33764
34088
  return;
33765
34089
  let entries;
33766
34090
  try {
33767
- entries = await fs5.readdir(rootDir, { withFileTypes: true });
34091
+ entries = await fs6.readdir(rootDir, { withFileTypes: true });
33768
34092
  } catch {
33769
34093
  return;
33770
34094
  }
@@ -33773,9 +34097,9 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33773
34097
  for (const entry of entries) {
33774
34098
  if (!entry.isDirectory())
33775
34099
  continue;
33776
- const fullPath = path6.join(rootDir, entry.name);
34100
+ const fullPath = path7.join(rootDir, entry.name);
33777
34101
  try {
33778
- const stat = await fs5.lstat(fullPath);
34102
+ const stat = await fs6.lstat(fullPath);
33779
34103
  if (!stat.isDirectory())
33780
34104
  continue;
33781
34105
  const size = await directorySize(fullPath);
@@ -33791,10 +34115,10 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33791
34115
  for (const dir of dirs) {
33792
34116
  if (total <= maxBytes)
33793
34117
  break;
33794
- if (preserveDirs?.has(path6.resolve(dir.path)))
34118
+ if (preserveDirs?.has(path7.resolve(dir.path)))
33795
34119
  continue;
33796
34120
  try {
33797
- await fs5.rm(dir.path, { recursive: true, force: true });
34121
+ await fs6.rm(dir.path, { recursive: true, force: true });
33798
34122
  total -= dir.size;
33799
34123
  } catch (err) {
33800
34124
  log2?.warn?.(`agent-core: failed to prune attachment cache dir ${dir.path}: ${String(err)}`);
@@ -33803,12 +34127,12 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33803
34127
  }
33804
34128
  async function directorySize(dirPath) {
33805
34129
  let total = 0;
33806
- const entries = await fs5.readdir(dirPath, { withFileTypes: true });
34130
+ const entries = await fs6.readdir(dirPath, { withFileTypes: true });
33807
34131
  for (const entry of entries) {
33808
- const fullPath = path6.join(dirPath, entry.name);
34132
+ const fullPath = path7.join(dirPath, entry.name);
33809
34133
  let stat;
33810
34134
  try {
33811
- stat = await fs5.lstat(fullPath);
34135
+ stat = await fs6.lstat(fullPath);
33812
34136
  } catch {
33813
34137
  continue;
33814
34138
  }
@@ -33823,10 +34147,10 @@ async function directorySize(dirPath) {
33823
34147
  return total;
33824
34148
  }
33825
34149
  function activeDirsForRoot(rootDir) {
33826
- const root = path6.resolve(rootDir);
34150
+ const root = path7.resolve(rootDir);
33827
34151
  const dirs = /* @__PURE__ */ new Set();
33828
34152
  for (const dir of activeAttachmentDirs) {
33829
- if (dir === root || dir.startsWith(`${root}${path6.sep}`)) {
34153
+ if (dir === root || dir.startsWith(`${root}${path7.sep}`)) {
33830
34154
  dirs.add(dir);
33831
34155
  }
33832
34156
  }
@@ -33923,9 +34247,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
33923
34247
  }
33924
34248
  writtenStat = await file.stat();
33925
34249
  await closeFile();
33926
- await localDirectoryStatInsideRoot(path6.dirname(filePath), rootDir);
34250
+ await localDirectoryStatInsideRoot(path7.dirname(filePath), rootDir);
33927
34251
  await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
33928
- await fs5.rename(tmpPath, filePath);
34252
+ await fs6.rename(tmpPath, filePath);
33929
34253
  completed = true;
33930
34254
  return written;
33931
34255
  } finally {
@@ -33941,9 +34265,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
33941
34265
  }
33942
34266
  }
33943
34267
  function localFileName(attachmentId, fileName, mimeType) {
33944
- const safeName = sanitizePathSegment(path6.basename(fileName || attachmentId));
33945
- const ext = path6.extname(safeName) || extensionForMime(mimeType);
33946
- const stem = path6.basename(safeName, path6.extname(safeName)) || attachmentId;
34268
+ const safeName = sanitizePathSegment(path7.basename(fileName || attachmentId));
34269
+ const ext = path7.extname(safeName) || extensionForMime(mimeType);
34270
+ const stem = path7.basename(safeName, path7.extname(safeName)) || attachmentId;
33947
34271
  return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
33948
34272
  }
33949
34273
  function extensionForMime(mimeType) {
@@ -34235,6 +34559,11 @@ function buildSpawnEnv(parentEnv, claudeHome, context2, opts) {
34235
34559
  if (opts.effortLevel) {
34236
34560
  result.CLAUDE_CODE_EFFORT_LEVEL = opts.effortLevel;
34237
34561
  }
34562
+ if (opts.capabilityBinDir) {
34563
+ const pathKey = process.platform === "win32" ? Object.keys(result).find((k) => k.toUpperCase() === "PATH") ?? "PATH" : "PATH";
34564
+ const existing = result[pathKey];
34565
+ result[pathKey] = existing ? `${opts.capabilityBinDir}${path8.delimiter}${existing}` : opts.capabilityBinDir;
34566
+ }
34238
34567
  return result;
34239
34568
  }
34240
34569
  var ClaudeCodeAdapter = class {
@@ -34262,9 +34591,18 @@ var ClaudeCodeAdapter = class {
34262
34591
  if (effortChanged)
34263
34592
  this._effortLevel = config.effort ?? void 0;
34264
34593
  if (modelChanged || effortChanged) {
34265
- for (const [, state] of this.processes) {
34266
- state.needsRestart = true;
34267
- }
34594
+ this.requestProcessRestart();
34595
+ }
34596
+ }
34597
+ // Mark every live subprocess for a lazy respawn (applied at its next
34598
+ // dispatch; the session survives via --resume) — the same mechanism
34599
+ // updateConfig uses for model/effort changes. For spawn-time inputs that
34600
+ // live OUTSIDE this adapter's config, e.g. the .parall/system-prompt.md
34601
+ // file: a long-lived process read it via --append-system-prompt-file at
34602
+ // spawn, so a capability declaration change only reaches it by respawning.
34603
+ requestProcessRestart() {
34604
+ for (const [, state] of this.processes) {
34605
+ state.needsRestart = true;
34268
34606
  }
34269
34607
  }
34270
34608
  enqueueDuringDispatch(sessionKey, body) {
@@ -34333,8 +34671,8 @@ var ClaudeCodeAdapter = class {
34333
34671
  if (!sessionId)
34334
34672
  return void 0;
34335
34673
  const projectSlug = this.opts.workspaceDir.replace(/[/.]/g, "-");
34336
- const filePath = path7.join(this.opts.claudeHome, ".claude", "projects", projectSlug, `${sessionId}.jsonl`);
34337
- return fs6.existsSync(filePath) ? filePath : void 0;
34674
+ const filePath = path8.join(this.opts.claudeHome, ".claude", "projects", projectSlug, `${sessionId}.jsonl`);
34675
+ return fs7.existsSync(filePath) ? filePath : void 0;
34338
34676
  }
34339
34677
  forkSession({ sessionKey }) {
34340
34678
  return this.opts.sessionManager.createForkSession(sessionKey);
@@ -34541,7 +34879,8 @@ var ClaudeCodeAdapter = class {
34541
34879
  const env = buildSpawnEnv(process.env, this.opts.claudeHome, this.buildPlaceholderContext(sessionKey), {
34542
34880
  allowApiKey: this.opts.allowApiKey,
34543
34881
  effortLevel: this._effortLevel,
34544
- wikiMountRoot: this.opts.workspaceDir
34882
+ wikiMountRoot: this.opts.workspaceDir,
34883
+ capabilityBinDir: this.opts.capabilityBinDir
34545
34884
  });
34546
34885
  log2?.info(`spawn long-lived ${this.opts.claudeBin} (session ${sessionKey}, model=${this._model || "default"}, effort=${this._effortLevel || "default"}, mode=${this.opts.permissionMode})`);
34547
34886
  const proc = spawn(IS_WIN32 ? quoteWin32Arg(this.opts.claudeBin) : this.opts.claudeBin, IS_WIN32 ? args.map(quoteWin32Arg) : args, {
@@ -34620,7 +34959,7 @@ var ClaudeCodeAdapter = class {
34620
34959
  if (this.opts.disallowedTools.length > 0) {
34621
34960
  args.push("--disallowedTools", this.opts.disallowedTools.join(","));
34622
34961
  }
34623
- args.push("--append-system-prompt-file", path7.join(this.opts.workspaceDir, ".parall", "system-prompt.md"));
34962
+ args.push("--append-system-prompt-file", path8.join(this.opts.workspaceDir, ".parall", "system-prompt.md"));
34624
34963
  if (this.opts.appendSystemPrompt) {
34625
34964
  args.push("--append-system-prompt", this.opts.appendSystemPrompt);
34626
34965
  }
@@ -34652,8 +34991,8 @@ var ClaudeCodeAdapter = class {
34652
34991
  };
34653
34992
 
34654
34993
  // ts/claude-agent/dist/session-manager.js
34655
- import * as fs7 from "node:fs";
34656
- import * as path8 from "node:path";
34994
+ import * as fs8 from "node:fs";
34995
+ import * as path9 from "node:path";
34657
34996
  import { randomUUID as randomUUID2 } from "node:crypto";
34658
34997
  var ClaudeSessionManager = class _ClaudeSessionManager {
34659
34998
  mainSessionKey;
@@ -34802,13 +35141,13 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
34802
35141
  clearMainSession() {
34803
35142
  this.sessionIds.delete(this.mainSessionKey);
34804
35143
  try {
34805
- fs7.unlinkSync(this.stateFilePath);
35144
+ fs8.unlinkSync(this.stateFilePath);
34806
35145
  } catch {
34807
35146
  }
34808
35147
  }
34809
35148
  restore() {
34810
35149
  try {
34811
- const raw = fs7.readFileSync(this.stateFilePath, "utf8");
35150
+ const raw = fs8.readFileSync(this.stateFilePath, "utf8");
34812
35151
  const parsed = JSON.parse(raw);
34813
35152
  if (parsed.runtimeKey === this.mainSessionKey && typeof parsed.sessionId === "string" && parsed.sessionId.trim()) {
34814
35153
  this.sessionIds.set(this.mainSessionKey, parsed.sessionId.trim());
@@ -34818,8 +35157,8 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
34818
35157
  }
34819
35158
  persist(sessionId) {
34820
35159
  try {
34821
- fs7.mkdirSync(path8.dirname(this.stateFilePath), { recursive: true });
34822
- fs7.writeFileSync(this.stateFilePath, JSON.stringify({
35160
+ fs8.mkdirSync(path9.dirname(this.stateFilePath), { recursive: true });
35161
+ fs8.writeFileSync(this.stateFilePath, JSON.stringify({
34823
35162
  runtimeKey: this.mainSessionKey,
34824
35163
  sessionId
34825
35164
  }, null, 2));
@@ -34830,22 +35169,31 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
34830
35169
  };
34831
35170
 
34832
35171
  // ts/claude-agent/dist/workspace.js
34833
- import * as fs8 from "node:fs";
34834
- import * as path9 from "node:path";
34835
- function ensureClaudeWorkspace(workspaceDir, log2, agentIdentity) {
34836
- const systemPrompt = [
35172
+ import * as fs9 from "node:fs";
35173
+ import * as path10 from "node:path";
35174
+ function buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
35175
+ const parts = [
34837
35176
  buildIdentity(agentIdentity),
34838
35177
  BRIDGE_WORKSPACE_INSTRUCTIONS,
34839
35178
  PRLL_BEHAVIOR,
34840
- PRLL_REFERENCE_GUIDE,
34841
- buildSkillReferences(workspaceDir)
34842
- ].join("\n\n");
34843
- fs8.mkdirSync(workspaceDir, { recursive: true });
34844
- fs8.mkdirSync(path9.join(workspaceDir, ".claude"), { recursive: true });
34845
- const parallDir = path9.join(workspaceDir, ".parall");
34846
- fs8.mkdirSync(parallDir, { recursive: true });
34847
- fs8.writeFileSync(path9.join(parallDir, "system-prompt.md"), systemPrompt, "utf8");
34848
- writeSkillFiles(path9.join(parallDir, "skills"));
35179
+ PRLL_REFERENCE_GUIDE
35180
+ ];
35181
+ if (capabilityFragments && capabilityFragments.length > 0) {
35182
+ parts.push(capabilityFragments.join("\n\n"));
35183
+ }
35184
+ parts.push(buildSkillReferences(workspaceDir));
35185
+ return parts.join("\n\n");
35186
+ }
35187
+ function writeClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
35188
+ const parallDir = path10.join(workspaceDir, ".parall");
35189
+ fs9.mkdirSync(parallDir, { recursive: true });
35190
+ fs9.writeFileSync(path10.join(parallDir, "system-prompt.md"), buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments), "utf8");
35191
+ }
35192
+ function ensureClaudeWorkspace(workspaceDir, log2, agentIdentity, capabilityFragments) {
35193
+ fs9.mkdirSync(workspaceDir, { recursive: true });
35194
+ fs9.mkdirSync(path10.join(workspaceDir, ".claude"), { recursive: true });
35195
+ writeClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments);
35196
+ writeSkillFiles(path10.join(workspaceDir, ".parall", "skills"));
34849
35197
  ensureLocalAttachmentGitExclude(workspaceDir);
34850
35198
  }
34851
35199
 
@@ -34900,11 +35248,11 @@ async function main() {
34900
35248
  const agentUserId = me.id;
34901
35249
  const agentLog = childLogger(activeLog, agentUserId);
34902
35250
  activeLog = agentLog;
34903
- ensureClaudeWorkspace(config.workspaceDir, agentLog, {
35251
+ const agentIdentity = {
34904
35252
  userId: agentUserId,
34905
35253
  displayName: me.display_name,
34906
35254
  description: me.agent_profile?.description ?? void 0
34907
- });
35255
+ };
34908
35256
  const runtimeKey = config.runtimeKey || buildClaudeRuntimeKey(agentUserId);
34909
35257
  const sessionStateFilePath = sessionStateFilePathForRuntime(config.stateDir, runtimeKey);
34910
35258
  const sessionManager = new ClaudeSessionManager(runtimeKey, sessionStateFilePath, agentLog);
@@ -34920,6 +35268,14 @@ async function main() {
34920
35268
  log: agentLog
34921
35269
  });
34922
35270
  const platformDefaults = await configMgr.fetch();
35271
+ const applyChannelCapabilities = () => {
35272
+ const caps = configMgr.capabilities();
35273
+ materializeChannelCapabilities(config.stateDir, caps, agentLog);
35274
+ return caps.map((c) => c.fragment);
35275
+ };
35276
+ const bootCapabilityFragments = applyChannelCapabilities();
35277
+ let lastCapabilityFragments = bootCapabilityFragments.join("\n\n");
35278
+ ensureClaudeWorkspace(config.workspaceDir, agentLog, agentIdentity, bootCapabilityFragments);
34923
35279
  const platformModelOverride = deriveModelIsPin(platformDefaults, me.agent_profile);
34924
35280
  const resolvedModel = resolveRuntimeModel(platformModelOverride, platformDefaults.model, config.model);
34925
35281
  const resolvedEffort = platformDefaults.thinkingEffort ?? (process.env.CLAUDE_CODE_EFFORT_LEVEL?.trim() || void 0);
@@ -34947,7 +35303,10 @@ async function main() {
34947
35303
  orgId: config.orgId,
34948
35304
  contextFilePathForSession: (sessionKey) => contextFilePathForSession(config.stateDir, sessionKey),
34949
35305
  stepIdFilePathForSession: (sessionKey) => stepIdFilePathForSession(config.stateDir, sessionKey),
34950
- contextDirPath: dispatchContextDirPath(config.stateDir)
35306
+ contextDirPath: dispatchContextDirPath(config.stateDir),
35307
+ // Constant PATH prepend; the directory's content (the lark-cli shim)
35308
+ // tracks capability grants, so add/remove reaches live subprocesses.
35309
+ capabilityBinDir: capabilityBinDir(config.stateDir)
34951
35310
  });
34952
35311
  if (resolvedEffort) {
34953
35312
  adapter.updateConfig({ effort: resolvedEffort });
@@ -34968,6 +35327,19 @@ async function main() {
34968
35327
  model: resolveRuntimeModel(isPin, updated.model, config.model) ?? null,
34969
35328
  effort: updated.thinkingEffort ?? localEffort
34970
35329
  });
35330
+ const fragments = applyChannelCapabilities();
35331
+ const joinedFragments = fragments.join("\n\n");
35332
+ let promptWritten = true;
35333
+ try {
35334
+ writeClaudeSystemPrompt(config.workspaceDir, agentIdentity, fragments);
35335
+ } catch (err) {
35336
+ promptWritten = false;
35337
+ agentLog.warn(`system prompt refresh write failed (retrying next refresh): ${String(err)}`);
35338
+ }
35339
+ if (promptWritten && joinedFragments !== lastCapabilityFragments) {
35340
+ lastCapabilityFragments = joinedFragments;
35341
+ adapter.requestProcessRestart();
35342
+ }
34971
35343
  };
34972
35344
  const gateway = new ParallAgentGateway({
34973
35345
  accountId: agentUserId,
@@ -34990,6 +35362,11 @@ async function main() {
34990
35362
  },
34991
35363
  dispatchAdapter: adapter,
34992
35364
  log: agentLog,
35365
+ // Live capability view for hint routing: the channel reply hint points
35366
+ // at the vendor CLI only while the grant is active (config manager
35367
+ // re-fetches on agent_config.update, so revocation reaches the very
35368
+ // next dispatch's hint).
35369
+ getCapabilityKeys: () => configMgr.capabilities().map((c) => c.key),
34993
35370
  shutdownDeadlineMs: parseShutdownDeadlineMs(process.env.PRLL_SHUTDOWN_DEADLINE_MS),
34994
35371
  forkDeadlineMs: parseForkDeadlineMs(process.env.PRLL_FORK_DEADLINE_MS),
34995
35372
  dispatchDeadlineMs: parseDispatchDeadlineMs(process.env.PRLL_DISPATCH_DEADLINE_MS),