@parall/parall 1.42.1 → 1.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17717,9 +17717,9 @@ var require_getMachineId_linux = __commonJS({
17717
17717
  var api_1 = (init_esm(), __toCommonJS(esm_exports));
17718
17718
  async function getMachineId() {
17719
17719
  const paths = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
17720
- for (const path8 of paths) {
17720
+ for (const path9 of paths) {
17721
17721
  try {
17722
- const result = await fs_1.promises.readFile(path8, { encoding: "utf8" });
17722
+ const result = await fs_1.promises.readFile(path9, { encoding: "utf8" });
17723
17723
  return result.trim();
17724
17724
  } catch (e) {
17725
17725
  api_1.diag.debug(`error reading machine id: ${e}`);
@@ -21122,7 +21122,7 @@ function appendRootPathToUrlIfNeeded(url) {
21122
21122
  return void 0;
21123
21123
  }
21124
21124
  }
21125
- function appendResourcePathToUrl(url, path8) {
21125
+ function appendResourcePathToUrl(url, path9) {
21126
21126
  try {
21127
21127
  new URL(url);
21128
21128
  } catch (_a) {
@@ -21132,11 +21132,11 @@ function appendResourcePathToUrl(url, path8) {
21132
21132
  if (!url.endsWith("/")) {
21133
21133
  url = url + "/";
21134
21134
  }
21135
- url += path8;
21135
+ url += path9;
21136
21136
  try {
21137
21137
  new URL(url);
21138
21138
  } catch (_b) {
21139
- diag2.warn("Configuration: Provided URL appended with '" + path8 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
21139
+ diag2.warn("Configuration: Provided URL appended with '" + path9 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
21140
21140
  return void 0;
21141
21141
  }
21142
21142
  return url;
@@ -26483,657 +26483,8 @@ function laneContextFilePath(contextDir, targetUri, threadRootId) {
26483
26483
  return path.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
26484
26484
  }
26485
26485
 
26486
- // ../agent-core/dist/session-state.js
26487
- function normalizeSessionKey(sessionKey) {
26488
- return sessionKey.toLowerCase();
26489
- }
26490
- var sessionChatIdMap = /* @__PURE__ */ new Map();
26491
- var sessionMessageIdMap = /* @__PURE__ */ new Map();
26492
- var dispatchMessageIdMap = /* @__PURE__ */ new Map();
26493
- var dispatchGroupKeyMap = /* @__PURE__ */ new Map();
26494
- var dispatchNoReplyMap = /* @__PURE__ */ new Map();
26495
- function setSessionChatId(sessionKey, chatId) {
26496
- sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
26497
- }
26498
- function getSessionChatId(sessionKey) {
26499
- return sessionChatIdMap.get(normalizeSessionKey(sessionKey));
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 getDispatchMessageId(sessionKey) {
26511
- return dispatchMessageIdMap.get(normalizeSessionKey(sessionKey));
26512
- }
26513
- function clearDispatchMessageId(sessionKey) {
26514
- dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
26515
- }
26516
- function setDispatchGroupKey(sessionKey, groupKey) {
26517
- dispatchGroupKeyMap.set(normalizeSessionKey(sessionKey), groupKey);
26518
- }
26519
- function getDispatchGroupKey(sessionKey) {
26520
- return dispatchGroupKeyMap.get(normalizeSessionKey(sessionKey));
26521
- }
26522
- function clearDispatchGroupKey(sessionKey) {
26523
- dispatchGroupKeyMap.delete(normalizeSessionKey(sessionKey));
26524
- }
26525
- function setDispatchNoReply(sessionKey, noReply) {
26526
- dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
26527
- }
26528
- function clearDispatchNoReply(sessionKey) {
26529
- dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
26530
- }
26531
- var dispatchMetricsMap = /* @__PURE__ */ new Map();
26532
- function resetDispatchMetrics(sessionKey) {
26533
- dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
26534
- deliver_text_chunks: 0,
26535
- deliver_text_chars: 0,
26536
- message_send_attempts: 0,
26537
- message_send_successes: 0,
26538
- no_reply_called: false,
26539
- tool_call_count: 0,
26540
- started_at: Date.now()
26541
- });
26542
- }
26543
- function getDispatchMetrics(sessionKey) {
26544
- return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26545
- }
26546
- function clearDispatchMetrics(sessionKey) {
26547
- dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
26548
- }
26549
- function recordDeliverText(sessionKey, charCount) {
26550
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26551
- if (!m)
26552
- return;
26553
- m.deliver_text_chunks++;
26554
- m.deliver_text_chars += charCount;
26555
- }
26556
- function recordMessageSend(sessionKey, success) {
26557
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26558
- if (!m)
26559
- return;
26560
- m.message_send_attempts++;
26561
- if (success)
26562
- m.message_send_successes++;
26563
- }
26564
- function recordNoReply(sessionKey) {
26565
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26566
- if (!m)
26567
- return;
26568
- m.no_reply_called = true;
26569
- }
26570
- function recordToolCall(sessionKey) {
26571
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26572
- if (!m)
26573
- return;
26574
- m.tool_call_count++;
26575
- }
26576
-
26577
- // ../agent-core/dist/routing.js
26578
- var MAX_CONCURRENT_FORKS = 20;
26579
- var defaultRoutingStrategy = (event, state) => {
26580
- if (state.mainCurrentTargetId === event.targetId) {
26581
- return { action: "buffer-main" };
26582
- }
26583
- const existingForkKey = state.activeForks.get(event.targetId);
26584
- if (existingForkKey)
26585
- return { action: "buffer-fork", forkKey: existingForkKey };
26586
- if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
26587
- return { action: "buffer-main" };
26588
- }
26589
- return { action: "new-fork" };
26590
- };
26591
- function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
26592
- const existingForkKey = state.activeForks.get(event.targetId);
26593
- if (existingForkKey)
26594
- return { action: "buffer-fork", forkKey: existingForkKey };
26595
- if (!state.mainDispatching)
26596
- return { action: "main" };
26597
- return strategy(event, state);
26598
- }
26599
-
26600
- // ../agent-core/dist/event-format.js
26601
- function sanitizeMeta(value) {
26602
- return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
26603
- }
26604
- function buildEventBody(event) {
26605
- const lines = [];
26606
- if (event.type === "message") {
26607
- lines.push(`[Event: message.new]`);
26608
- const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
26609
- lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
26610
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26611
- lines.push(`[Message ID: prll://${event.messageId}]`);
26612
- if (event.threadRootId) {
26613
- const threadMeta = [
26614
- `prll://${event.threadRootId}`,
26615
- event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
26616
- event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
26617
- event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
26618
- ].filter(Boolean).join(" | ");
26619
- lines.push(`[Thread: ${threadMeta}]`);
26620
- }
26621
- if (event.unreadCount != null && event.unreadCount > 1) {
26622
- const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
26623
- const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
26624
- let line = `[Unread: ${countStr} messages${sinceStr}]`;
26625
- if (event.unreadCount > 50)
26626
- line += ` \u2014 fetch recent context with --limit, not all`;
26627
- lines.push(line);
26628
- }
26629
- if (event.noReply)
26630
- lines.push(`[Hint: no_reply]`);
26631
- if (event.attachments?.length) {
26632
- for (const att of event.attachments) {
26633
- const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
26634
- lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
26635
- }
26636
- }
26637
- lines.push("", event.body);
26638
- } else if (event.type === "task_comment") {
26639
- lines.push(`[Event: task.comment.created]`);
26640
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
26641
- lines.push(`[Task: ${taskLabel}]`);
26642
- if (event.deliveryReason)
26643
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
26644
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26645
- lines.push(`[Comment ID: prll://${event.messageId}]`);
26646
- lines.push("", event.body);
26647
- } else if (event.type === "wiki_comment") {
26648
- lines.push(`[Event: wiki.comment.created]`);
26649
- const target = event.replyTargetUri ?? `prll://${event.targetId}`;
26650
- if (event.targetType === "changeset") {
26651
- lines.push(`[Wiki Changeset: ${target}]`);
26652
- } else {
26653
- lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
26654
- }
26655
- if (event.deliveryReason)
26656
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
26657
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26658
- lines.push(`[Comment ID: prll://${event.messageId}]`);
26659
- lines.push("", event.body);
26660
- } else if (event.type === "approval") {
26661
- lines.push(`[Event: approval.decided]`);
26662
- lines.push(`[Approval: prll://${event.messageId}]`);
26663
- lines.push(`[Chat: prll://${event.targetId}]`);
26664
- lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
26665
- lines.push("", event.body);
26666
- } else if (event.type === "schedule") {
26667
- lines.push(`[Event: schedule.fired]`);
26668
- lines.push(`[Schedule: prll://${event.targetId}]`);
26669
- lines.push(`[Run: prll://${event.messageId}]`);
26670
- if (event.scheduledFireAt)
26671
- lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
26672
- if (event.attachedUri)
26673
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
26674
- lines.push("", event.body);
26675
- } else if (event.type === "channel_message") {
26676
- lines.push(`[Event: channel.message]`);
26677
- const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
26678
- const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
26679
- lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
26680
- lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
26681
- if (event.channelExternalMessageId) {
26682
- lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
26683
- }
26684
- 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.]`);
26685
- lines.push("", event.body);
26686
- } else if (event.type === "external_trigger") {
26687
- lines.push(`[Event: external.trigger]`);
26688
- lines.push(`[Trigger: prll://${event.targetId}]`);
26689
- lines.push(`[Run: prll://${event.messageId}]`);
26690
- if (event.externalConnectionId) {
26691
- const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
26692
- lines.push(`[Connection: ${label}]`);
26693
- }
26694
- if (event.externalIngressEventId)
26695
- lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
26696
- if (event.attachedUri)
26697
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
26698
- if (event.externalConnectionSourceType) {
26699
- lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
26700
- }
26701
- if (event.externalIngressEventType) {
26702
- lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
26703
- }
26704
- lines.push("", event.body);
26705
- } else {
26706
- lines.push(`[Event: task.assigned]`);
26707
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
26708
- lines.push(`[Task: ${taskLabel}]`);
26709
- lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
26710
- lines.push("", event.body);
26711
- }
26712
- return lines.join("\n") + buildSendMessageHint(event);
26713
- }
26714
- function buildEventBodyForForkResult(event) {
26715
- return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
26716
- }
26717
- function buildSendMessageHint(event) {
26718
- if (event.noReply)
26719
- return "";
26720
- if (event.type === "wiki_comment" && event.replyTargetUri) {
26721
- const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
26722
- return `
26723
- <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>`;
26724
- }
26725
- if (event.targetId.startsWith("cht_")) {
26726
- if (event.threadRootId) {
26727
- return `
26728
- <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>`;
26729
- }
26730
- return `
26731
- <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>`;
26732
- }
26733
- if (event.targetId.startsWith("tsk_")) {
26734
- return `
26735
- <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>`;
26736
- }
26737
- if (event.targetId.startsWith("sch_")) {
26738
- return `
26739
- <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
26740
- }
26741
- if (event.type === "channel_message") {
26742
- const clipLabel = event.channelProvider ? `the \`${event.channelProvider}\` clip's` : "your channel provider clip's";
26743
- const apiLabel = event.channelProvider ?? "external platform";
26744
- const target = event.channelExternalConversationId ? `{"chat_id": "${event.channelExternalConversationId}", "text": "..."}` : `{"chat_id": "<conversation id>", "text": "..."}`;
26745
- const threadAlt = event.channelExternalMessageId ? ` To reply in-thread to this specific message, use {"message_id": "${event.channelExternalMessageId}", "text": "..."} instead.` : "";
26746
- return `
26747
- <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>`;
26748
- }
26749
- if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
26750
- return `
26751
- <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>`;
26752
- }
26753
- return "";
26754
- }
26755
- function buildForkScopePrefix(event) {
26756
- const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
26757
- 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.
26758
-
26759
- 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.
26760
-
26761
- End with a brief "Fork summary" of actions taken and decisions made.]
26762
-
26763
- `;
26764
- }
26765
- function buildForkResultPrefix(results) {
26766
- if (!results.length)
26767
- return "";
26768
- const blocks = results.map((result) => {
26769
- const lines = [];
26770
- for (const body of result.eventBodies) {
26771
- lines.push(body);
26772
- }
26773
- lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
26774
- 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."}]`);
26775
- if (result.actions.length)
26776
- lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
26777
- if (result.historyPath)
26778
- lines.push(`[Fork history: ${result.historyPath}]`);
26779
- return lines.join("\n");
26780
- });
26781
- return blocks.join("\n\n") + "\n\n---\n\n";
26782
- }
26783
-
26784
- // ../agent-core/dist/prompt-fragments.js
26785
- var PRLL_IDENTITY_BASE = `## You on Parall
26786
-
26787
- Parall is a shared workspace where humans and agents work side by side as equals.
26788
- You are a participant here, not a service. You hold tasks, own decisions, and are
26789
- accountable for the work you take on \u2014 the same way a human teammate is.
26790
-
26791
- The people and agents around you are collaborators, not users to serve. Be honest,
26792
- be direct, and care about the outcome of the work \u2014 not just the request in front
26793
- of you.`;
26794
- function sanitizeProfileField(value) {
26795
- return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
26796
- }
26797
- function sanitizeProfileBlock(value) {
26798
- return value.replace(/\r\n?/g, "\n").trim();
26799
- }
26800
- function buildIdentity(agent) {
26801
- if (!agent)
26802
- return PRLL_IDENTITY_BASE;
26803
- const name = sanitizeProfileField(agent.displayName);
26804
- const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
26805
- lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
26806
- if (agent.description) {
26807
- const description = sanitizeProfileBlock(agent.description);
26808
- if (description) {
26809
- lines.push("", "### Your Agent Profile", "", description);
26810
- }
26811
- }
26812
- lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
26813
- return lines.join("\n");
26814
- }
26815
- var PRLL_BEHAVIOR = `## How to work here
26816
-
26817
- ### Move work forward
26818
- Don't wait for instructions. If you see the next step, take it. If something is
26819
- ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
26820
- \u2014 don't go silent. Initiative is expected.
26821
-
26822
- Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
26823
- requests, verifying something landed. When a thing needs future attention and
26824
- nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
26825
-
26826
- ### Work in the open
26827
- Nothing you do exists until the system can see it. Your progress, decisions,
26828
- blockers, and results need to live in tasks, comments, messages, or wiki pages
26829
- \u2014 otherwise the organization is blind to your work, and so is the next agent
26830
- who picks up where you left off. Leave traces as you go, not at the end.
26831
-
26832
- For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
26833
- when status materially changes, close it when done, and link the origin that
26834
- triggered it. Decompose multi-step work into subtasks and keep their statuses
26835
- current \u2014 progress should be auditable without watching the work happen.
26836
- Details: load the \`parall-tasks\` skill.
26837
-
26838
- ### Done means landed
26839
- Producing output does not complete a task. Work counts as done only when it has
26840
- cleared its remaining gates \u2014 review, merge, deployment, the requester's
26841
- verification. Until then keep the status honest (\`in_progress\` or
26842
- \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
26843
- self-reminder if nothing else will prompt follow-up). Never mark done what a
26844
- human still has to accept.
26845
-
26846
- ### Sessions, forks, and what survives
26847
- Sessions end and context compacts. Anything that must survive \u2014 decisions,
26848
- progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
26849
- read the workspace, not this conversation.
26850
-
26851
- Some events are handled by parallel fork sessions \u2014 short-lived copies of the
26852
- same agent identity with separate context. In a fork: leave a written trace of
26853
- what was done or deliberately not done (other sessions cannot see fork
26854
- context), and do not start long-running processes \u2014 they die with the fork.
26855
- When an event is marked fork-handled: do not re-handle it; verify its outcome
26856
- instead of assuming it.
26857
-
26858
- ### Communicate like a teammate
26859
- Match the conversation \u2014 concise in chat, thorough in docs, plain language over
26860
- jargon. Say what matters; stop when you're done. Don't narrate every tool call
26861
- or pad replies to seem thorough.
26862
-
26863
- Match the language of the person you're replying to. If someone writes in
26864
- Chinese, reply in Chinese. If in English, reply in English. Never force a
26865
- language switch unless explicitly asked.
26866
-
26867
- Do not promise delivery times ("in an hour", "by tonight") unless the work is
26868
- driven by an explicit schedule. Scope visibly; report when actually done.
26869
-
26870
- ### Keep topics in threads
26871
- Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
26872
- Present \u2192 that thread is the context; reply there, passing the same root as
26873
- \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
26874
- never treat it as continuing your most recent thread. The sender's newest
26875
- message is the anchor \u2014 never route a reply back into an older thread just
26876
- because the topic used to live there.
26877
-
26878
- Reply where the event lives: a thread message gets a thread reply, a
26879
- top-level message gets a top-level reply. But in group chats, your later
26880
- follow-up on that topic \u2014 progress updates, analysis, links, verification you
26881
- post afterwards \u2014 belongs in a thread rooted at the topic's message
26882
- (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
26883
- the main channel stays scannable. Post follow-up at top level only when
26884
- starting a genuinely new topic, making a channel-wide announcement, or when
26885
- explicitly asked. Never post the same update in both the thread and the main
26886
- channel \u2014 thread replies surface in the thread panel; no need to duplicate
26887
- for visibility.
26888
-
26889
- In DMs, reply top-level by default; use a thread only to continue one that
26890
- already exists.
26891
-
26892
- ### Group chats: mentions and unaddressed work
26893
- An @mention is a direct request \u2014 act on it. A group message delivered to you
26894
- without an @mention means the chat's routing lets you see the conversation:
26895
- decide whether a reply adds value; silence is the default.
26896
-
26897
- A message without an @mention is not an open invitation. Judge from context
26898
- who the work belongs to \u2014 the named domain, the topic's owner, whoever is
26899
- already on it. If it belongs to someone else, leave it. If genuinely unclear,
26900
- ask or claim in one line ("taking this unless someone else has it") before
26901
- starting \u2014 asking first beats duplicated or misdirected work.
26902
-
26903
- ### Verify before you act
26904
- Events can be redelivered \u2014 before acting, check whether it was already
26905
- handled (your own recent replies, task comments); if handled, do nothing.
26906
- Sends can fail silently, and creates can error after succeeding server-side \u2014
26907
- check the chat or entity before retrying. Never blind-retry a mutating call.
26908
-
26909
- ### Gather the full picture first
26910
- When a request is vague, an entity may already exist, or work may already be
26911
- underway \u2014 gather context before acting: search (\`parall search "..."\`),
26912
- check existing tasks/chats/wiki, read the surrounding conversation. Act on the
26913
- full picture, not the fragment that arrived in the event.
26914
-
26915
- ### Report only work that ran
26916
- If a scheduled job, scan, or tool call did not actually run \u2014 restarted
26917
- session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
26918
- or approximate results of work that did not execute.
26919
-
26920
- ### Respect what's shared
26921
- You have broad latitude inside your own work. But actions that are visible to
26922
- others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
26923
- wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
26924
- acting, unless you've been explicitly authorized.
26925
-
26926
- ### Shared workspace
26927
- Other agents share this workspace. Before starting work, check whether someone
26928
- \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
26929
-
26930
- ### Permissions and approvals
26931
- You have real permissions based on your roles (chat member/admin, org member).
26932
- If you lack permission for an action, the API returns PERMISSION_DENIED with the
26933
- \`action\` and \`resource_uri\` that were denied. The server decides whether that
26934
- action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
26935
- fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
26936
- it to ask someone with permission. If it is NOT approvable, the output says so;
26937
- ask a human with permission instead of requesting approval. A
26938
- \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
26939
- (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
26940
- \`dm\` for a user). Don't retry or work around a denial; only request approval
26941
- after an actual denial, never preemptively.
26942
-
26943
- ### When in doubt
26944
- Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
26945
- credibility is what you bring to the workspace \u2014 protect it.`;
26946
- var PRLL_REFERENCE_GUIDE = `## Parall References
26947
-
26948
- Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
26949
- entities when you create or update tasks, comments, messages, and wiki files.
26950
-
26951
- All three forms work \u2014 pick whichever fits:
26952
-
26953
- prll://tsk_abc bare URI (auto-linked)
26954
- [](prll://tsk_abc) empty context (renders resolved title)
26955
- [relevant context](prll://tsk_abc) with author annotation
26956
-
26957
- Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
26958
- resolves and renders the entity title automatically.
26959
-
26960
- ### URI format
26961
-
26962
- \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
26963
-
26964
- **Entities** \u2014 the entity ID is the authority:
26965
-
26966
- prll://usr_xxx user prll://prj_xxx project
26967
- prll://tsk_xxx task prll://wik_xxx wiki
26968
- prll://msg_xxx message prll://tcm_xxx task comment
26969
- prll://cht_xxx chat prll://ase_xxx agent session
26970
- prll://att_xxx attachment prll://sch_xxx schedule
26971
- prll://srn_xxx schedule run
26972
-
26973
- **Wiki** \u2014 path is file path, fragment is a typed anchor:
26974
-
26975
- prll://wik_xxx/docs/guide.md file
26976
- prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
26977
- prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
26978
-
26979
- Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
26980
- Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
26981
-
26982
- **Chat message range**:
26983
-
26984
- prll://cht_xxx#range=msg_01HA,msg_01HZ
26985
-
26986
- **Field access** \u2014 path selects a field (omit to reference the entity itself):
26987
-
26988
- prll://tsk_xxx/description#Implementation heading within task description
26989
-
26990
- ### Unread context
26991
-
26992
- When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
26993
- This shows messages since your last interaction \u2014 your read cursor advances after each
26994
- dispatch, so context you skip now won't appear as unread next time. Use
26995
- \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
26996
- counts (50+), fetch only recent messages rather than everything.
26997
-
26998
- Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
26999
- Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
27000
- catch up on the thread.
27001
-
27002
- ### Reading context on demand
27003
-
27004
- An event only carries the single triggering message. If you're mentioned in a
27005
- group chat and lack context, pull what you need from the chat \u2014 don't guess:
27006
-
27007
- parall messages list cht_xxx --limit 20 --before msg_xxx
27008
- parall messages get msg_xxx
27009
- parall chats get cht_xxx
27010
-
27011
- Rule of thumb: in a group chat mention, the conversation that led up to you
27012
- being called almost always matters \u2014 read it before replying. In a DM, your
27013
- session already has continuity, so skip the fetch unless something is unclear.
27014
-
27015
- Same pattern for any other entity referenced in the event: \`tasks get\`,
27016
- \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
27017
-
27018
- ### Find context with search first
27019
-
27020
- Reach for unified semantic search before paging chat history:
27021
-
27022
- parall search "pricing decision june" [--limit 10]
27023
-
27024
- It spans messages, tasks, and wiki. Page \`messages list\` only for the verbatim
27025
- recent flow of one chat, not for discovery.
27026
-
27027
- ### File attachments
27028
-
27029
- Messages may include attachments. They appear in events as:
27030
-
27031
- [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
27032
-
27033
- To download an attachment, use the CLI:
27034
-
27035
- parall files download att_xxx --output /tmp/screenshot.png
27036
-
27037
- To send a file:
27038
-
27039
- parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
27040
-
27041
- Or upload first and reuse across chats:
27042
-
27043
- parall files upload /tmp/report.pdf
27044
- parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
27045
- parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
27046
-
27047
- 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 \`$(...)\`.
27048
-
27049
- ### When to reference
27050
-
27051
- - **Origin** \u2014 always link the message or task that triggered your work
27052
- - **Design docs / wiki** \u2014 link specs and guides relevant to the work
27053
- - **Related tasks** \u2014 link parent, sibling, or blocking tasks
27054
- - **People** \u2014 link assignees or stakeholders when mentioning them
27055
- - **Conversations** \u2014 link a chat or message range as context
27056
-
27057
- ### Why this matters
27058
-
27059
- Other agents and humans read your output. References build a navigable context graph \u2014
27060
- in multi-agent workflows, your references are the map that the next agent follows.`;
27061
- function renderLocalAttachmentSection(section) {
27062
- if (section.images.length === 0 && section.notes.length === 0)
27063
- return "";
27064
- const lines = ["[Local attachment files]"];
27065
- for (const image of section.images) {
27066
- lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
27067
- }
27068
- lines.push(...section.notes);
27069
- return lines.join("\n");
27070
- }
27071
- function sanitizePromptMeta(value) {
27072
- return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
27073
- }
27074
- function formatBytes(bytes) {
27075
- if (bytes >= 1048576)
27076
- return `${(bytes / 1048576).toFixed(1)}MB`;
27077
- if (bytes >= 1024)
27078
- return `${Math.round(bytes / 1024)}KB`;
27079
- return `${bytes}B`;
27080
- }
27081
-
27082
- // ../agent-core/dist/bridge-workspace.js
27083
- function extractShellCommand(input) {
27084
- if (!input || typeof input !== "object")
27085
- return void 0;
27086
- const command = input.command;
27087
- return typeof command === "string" && command.trim() ? command.trim() : void 0;
27088
- }
27089
- function parseParallCliInvocation(command) {
27090
- const tokens = command.replace(/\s+/g, " ").trim().split(" ");
27091
- let i = 0;
27092
- if (tokens[i] === "parall") {
27093
- i++;
27094
- } else if (tokens[i] === "npx") {
27095
- i++;
27096
- while (i < tokens.length && tokens[i].startsWith("-"))
27097
- i++;
27098
- if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
27099
- return null;
27100
- i++;
27101
- } else if (tokens[i] === "pnpm") {
27102
- i++;
27103
- if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
27104
- i++;
27105
- if (i >= tokens.length || tokens[i] !== "parall")
27106
- return null;
27107
- i++;
27108
- } else {
27109
- return null;
27110
- }
27111
- return tokens.slice(i).filter((t) => !t.startsWith("-"));
27112
- }
27113
- function isParallSendCommand(command) {
27114
- if (!command)
27115
- return false;
27116
- const sub = parseParallCliInvocation(command);
27117
- if (!sub || sub.length === 0)
27118
- return false;
27119
- return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
27120
- }
27121
- function isParallNoReplyCommand(command) {
27122
- if (!command)
27123
- return false;
27124
- const sub = parseParallCliInvocation(command);
27125
- return sub?.[0] === "no-reply";
27126
- }
27127
-
27128
- // ../agent-core/dist/dispatch-adapter.js
27129
- function buildErrorStepContent(message) {
27130
- return { text: message, suppressed: false, status: "error" };
27131
- }
27132
-
27133
- // ../agent-core/dist/gateway-base.js
27134
- import * as os from "node:os";
27135
- import * as fs2 from "node:fs";
27136
- import * as path2 from "node:path";
26486
+ // ../agent-core/dist/lane-ledger.js
26487
+ import * as fs from "node:fs";
27137
26488
 
27138
26489
  // ../sdk/dist/types.js
27139
26490
  var MENTION_ALL_USER_ID = "all";
@@ -27579,6 +26930,7 @@ var ParallClient = class _ParallClient {
27579
26930
  setTokens;
27580
26931
  refreshPromise = null;
27581
26932
  swimlaneName;
26933
+ getFeatureFlagOverrides;
27582
26934
  /** Auth endpoints excluded from automatic 401 refresh to prevent recursion. */
27583
26935
  static AUTH_PATHS = /* @__PURE__ */ new Set([
27584
26936
  "/auth/login",
@@ -27609,7 +26961,7 @@ var ParallClient = class _ParallClient {
27609
26961
  return apiError;
27610
26962
  }
27611
26963
  /** Build headers common to all requests (auth, swimlane). */
27612
- buildHeaders(extra) {
26964
+ buildHeaders(path9, extra) {
27613
26965
  const headers = {
27614
26966
  "Content-Type": "application/json",
27615
26967
  ...extra
@@ -27620,6 +26972,11 @@ var ParallClient = class _ParallClient {
27620
26972
  if (this.swimlaneName) {
27621
26973
  headers["X-Prll-Swimlane"] = this.swimlaneName;
27622
26974
  }
26975
+ if (path9.startsWith(API_BASE)) {
26976
+ const overrides = this.getFeatureFlagOverrides?.();
26977
+ if (overrides)
26978
+ headers["X-Prll-FF-Override"] = overrides;
26979
+ }
27623
26980
  return headers;
27624
26981
  }
27625
26982
  constructor(options = {}) {
@@ -27630,6 +26987,7 @@ var ParallClient = class _ParallClient {
27630
26987
  this.getRefreshToken = options.getRefreshToken;
27631
26988
  this.setTokens = options.setTokens;
27632
26989
  this.swimlaneName = options.swimlaneName;
26990
+ this.getFeatureFlagOverrides = options.getFeatureFlagOverrides;
27633
26991
  }
27634
26992
  /**
27635
26993
  * Pick the origin for a request path: wiki-service base for `/wiki/v1`
@@ -27637,8 +26995,8 @@ var ParallClient = class _ParallClient {
27637
26995
  * is authoritative, so wiki vs api routing can't drift from how a caller
27638
26996
  * happens to invoke the client.
27639
26997
  */
27640
- baseUrlFor(path8) {
27641
- return path8.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
26998
+ baseUrlFor(path9) {
26999
+ return path9.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
27642
27000
  }
27643
27001
  setToken(token) {
27644
27002
  this.token = token;
@@ -27665,10 +27023,10 @@ var ParallClient = class _ParallClient {
27665
27023
  * REFRESH_THRESHOLD_S, refresh it **before** sending the request.
27666
27024
  * No-op when the token is still fresh, missing, or un-parseable.
27667
27025
  */
27668
- async ensureFreshToken(path8) {
27026
+ async ensureFreshToken(path9) {
27669
27027
  if (!this.token || !this.getRefreshToken)
27670
27028
  return;
27671
- const pathSuffix = path8.replace(/^\/api\/v1/, "");
27029
+ const pathSuffix = path9.replace(/^\/api\/v1/, "");
27672
27030
  if (_ParallClient.AUTH_PATHS.has(pathSuffix))
27673
27031
  return;
27674
27032
  const exp = _ParallClient.decodeJwtExp(this.token);
@@ -27700,11 +27058,11 @@ var ParallClient = class _ParallClient {
27700
27058
  this.refreshPromise = null;
27701
27059
  }
27702
27060
  }
27703
- async request(method, path8, body, query, retried = false, opts) {
27061
+ async request(method, path9, body, query, retried = false, opts) {
27704
27062
  if (!retried) {
27705
- await this.ensureFreshToken(path8);
27063
+ await this.ensureFreshToken(path9);
27706
27064
  }
27707
- let url = `${this.baseUrlFor(path8)}${path8}`;
27065
+ let url = `${this.baseUrlFor(path9)}${path9}`;
27708
27066
  if (query) {
27709
27067
  const params = new URLSearchParams();
27710
27068
  for (const [key, value] of Object.entries(query)) {
@@ -27716,7 +27074,7 @@ var ParallClient = class _ParallClient {
27716
27074
  if (qs)
27717
27075
  url += `?${qs}`;
27718
27076
  }
27719
- const headers = this.buildHeaders();
27077
+ const headers = this.buildHeaders(path9);
27720
27078
  const timeoutSignal = AbortSignal.timeout(opts?.timeoutMs ?? 15e3);
27721
27079
  const signal = opts?.signal ? AbortSignal.any([opts.signal, timeoutSignal]) : timeoutSignal;
27722
27080
  let res;
@@ -27734,12 +27092,12 @@ var ParallClient = class _ParallClient {
27734
27092
  throw _ParallClient.normalizeFetchError(err);
27735
27093
  }
27736
27094
  if (res.status === 401) {
27737
- const pathSuffix = path8.replace(/^\/api\/v1/, "");
27095
+ const pathSuffix = path9.replace(/^\/api\/v1/, "");
27738
27096
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
27739
27097
  if (!retried && !isAuthPath && this.getRefreshToken) {
27740
27098
  const refreshed = await this.tryRefresh();
27741
27099
  if (refreshed) {
27742
- return this.request(method, path8, body, query, true, opts);
27100
+ return this.request(method, path9, body, query, true, opts);
27743
27101
  }
27744
27102
  }
27745
27103
  if (this.onTokenExpired && !isAuthPath) {
@@ -27769,15 +27127,15 @@ var ParallClient = class _ParallClient {
27769
27127
  * hit the 100 MiB cap, so a longer 5-minute timeout is used so a
27770
27128
  * 50 MiB blob on a slow connection doesn't get chopped at 15 s.
27771
27129
  */
27772
- async multipartRequest(method, path8, body, retried = false) {
27130
+ async multipartRequest(method, path9, body, retried = false) {
27773
27131
  if (!retried) {
27774
- await this.ensureFreshToken(path8);
27132
+ await this.ensureFreshToken(path9);
27775
27133
  }
27776
- const { "Content-Type": _drop, ...headers } = this.buildHeaders();
27134
+ const { "Content-Type": _drop, ...headers } = this.buildHeaders(path9);
27777
27135
  void _drop;
27778
27136
  let res;
27779
27137
  try {
27780
- res = await fetch(`${this.baseUrlFor(path8)}${path8}`, {
27138
+ res = await fetch(`${this.baseUrlFor(path9)}${path9}`, {
27781
27139
  method,
27782
27140
  headers,
27783
27141
  body,
@@ -27787,12 +27145,12 @@ var ParallClient = class _ParallClient {
27787
27145
  throw _ParallClient.normalizeFetchError(err);
27788
27146
  }
27789
27147
  if (res.status === 401) {
27790
- const pathSuffix = path8.replace(/^\/api\/v1/, "");
27148
+ const pathSuffix = path9.replace(/^\/api\/v1/, "");
27791
27149
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
27792
27150
  if (!retried && !isAuthPath && this.getRefreshToken) {
27793
27151
  const refreshed = await this.tryRefresh();
27794
27152
  if (refreshed) {
27795
- return this.multipartRequest(method, path8, body, true);
27153
+ return this.multipartRequest(method, path9, body, true);
27796
27154
  }
27797
27155
  }
27798
27156
  if (this.onTokenExpired && !isAuthPath) {
@@ -28496,8 +27854,8 @@ var ParallClient = class _ParallClient {
28496
27854
  async requestMachineUpdate(orgId, machineId, mandatory = false) {
28497
27855
  await this.request("POST", ENDPOINTS.MACHINE_REQUEST_UPDATE(orgId, machineId), { mandatory });
28498
27856
  }
28499
- async browseMachineFilesystem(orgId, machineId, path8) {
28500
- return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path8 }, void 0, false, { timeoutMs: 15e3 });
27857
+ async browseMachineFilesystem(orgId, machineId, path9) {
27858
+ return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path9 }, void 0, false, { timeoutMs: 15e3 });
28501
27859
  }
28502
27860
  /** Create a new machine key. Returns the raw key string (shown once) + metadata. */
28503
27861
  async createMachineKey(orgId, machineId, name) {
@@ -28618,7 +27976,7 @@ var ParallClient = class _ParallClient {
28618
27976
  if (currentVersion !== void 0) {
28619
27977
  extra["If-None-Match"] = currentVersion;
28620
27978
  }
28621
- const headers = this.buildHeaders(extra);
27979
+ const headers = this.buildHeaders(ENDPOINTS.PLATFORM_CONFIG, extra);
28622
27980
  let res;
28623
27981
  try {
28624
27982
  res = await fetch(url, {
@@ -29066,8 +28424,8 @@ var ParallClient = class _ParallClient {
29066
28424
  async deleteWikiRestriction(orgId, wikiId, restrictionId) {
29067
28425
  await this.request("DELETE", ENDPOINTS.WIKI_RESTRICTION(orgId, wikiId, restrictionId));
29068
28426
  }
29069
- async getWikiAccessStatus(orgId, wikiId, path8) {
29070
- return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path8 ? { path: path8 } : void 0);
28427
+ async getWikiAccessStatus(orgId, wikiId, path9) {
28428
+ return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path9 ? { path: path9 } : void 0);
29071
28429
  }
29072
28430
  async createWikiAccessRequest(orgId, wikiId, data) {
29073
28431
  await this.request("POST", ENDPOINTS.WIKI_ACCESS_REQUESTS(orgId, wikiId), data);
@@ -29076,14 +28434,14 @@ var ParallClient = class _ParallClient {
29076
28434
  async getWikiCommits(orgId, wikiId, params) {
29077
28435
  return this.request("GET", ENDPOINTS.WIKI_COMMITS(orgId, wikiId), void 0, params);
29078
28436
  }
29079
- async getWikiFileCommits(orgId, wikiId, path8, params) {
28437
+ async getWikiFileCommits(orgId, wikiId, path9, params) {
29080
28438
  return this.request("GET", ENDPOINTS.WIKI_FILE_COMMITS(orgId, wikiId), void 0, {
29081
- path: path8,
28439
+ path: path9,
29082
28440
  ...params
29083
28441
  });
29084
28442
  }
29085
- async getWikiBlame(orgId, wikiId, path8, ref) {
29086
- return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path8, ref });
28443
+ async getWikiBlame(orgId, wikiId, path9, ref) {
28444
+ return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path9, ref });
29087
28445
  }
29088
28446
  // ---- Wiki Operations (audit log) ----
29089
28447
  async getWikiOperations(orgId, wikiId, params) {
@@ -29272,866 +28630,1585 @@ var ParallClient = class _ParallClient {
29272
28630
  async unbindAgentClip(orgId, agentId, clipId) {
29273
28631
  await this.request("DELETE", ENDPOINTS.AGENT_CLIP(orgId, agentId, clipId));
29274
28632
  }
29275
- async invokeClip(orgId, req) {
29276
- const serverTimeout = Math.max(req.timeout_ms ?? 3e4, 1e3);
29277
- const timeoutMs = serverTimeout + 5e3;
29278
- return this.request("POST", ENDPOINTS.CLIP_INVOKE(orgId), req, void 0, false, { timeoutMs });
28633
+ async invokeClip(orgId, req) {
28634
+ const serverTimeout = Math.max(req.timeout_ms ?? 3e4, 1e3);
28635
+ const timeoutMs = serverTimeout + 5e3;
28636
+ return this.request("POST", ENDPOINTS.CLIP_INVOKE(orgId), req, void 0, false, { timeoutMs });
28637
+ }
28638
+ async listOnlineClips(orgId) {
28639
+ const resp = await this.request("GET", ENDPOINTS.CLIP_ONLINE(orgId));
28640
+ return resp.data;
28641
+ }
28642
+ /** Deployment-wide hosted browser runtime availability — drives whether the
28643
+ * create UI offers the platform-hosted placement. Fail-closed server-side. */
28644
+ async getBrowserRuntimeStatus(orgId) {
28645
+ return this.request("GET", ENDPOINTS.BROWSER_RUNTIME_STATUS(orgId));
28646
+ }
28647
+ /** Org-wide browser-profile discovery list. Returns the sanitized
28648
+ * {@link BrowserProfileListItem} shape (not the full domain model), each row
28649
+ * carrying a per-viewer `can_open` control hint. */
28650
+ async listBrowserProfiles(orgId) {
28651
+ const resp = await this.request("GET", ENDPOINTS.BROWSER_PROFILES(orgId));
28652
+ return resp.data;
28653
+ }
28654
+ async createBrowserProfile(orgId, req) {
28655
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILES(orgId), req);
28656
+ }
28657
+ async getBrowserProfile(orgId, profileId) {
28658
+ return this.request("GET", ENDPOINTS.BROWSER_PROFILE(orgId, profileId));
28659
+ }
28660
+ async updateBrowserProfile(orgId, profileId, req) {
28661
+ return this.request("PATCH", ENDPOINTS.BROWSER_PROFILE(orgId, profileId), req);
28662
+ }
28663
+ async deleteBrowserProfile(orgId, profileId) {
28664
+ await this.request("DELETE", ENDPOINTS.BROWSER_PROFILE(orgId, profileId));
28665
+ }
28666
+ async openBrowserProfile(orgId, profileId, req = {}) {
28667
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILE_OPEN(orgId, profileId), req);
28668
+ }
28669
+ async stopBrowserProfile(orgId, profileId) {
28670
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILE_STOP(orgId, profileId), {});
28671
+ }
28672
+ async resetBrowserProfile(orgId, profileId) {
28673
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILE_RESET(orgId, profileId));
28674
+ }
28675
+ async listBrowserProfileConsents(orgId, profileId) {
28676
+ const resp = await this.request("GET", ENDPOINTS.BROWSER_PROFILE_CONSENTS(orgId, profileId));
28677
+ return resp.data;
28678
+ }
28679
+ async grantBrowserProfileConsent(orgId, profileId, req) {
28680
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILE_CONSENTS(orgId, profileId), req);
28681
+ }
28682
+ async revokeBrowserProfileConsent(orgId, profileId, clipId) {
28683
+ await this.request("DELETE", ENDPOINTS.BROWSER_PROFILE_CONSENT(orgId, profileId, clipId));
28684
+ }
28685
+ async listRegistryClips(q) {
28686
+ const url = ENDPOINTS.CLIP_REGISTRY() + (q ? `?q=${encodeURIComponent(q)}` : "");
28687
+ const resp = await this.request("GET", url);
28688
+ return resp.data;
28689
+ }
28690
+ // ---- Edge devices ----
28691
+ async listEdgeDevices(orgId) {
28692
+ return this.request("GET", ENDPOINTS.ORG_EDGE_DEVICES(orgId));
28693
+ }
28694
+ async getEdgeOnboarding(orgId) {
28695
+ return this.request("GET", ENDPOINTS.ORG_EDGE_ONBOARDING(orgId));
28696
+ }
28697
+ async listEdgeProfiles(orgId, edgeId) {
28698
+ return this.request("GET", ENDPOINTS.ORG_EDGE_PROFILES(orgId, edgeId));
28699
+ }
28700
+ // ---- Clip connections ----
28701
+ async listClipConnections(orgId, clipId) {
28702
+ return this.request("GET", ENDPOINTS.CLIP_CONNECTIONS(orgId, clipId));
28703
+ }
28704
+ async createClipConnection(orgId, clipId, input) {
28705
+ return this.request("POST", ENDPOINTS.CLIP_CONNECTIONS(orgId, clipId), input);
28706
+ }
28707
+ async deleteClipConnection(orgId, connId) {
28708
+ return this.request("DELETE", ENDPOINTS.CLIP_CONNECTION(orgId, connId));
28709
+ }
28710
+ };
28711
+ function normalizeWikiChangeset(changeset) {
28712
+ return {
28713
+ ...changeset,
28714
+ changed_paths: changeset.changed_paths ?? [],
28715
+ file_changes: changeset.file_changes ?? []
28716
+ };
28717
+ }
28718
+ var ApiError = class extends Error {
28719
+ status;
28720
+ code;
28721
+ extras;
28722
+ /** Attempted action (authorization denials) — e.g. "chat.add_member". */
28723
+ action;
28724
+ /** Target resource URI that was evaluated — e.g. "prll://cht_…". */
28725
+ resourceUri;
28726
+ /** Whether the action is approval-executable (PERMISSION_DENIED only). */
28727
+ approvable;
28728
+ constructor(status, message, code) {
28729
+ super(message);
28730
+ this.status = status;
28731
+ this.code = code;
28732
+ this.name = "ApiError";
28733
+ }
28734
+ };
28735
+ function buildApiError(res, rawErrorBody) {
28736
+ const errorBody = rawErrorBody !== null && typeof rawErrorBody === "object" ? rawErrorBody : {};
28737
+ const errorObj = errorBody.error && typeof errorBody.error === "object" ? errorBody.error : void 0;
28738
+ const errMsg = (typeof errorObj?.message === "string" ? errorObj.message : void 0) ?? (typeof errorBody.message === "string" ? errorBody.message : void 0) ?? (typeof errorBody.error === "string" ? errorBody.error : void 0);
28739
+ const errCode = (typeof errorObj?.code === "string" ? errorObj.code : void 0) ?? (typeof errorBody.code === "string" ? errorBody.code : void 0);
28740
+ const apiError = new ApiError(res.status, errMsg ?? res.statusText, errCode);
28741
+ const anchors = errorObj ?? errorBody;
28742
+ if (typeof anchors.action === "string")
28743
+ apiError.action = anchors.action;
28744
+ if (typeof anchors.resource_uri === "string")
28745
+ apiError.resourceUri = anchors.resource_uri;
28746
+ if (typeof anchors.approvable === "boolean")
28747
+ apiError.approvable = anchors.approvable;
28748
+ const structural = /* @__PURE__ */ new Set(["error", "code", "message", "status"]);
28749
+ const extras = {};
28750
+ for (const [k, v] of Object.entries(errorBody))
28751
+ if (!structural.has(k))
28752
+ extras[k] = v;
28753
+ if (errorObj) {
28754
+ for (const [k, v] of Object.entries(errorObj))
28755
+ if (!structural.has(k))
28756
+ extras[k] = v;
28757
+ }
28758
+ if (Object.keys(extras).length > 0)
28759
+ apiError.extras = extras;
28760
+ return apiError;
28761
+ }
28762
+
28763
+ // ../sdk/dist/ws.js
28764
+ function isRetryableNetworkError(err) {
28765
+ return err instanceof Error && err.name === "ApiError" && "status" in err && err.status === 0;
28766
+ }
28767
+ function isBrowserRuntime() {
28768
+ return typeof window !== "undefined";
28769
+ }
28770
+ var ParallWs = class {
28771
+ ws = null;
28772
+ options;
28773
+ listeners = /* @__PURE__ */ new Map();
28774
+ stateListeners = /* @__PURE__ */ new Set();
28775
+ heartbeatTimer = null;
28776
+ reconnectTimer = null;
28777
+ reconnectAttempts = 0;
28778
+ lastSeq = 0;
28779
+ _state = "disconnected";
28780
+ intentionalClose = false;
28781
+ lastReceivedAt = 0;
28782
+ heartbeatIntervalMs = 0;
28783
+ probeTimer = null;
28784
+ browserListenersActive = false;
28785
+ constructor(options) {
28786
+ this.options = {
28787
+ reconnect: true,
28788
+ reconnectInterval: 1e3,
28789
+ maxReconnectInterval: 3e4,
28790
+ ...options
28791
+ };
28792
+ this.lastSeq = options.lastSeq ?? 0;
28793
+ }
28794
+ get state() {
28795
+ return this._state;
29279
28796
  }
29280
- async listOnlineClips(orgId) {
29281
- const resp = await this.request("GET", ENDPOINTS.CLIP_ONLINE(orgId));
29282
- return resp.data;
28797
+ async connect() {
28798
+ this.intentionalClose = false;
28799
+ this.setupBrowserListeners();
28800
+ this.setState("connecting");
28801
+ let ticket;
28802
+ try {
28803
+ ticket = await this.options.getTicket();
28804
+ } catch (err) {
28805
+ if (isBrowserRuntime() && isRetryableNetworkError(err)) {
28806
+ console.warn("Failed to get WS ticket:", err);
28807
+ } else {
28808
+ console.error("Failed to get WS ticket:", err);
28809
+ }
28810
+ if (this.options.reconnect) {
28811
+ this.scheduleReconnect();
28812
+ } else {
28813
+ this.setState("disconnected");
28814
+ }
28815
+ return;
28816
+ }
28817
+ const wsUrl = ticket.ws_url || this.options.wsUrl;
28818
+ if (!wsUrl) {
28819
+ console.error("No WS URL available");
28820
+ this.setState("disconnected");
28821
+ return;
28822
+ }
28823
+ const url = new URL(wsUrl);
28824
+ url.searchParams.set("ticket", ticket.ticket);
28825
+ if (this.lastSeq > 0) {
28826
+ url.searchParams.set("last_seq", String(this.lastSeq));
28827
+ }
28828
+ this.ws = new WebSocket(url.toString());
28829
+ const ws = this.ws;
28830
+ const connectTimeout = setTimeout(() => {
28831
+ if (this._state === "connected" || this.intentionalClose)
28832
+ return;
28833
+ ws.onclose = null;
28834
+ ws.onopen = null;
28835
+ ws.onerror = null;
28836
+ try {
28837
+ ws.close();
28838
+ } catch {
28839
+ }
28840
+ if (ws !== this.ws)
28841
+ return;
28842
+ if (this.options.reconnect) {
28843
+ this.scheduleReconnect();
28844
+ } else {
28845
+ this.setState("disconnected");
28846
+ }
28847
+ }, 15e3);
28848
+ this.ws.onopen = () => {
28849
+ clearTimeout(connectTimeout);
28850
+ this.reconnectAttempts = 0;
28851
+ this.lastReceivedAt = Date.now();
28852
+ this.setState("connected");
28853
+ };
28854
+ this.ws.onmessage = (event) => {
28855
+ try {
28856
+ const frame = JSON.parse(event.data);
28857
+ this.handleFrame(frame);
28858
+ } catch {
28859
+ }
28860
+ };
28861
+ this.ws.onclose = () => {
28862
+ clearTimeout(connectTimeout);
28863
+ this.stopHeartbeat();
28864
+ this.clearProbe();
28865
+ if (this.intentionalClose) {
28866
+ this.setState("disconnected");
28867
+ return;
28868
+ }
28869
+ if (this.options.reconnect) {
28870
+ this.scheduleReconnect();
28871
+ } else {
28872
+ this.setState("disconnected");
28873
+ }
28874
+ };
28875
+ this.ws.onerror = () => {
28876
+ };
29283
28877
  }
29284
- /** Deployment-wide hosted browser runtime availability — drives whether the
29285
- * create UI offers the platform-hosted placement. Fail-closed server-side. */
29286
- async getBrowserRuntimeStatus(orgId) {
29287
- return this.request("GET", ENDPOINTS.BROWSER_RUNTIME_STATUS(orgId));
28878
+ disconnect() {
28879
+ this.intentionalClose = true;
28880
+ this.stopHeartbeat();
28881
+ this.clearReconnect();
28882
+ this.clearProbe();
28883
+ this.teardownBrowserListeners();
28884
+ if (this.ws) {
28885
+ this.ws.close();
28886
+ this.ws = null;
28887
+ }
28888
+ this.setState("disconnected");
29288
28889
  }
29289
- /** Org-wide browser-profile discovery list. Returns the sanitized
29290
- * {@link BrowserProfileListItem} shape (not the full domain model), each row
29291
- * carrying a per-viewer `can_open` control hint. */
29292
- async listBrowserProfiles(orgId) {
29293
- const resp = await this.request("GET", ENDPOINTS.BROWSER_PROFILES(orgId));
29294
- return resp.data;
28890
+ // ---- Client -> Server messages ----
28891
+ /** Tell the server which chats the user is currently viewing (no auth implications). */
28892
+ watch(chatIds) {
28893
+ this.send({ type: WS_EVENTS.WATCH, data: { chat_ids: chatIds } });
29295
28894
  }
29296
- async createBrowserProfile(orgId, req) {
29297
- return this.request("POST", ENDPOINTS.BROWSER_PROFILES(orgId), req);
28895
+ sendTyping(chatId, action, threadRootId) {
28896
+ this.send({
28897
+ type: WS_EVENTS.TYPING,
28898
+ data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
28899
+ });
29298
28900
  }
29299
- async getBrowserProfile(orgId, profileId) {
29300
- return this.request("GET", ENDPOINTS.BROWSER_PROFILE(orgId, profileId));
28901
+ /** Send an agent heartbeat with telemetry data. */
28902
+ sendAgentHeartbeat(sessionId, telemetry) {
28903
+ this.send({
28904
+ type: WS_EVENTS.AGENT_HEARTBEAT,
28905
+ data: { session_id: sessionId, telemetry }
28906
+ });
29301
28907
  }
29302
- async updateBrowserProfile(orgId, profileId, req) {
29303
- return this.request("PATCH", ENDPOINTS.BROWSER_PROFILE(orgId, profileId), req);
28908
+ sendEvent(type, data) {
28909
+ this.send({ type, data });
29304
28910
  }
29305
- async deleteBrowserProfile(orgId, profileId) {
29306
- await this.request("DELETE", ENDPOINTS.BROWSER_PROFILE(orgId, profileId));
28911
+ // ---- Event listeners ----
28912
+ on(event, handler) {
28913
+ let set = this.listeners.get(event);
28914
+ if (!set) {
28915
+ set = /* @__PURE__ */ new Set();
28916
+ this.listeners.set(event, set);
28917
+ }
28918
+ set.add(handler);
28919
+ return () => {
28920
+ set.delete(handler);
28921
+ };
29307
28922
  }
29308
- async openBrowserProfile(orgId, profileId, req = {}) {
29309
- return this.request("POST", ENDPOINTS.BROWSER_PROFILE_OPEN(orgId, profileId), req);
28923
+ off(event, handler) {
28924
+ this.listeners.get(event)?.delete(handler);
29310
28925
  }
29311
- async stopBrowserProfile(orgId, profileId) {
29312
- return this.request("POST", ENDPOINTS.BROWSER_PROFILE_STOP(orgId, profileId), {});
28926
+ onStateChange(handler) {
28927
+ this.stateListeners.add(handler);
28928
+ return () => {
28929
+ this.stateListeners.delete(handler);
28930
+ };
29313
28931
  }
29314
- async resetBrowserProfile(orgId, profileId) {
29315
- return this.request("POST", ENDPOINTS.BROWSER_PROFILE_RESET(orgId, profileId));
28932
+ // ---- Internal ----
28933
+ send(frame) {
28934
+ if (this.ws?.readyState === WebSocket.OPEN) {
28935
+ this.ws.send(JSON.stringify(frame));
28936
+ }
29316
28937
  }
29317
- async listBrowserProfileConsents(orgId, profileId) {
29318
- const resp = await this.request("GET", ENDPOINTS.BROWSER_PROFILE_CONSENTS(orgId, profileId));
29319
- return resp.data;
28938
+ handleFrame(frame) {
28939
+ this.lastReceivedAt = Date.now();
28940
+ this.clearProbe();
28941
+ if (frame.seq !== void 0) {
28942
+ this.lastSeq = frame.seq;
28943
+ }
28944
+ if (frame.type === WS_EVENTS.HELLO) {
28945
+ const interval = frame.data.heartbeat_interval;
28946
+ this.startHeartbeat(interval);
28947
+ }
28948
+ const handlers = this.listeners.get(frame.type);
28949
+ if (handlers) {
28950
+ for (const handler of handlers) {
28951
+ handler(frame.data, frame.seq);
28952
+ }
28953
+ }
29320
28954
  }
29321
- async grantBrowserProfileConsent(orgId, profileId, req) {
29322
- return this.request("POST", ENDPOINTS.BROWSER_PROFILE_CONSENTS(orgId, profileId), req);
28955
+ startHeartbeat(intervalSec) {
28956
+ this.stopHeartbeat();
28957
+ if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
28958
+ console.error("Invalid heartbeat interval from server:", intervalSec);
28959
+ return;
28960
+ }
28961
+ this.heartbeatIntervalMs = intervalSec * 1e3;
28962
+ this.heartbeatTimer = setInterval(() => {
28963
+ if (this.lastReceivedAt > 0 && Date.now() - this.lastReceivedAt > this.heartbeatIntervalMs * 1.5) {
28964
+ this.probeConnection();
28965
+ return;
28966
+ }
28967
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
28968
+ }, intervalSec * 1e3);
29323
28969
  }
29324
- async revokeBrowserProfileConsent(orgId, profileId, clipId) {
29325
- await this.request("DELETE", ENDPOINTS.BROWSER_PROFILE_CONSENT(orgId, profileId, clipId));
28970
+ stopHeartbeat() {
28971
+ if (this.heartbeatTimer) {
28972
+ clearInterval(this.heartbeatTimer);
28973
+ this.heartbeatTimer = null;
28974
+ }
29326
28975
  }
29327
- async listRegistryClips(q) {
29328
- const url = ENDPOINTS.CLIP_REGISTRY() + (q ? `?q=${encodeURIComponent(q)}` : "");
29329
- const resp = await this.request("GET", url);
29330
- return resp.data;
28976
+ scheduleReconnect() {
28977
+ this.setState("reconnecting");
28978
+ this.clearReconnect();
28979
+ const base = Math.min(this.options.reconnectInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
28980
+ const delay = base * (0.5 + Math.random() * 0.5);
28981
+ this.reconnectAttempts++;
28982
+ this.reconnectTimer = setTimeout(() => {
28983
+ this.connect();
28984
+ }, delay);
29331
28985
  }
29332
- // ---- Edge devices ----
29333
- async listEdgeDevices(orgId) {
29334
- return this.request("GET", ENDPOINTS.ORG_EDGE_DEVICES(orgId));
28986
+ clearReconnect() {
28987
+ if (this.reconnectTimer) {
28988
+ clearTimeout(this.reconnectTimer);
28989
+ this.reconnectTimer = null;
28990
+ }
29335
28991
  }
29336
- async getEdgeOnboarding(orgId) {
29337
- return this.request("GET", ENDPOINTS.ORG_EDGE_ONBOARDING(orgId));
28992
+ /** Force-close a dead/stale connection and trigger reconnect. */
28993
+ forceReconnect() {
28994
+ this.stopHeartbeat();
28995
+ this.clearReconnect();
28996
+ this.clearProbe();
28997
+ if (this.ws) {
28998
+ this.ws.onclose = null;
28999
+ this.ws.onopen = null;
29000
+ this.ws.onerror = null;
29001
+ this.ws.onmessage = null;
29002
+ try {
29003
+ this.ws.close();
29004
+ } catch {
29005
+ }
29006
+ this.ws = null;
29007
+ }
29008
+ if (this.options.reconnect && !this.intentionalClose) {
29009
+ this.scheduleReconnect();
29010
+ } else {
29011
+ this.setState("disconnected");
29012
+ }
29338
29013
  }
29339
- async listEdgeProfiles(orgId, edgeId) {
29340
- return this.request("GET", ENDPOINTS.ORG_EDGE_PROFILES(orgId, edgeId));
29014
+ // ---- Browser event listeners for proactive reconnection ----
29015
+ setupBrowserListeners() {
29016
+ if (this.browserListenersActive)
29017
+ return;
29018
+ this.browserListenersActive = true;
29019
+ if (typeof document !== "undefined") {
29020
+ document.addEventListener("visibilitychange", this.handleVisibilityChange);
29021
+ }
29022
+ if (typeof window !== "undefined") {
29023
+ window.addEventListener("online", this.handleOnline);
29024
+ }
29341
29025
  }
29342
- // ---- Clip connections ----
29343
- async listClipConnections(orgId, clipId) {
29344
- return this.request("GET", ENDPOINTS.CLIP_CONNECTIONS(orgId, clipId));
29026
+ teardownBrowserListeners() {
29027
+ if (!this.browserListenersActive)
29028
+ return;
29029
+ this.browserListenersActive = false;
29030
+ if (typeof document !== "undefined") {
29031
+ document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29032
+ }
29033
+ if (typeof window !== "undefined") {
29034
+ window.removeEventListener("online", this.handleOnline);
29035
+ }
29345
29036
  }
29346
- async createClipConnection(orgId, clipId, input) {
29347
- return this.request("POST", ENDPOINTS.CLIP_CONNECTIONS(orgId, clipId), input);
29037
+ /**
29038
+ * Send a ping and arm a short timeout. If no frame arrives within 5s the
29039
+ * connection is assumed dead and force-reconnected. Any received frame
29040
+ * (including the pong) cancels the timer via clearProbe() in handleFrame.
29041
+ */
29042
+ probeConnection() {
29043
+ if (this.probeTimer)
29044
+ return;
29045
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29046
+ this.probeTimer = setTimeout(() => {
29047
+ this.forceReconnect();
29048
+ }, 5e3);
29348
29049
  }
29349
- async deleteClipConnection(orgId, connId) {
29350
- return this.request("DELETE", ENDPOINTS.CLIP_CONNECTION(orgId, connId));
29050
+ clearProbe() {
29051
+ if (this.probeTimer) {
29052
+ clearTimeout(this.probeTimer);
29053
+ this.probeTimer = null;
29054
+ }
29351
29055
  }
29352
- };
29353
- function normalizeWikiChangeset(changeset) {
29354
- return {
29355
- ...changeset,
29356
- changed_paths: changeset.changed_paths ?? [],
29357
- file_changes: changeset.file_changes ?? []
29056
+ /** Tab returned to foreground — verify connection or accelerate reconnect. */
29057
+ handleVisibilityChange = () => {
29058
+ if (typeof document !== "undefined" && document.hidden)
29059
+ return;
29060
+ if (this._state === "connected") {
29061
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29062
+ this.forceReconnect();
29063
+ } else {
29064
+ this.probeConnection();
29065
+ }
29066
+ } else if (this._state === "reconnecting") {
29067
+ this.clearReconnect();
29068
+ this.reconnectAttempts = 0;
29069
+ this.connect();
29070
+ }
29358
29071
  };
29359
- }
29360
- var ApiError = class extends Error {
29361
- status;
29362
- code;
29363
- extras;
29364
- /** Attempted action (authorization denials) — e.g. "chat.add_member". */
29365
- action;
29366
- /** Target resource URI that was evaluated — e.g. "prll://cht_…". */
29367
- resourceUri;
29368
- /** Whether the action is approval-executable (PERMISSION_DENIED only). */
29369
- approvable;
29370
- constructor(status, message, code) {
29371
- super(message);
29372
- this.status = status;
29373
- this.code = code;
29374
- this.name = "ApiError";
29072
+ /** Network restored — accelerate reconnection. */
29073
+ handleOnline = () => {
29074
+ if (this.intentionalClose)
29075
+ return;
29076
+ if (this._state === "connected") {
29077
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29078
+ this.forceReconnect();
29079
+ } else {
29080
+ this.probeConnection();
29081
+ }
29082
+ } else if (this._state === "reconnecting") {
29083
+ this.clearReconnect();
29084
+ this.reconnectAttempts = 0;
29085
+ this.connect();
29086
+ }
29087
+ };
29088
+ setState(state) {
29089
+ this._state = state;
29090
+ for (const listener of this.stateListeners) {
29091
+ listener(state);
29092
+ }
29375
29093
  }
29376
29094
  };
29377
- function buildApiError(res, rawErrorBody) {
29378
- const errorBody = rawErrorBody !== null && typeof rawErrorBody === "object" ? rawErrorBody : {};
29379
- const errorObj = errorBody.error && typeof errorBody.error === "object" ? errorBody.error : void 0;
29380
- const errMsg = (typeof errorObj?.message === "string" ? errorObj.message : void 0) ?? (typeof errorBody.message === "string" ? errorBody.message : void 0) ?? (typeof errorBody.error === "string" ? errorBody.error : void 0);
29381
- const errCode = (typeof errorObj?.code === "string" ? errorObj.code : void 0) ?? (typeof errorBody.code === "string" ? errorBody.code : void 0);
29382
- const apiError = new ApiError(res.status, errMsg ?? res.statusText, errCode);
29383
- const anchors = errorObj ?? errorBody;
29384
- if (typeof anchors.action === "string")
29385
- apiError.action = anchors.action;
29386
- if (typeof anchors.resource_uri === "string")
29387
- apiError.resourceUri = anchors.resource_uri;
29388
- if (typeof anchors.approvable === "boolean")
29389
- apiError.approvable = anchors.approvable;
29390
- const structural = /* @__PURE__ */ new Set(["error", "code", "message", "status"]);
29391
- const extras = {};
29392
- for (const [k, v] of Object.entries(errorBody))
29393
- if (!structural.has(k))
29394
- extras[k] = v;
29395
- if (errorObj) {
29396
- for (const [k, v] of Object.entries(errorObj))
29397
- if (!structural.has(k))
29398
- extras[k] = v;
29399
- }
29400
- if (Object.keys(extras).length > 0)
29401
- apiError.extras = extras;
29402
- return apiError;
29403
- }
29404
29095
 
29405
- // ../sdk/dist/ws.js
29406
- function isRetryableNetworkError(err) {
29407
- return err instanceof Error && err.name === "ApiError" && "status" in err && err.status === 0;
29096
+ // ../agent-core/dist/lane-ledger.js
29097
+ var LedgerUnsupportedError = class extends Error {
29098
+ };
29099
+ function isStaleLane(err) {
29100
+ return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
29408
29101
  }
29409
- function isBrowserRuntime() {
29410
- return typeof window !== "undefined";
29102
+ function isEndpointMissing(err) {
29103
+ return err instanceof ApiError && err.status === 404 && !err.code;
29411
29104
  }
29412
- var ParallWs = class {
29413
- ws = null;
29414
- options;
29415
- listeners = /* @__PURE__ */ new Map();
29416
- stateListeners = /* @__PURE__ */ new Set();
29417
- heartbeatTimer = null;
29418
- reconnectTimer = null;
29419
- reconnectAttempts = 0;
29420
- lastSeq = 0;
29421
- _state = "disconnected";
29422
- intentionalClose = false;
29423
- lastReceivedAt = 0;
29424
- heartbeatIntervalMs = 0;
29425
- probeTimer = null;
29426
- browserListenersActive = false;
29427
- constructor(options) {
29428
- this.options = {
29429
- reconnect: true,
29430
- reconnectInterval: 1e3,
29431
- maxReconnectInterval: 3e4,
29432
- ...options
29433
- };
29434
- this.lastSeq = options.lastSeq ?? 0;
29105
+ var LaneLedger = class {
29106
+ opts;
29107
+ lanes = /* @__PURE__ */ new Map();
29108
+ constructor(opts) {
29109
+ this.opts = opts;
29435
29110
  }
29436
- get state() {
29437
- return this._state;
29111
+ get contextDir() {
29112
+ return this.opts.contextDir;
29113
+ }
29114
+ /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
29115
+ handles(event) {
29116
+ return event.type === "message" && event.targetId.startsWith("cht_");
29117
+ }
29118
+ laneKeyFor(event) {
29119
+ if (event.type !== "message" && event.dispatchEventId) {
29120
+ return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29121
+ }
29122
+ return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29123
+ }
29124
+ getForEvent(event) {
29125
+ return this.lanes.get(this.laneKeyFor(event));
29126
+ }
29127
+ laneContextPath(lane) {
29128
+ return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29129
+ }
29130
+ /**
29131
+ * Claim (or reuse) the lane for a group of same-lane message events and
29132
+ * fold every group member into it. Returns 'foreign' when a healthy
29133
+ * incumbent (another pod) holds the resource — the caller must not
29134
+ * dispatch; the events stay pending server-side and re-drive after the
29135
+ * incumbent completes.
29136
+ */
29137
+ async ensureLane(events) {
29138
+ const trigger = events[events.length - 1];
29139
+ const laneKey = this.laneKeyFor(trigger);
29140
+ let lane = this.lanes.get(laneKey);
29141
+ if (!lane) {
29142
+ const targetUri = `prll://${trigger.targetId}`;
29143
+ let res;
29144
+ try {
29145
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29146
+ target_uri: targetUri,
29147
+ thread_root_id: trigger.threadRootId,
29148
+ limit: 100
29149
+ });
29150
+ } catch (err) {
29151
+ if (isEndpointMissing(err))
29152
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29153
+ throw err;
29154
+ }
29155
+ if (!res.claimed || !res.lane) {
29156
+ this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
29157
+ return null;
29158
+ }
29159
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29160
+ lane = {
29161
+ laneKey,
29162
+ lane: res.lane,
29163
+ targetUri,
29164
+ threadRootId: trigger.threadRootId,
29165
+ folded: /* @__PURE__ */ new Map(),
29166
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29167
+ };
29168
+ for (const ev of res.events ?? []) {
29169
+ lane.folded.set(ev.source_id, ev.id);
29170
+ }
29171
+ this.lanes.set(laneKey, lane);
29172
+ }
29173
+ for (const ev of events) {
29174
+ if (lane.folded.has(ev.messageId))
29175
+ continue;
29176
+ try {
29177
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29178
+ lane: lane.lane,
29179
+ target_uri: lane.targetUri,
29180
+ thread_root_id: lane.threadRootId,
29181
+ ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
29182
+ });
29183
+ lane.folded.set(ev.messageId, res.dispatch_event_id);
29184
+ } catch (err) {
29185
+ if (isStaleLane(err)) {
29186
+ this.lanes.delete(laneKey);
29187
+ return null;
29188
+ }
29189
+ this.opts.log?.warn(`steer fold failed for ${ev.messageId} \u2014 failing closed, releasing lane: ${String(err)}`);
29190
+ await this.release(laneKey);
29191
+ return null;
29192
+ }
29193
+ }
29194
+ return lane;
29438
29195
  }
29439
- async connect() {
29440
- this.intentionalClose = false;
29441
- this.setupBrowserListeners();
29442
- this.setState("connecting");
29443
- let ticket;
29196
+ /**
29197
+ * Fold a live mid-turn message into its active lane BEFORE injecting it
29198
+ * into the running turn. Injection without a successful fold is forbidden —
29199
+ * an un-folded injected message would be re-driven after complete and the
29200
+ * model would handle it twice.
29201
+ */
29202
+ async steerLive(event) {
29203
+ const laneKey = this.laneKeyFor(event);
29204
+ const lane = this.lanes.get(laneKey);
29205
+ if (!lane)
29206
+ return false;
29207
+ if (lane.folded.has(event.messageId))
29208
+ return true;
29444
29209
  try {
29445
- ticket = await this.options.getTicket();
29210
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29211
+ lane: lane.lane,
29212
+ target_uri: lane.targetUri,
29213
+ thread_root_id: lane.threadRootId,
29214
+ ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
29215
+ });
29216
+ lane.folded.set(event.messageId, res.dispatch_event_id);
29217
+ return true;
29446
29218
  } catch (err) {
29447
- if (isBrowserRuntime() && isRetryableNetworkError(err)) {
29448
- console.warn("Failed to get WS ticket:", err);
29449
- } else {
29450
- console.error("Failed to get WS ticket:", err);
29451
- }
29452
- if (this.options.reconnect) {
29453
- this.scheduleReconnect();
29219
+ if (isStaleLane(err)) {
29220
+ this.lanes.delete(laneKey);
29454
29221
  } else {
29455
- this.setState("disconnected");
29222
+ this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
29456
29223
  }
29457
- return;
29224
+ return false;
29458
29225
  }
29459
- const wsUrl = ticket.ws_url || this.options.wsUrl;
29460
- if (!wsUrl) {
29461
- console.error("No WS URL available");
29462
- this.setState("disconnected");
29226
+ }
29227
+ /**
29228
+ * Complete the lane when no local work remains for it: the server sweeps
29229
+ * still-leased members as no_action, releases the occupancy row, and
29230
+ * re-drives any same-target pending work. A STALE_LANE answer means a
29231
+ * takeover already owns the resource — local state is dropped either way.
29232
+ */
29233
+ async completeIfIdle(laneKey, hasMoreLocal) {
29234
+ const lane = this.lanes.get(laneKey);
29235
+ if (!lane || hasMoreLocal)
29463
29236
  return;
29464
- }
29465
- const url = new URL(wsUrl);
29466
- url.searchParams.set("ticket", ticket.ticket);
29467
- if (this.lastSeq > 0) {
29468
- url.searchParams.set("last_seq", String(this.lastSeq));
29469
- }
29470
- this.ws = new WebSocket(url.toString());
29471
- const ws = this.ws;
29472
- const connectTimeout = setTimeout(() => {
29473
- if (this._state === "connected" || this.intentionalClose)
29474
- return;
29475
- ws.onclose = null;
29476
- ws.onopen = null;
29477
- ws.onerror = null;
29478
- try {
29479
- ws.close();
29480
- } catch {
29481
- }
29482
- if (ws !== this.ws)
29483
- return;
29484
- if (this.options.reconnect) {
29485
- this.scheduleReconnect();
29486
- } else {
29487
- this.setState("disconnected");
29488
- }
29489
- }, 15e3);
29490
- this.ws.onopen = () => {
29491
- clearTimeout(connectTimeout);
29492
- this.reconnectAttempts = 0;
29493
- this.lastReceivedAt = Date.now();
29494
- this.setState("connected");
29495
- };
29496
- this.ws.onmessage = (event) => {
29497
- try {
29498
- const frame = JSON.parse(event.data);
29499
- this.handleFrame(frame);
29500
- } catch {
29237
+ this.lanes.delete(laneKey);
29238
+ this.removeLaneContext(lane);
29239
+ try {
29240
+ const res = await this.opts.client.completeDispatch(this.opts.orgId, {
29241
+ lane: lane.lane,
29242
+ target_uri: lane.targetUri,
29243
+ thread_root_id: lane.threadRootId
29244
+ });
29245
+ if (res.swept_no_action > 0 || res.redriven) {
29246
+ this.opts.log?.info(`lane complete for ${lane.targetUri}: swept ${res.swept_no_action} no_action, redriven=${res.redriven}`);
29501
29247
  }
29502
- };
29503
- this.ws.onclose = () => {
29504
- clearTimeout(connectTimeout);
29505
- this.stopHeartbeat();
29506
- this.clearProbe();
29507
- if (this.intentionalClose) {
29508
- this.setState("disconnected");
29248
+ } catch (err) {
29249
+ if (isStaleLane(err)) {
29250
+ this.opts.log?.info(`lane complete skipped for ${lane.targetUri} \u2014 taken over`);
29509
29251
  return;
29510
29252
  }
29511
- if (this.options.reconnect) {
29512
- this.scheduleReconnect();
29513
- } else {
29514
- this.setState("disconnected");
29515
- }
29516
- };
29517
- this.ws.onerror = () => {
29518
- };
29519
- }
29520
- disconnect() {
29521
- this.intentionalClose = true;
29522
- this.stopHeartbeat();
29523
- this.clearReconnect();
29524
- this.clearProbe();
29525
- this.teardownBrowserListeners();
29526
- if (this.ws) {
29527
- this.ws.close();
29528
- this.ws = null;
29253
+ this.opts.log?.warn(`lane complete failed for ${lane.targetUri}: ${String(err)}`);
29529
29254
  }
29530
- this.setState("disconnected");
29531
- }
29532
- // ---- Client -> Server messages ----
29533
- /** Tell the server which chats the user is currently viewing (no auth implications). */
29534
- watch(chatIds) {
29535
- this.send({ type: WS_EVENTS.WATCH, data: { chat_ids: chatIds } });
29536
29255
  }
29537
- sendTyping(chatId, action, threadRootId) {
29538
- this.send({
29539
- type: WS_EVENTS.TYPING,
29540
- data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
29541
- });
29542
- }
29543
- /** Send an agent heartbeat with telemetry data. */
29544
- sendAgentHeartbeat(sessionId, telemetry) {
29545
- this.send({
29546
- type: WS_EVENTS.AGENT_HEARTBEAT,
29547
- data: { session_id: sessionId, telemetry }
29256
+ /**
29257
+ * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
29258
+ * so a chatty turn doesn't spam the server. Without this, a legitimately
29259
+ * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
29260
+ * write misfired with STALE_LANE — the design doc's "long turns renew via
29261
+ * step writes". Fire-and-forget: a failed renewal is surfaced by the next
29262
+ * write's incumbency check anyway.
29263
+ */
29264
+ maybeRenew(lane) {
29265
+ const now = Date.now();
29266
+ const ttl = lane.leaseTtlMs ?? 10 * 6e4;
29267
+ const until = lane.leaseUntilMs ?? now;
29268
+ if (until - now > ttl / 2)
29269
+ return;
29270
+ lane.leaseUntilMs = now + ttl;
29271
+ void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
29272
+ lane: lane.lane,
29273
+ target_uri: lane.targetUri,
29274
+ thread_root_id: lane.threadRootId
29275
+ }).then((res) => {
29276
+ const until2 = Date.parse(res?.lease_until ?? "");
29277
+ if (!Number.isNaN(until2))
29278
+ lane.leaseUntilMs = until2;
29279
+ }).catch((err) => {
29280
+ if (isStaleLane(err)) {
29281
+ this.lanes.delete(lane.laneKey);
29282
+ this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
29283
+ return;
29284
+ }
29285
+ this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
29548
29286
  });
29549
29287
  }
29550
- sendEvent(type, data) {
29551
- this.send({ type, data });
29552
- }
29553
- // ---- Event listeners ----
29554
- on(event, handler) {
29555
- let set = this.listeners.get(event);
29556
- if (!set) {
29557
- set = /* @__PURE__ */ new Set();
29558
- this.listeners.set(event, set);
29288
+ /**
29289
+ * Release a lane's unresolved members back to pending (dispatch error /
29290
+ * shutdown) so the next pod re-claims immediately instead of waiting out
29291
+ * the lease.
29292
+ */
29293
+ async release(laneKey) {
29294
+ const lane = this.lanes.get(laneKey);
29295
+ if (!lane)
29296
+ return;
29297
+ this.lanes.delete(laneKey);
29298
+ this.removeLaneContext(lane);
29299
+ try {
29300
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane);
29301
+ } catch (err) {
29302
+ this.opts.log?.warn(`lane release failed for ${lane.targetUri}: ${String(err)}`);
29559
29303
  }
29560
- set.add(handler);
29561
- return () => {
29562
- set.delete(handler);
29563
- };
29564
29304
  }
29565
- off(event, handler) {
29566
- this.listeners.get(event)?.delete(handler);
29305
+ async releaseAll() {
29306
+ const keys = [...this.lanes.keys()];
29307
+ for (const key of keys) {
29308
+ await this.release(key);
29309
+ }
29567
29310
  }
29568
- onStateChange(handler) {
29569
- this.stateListeners.add(handler);
29570
- return () => {
29571
- this.stateListeners.delete(handler);
29572
- };
29311
+ /** True when any lane is currently active (used by shutdown logging). */
29312
+ get activeCount() {
29313
+ return this.lanes.size;
29573
29314
  }
29574
- // ---- Internal ----
29575
- send(frame) {
29576
- if (this.ws?.readyState === WebSocket.OPEN) {
29577
- this.ws.send(JSON.stringify(frame));
29315
+ /**
29316
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
29317
+ * by WorkItem id or by source identity (the live task.assigned event has no
29318
+ * WorkItem id). Returns null when a healthy incumbent (another pod) holds
29319
+ * it or the WorkItem is already resolved — the caller must skip processing.
29320
+ */
29321
+ async claimTyped(ref) {
29322
+ let res;
29323
+ try {
29324
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29325
+ dispatch_event_id: ref.dispatchEventId,
29326
+ source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
29327
+ source_id: ref.dispatchEventId ? void 0 : ref.sourceId
29328
+ });
29329
+ } catch (err) {
29330
+ if (isEndpointMissing(err))
29331
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29332
+ throw err;
29578
29333
  }
29334
+ if (!res.claimed || !res.lane || !res.events?.length)
29335
+ return null;
29336
+ const workItem = res.events[0];
29337
+ const targetUri = `dsp:${workItem.id}`;
29338
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29339
+ const lane = {
29340
+ laneKey: laneKeyForTarget(targetUri),
29341
+ lane: res.lane,
29342
+ targetUri,
29343
+ folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
29344
+ typedDispatchEventId: workItem.id,
29345
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29346
+ };
29347
+ this.lanes.set(lane.laneKey, lane);
29348
+ return lane;
29579
29349
  }
29580
- handleFrame(frame) {
29581
- this.lastReceivedAt = Date.now();
29582
- this.clearProbe();
29583
- if (frame.seq !== void 0) {
29584
- this.lastSeq = frame.seq;
29585
- }
29586
- if (frame.type === WS_EVENTS.HELLO) {
29587
- const interval = frame.data.heartbeat_interval;
29588
- this.startHeartbeat(interval);
29589
- }
29590
- const handlers = this.listeners.get(frame.type);
29591
- if (handlers) {
29592
- for (const handler of handlers) {
29593
- handler(frame.data, frame.seq);
29350
+ /**
29351
+ * Remove the per-lane context file (and its CLI sidecar) when the lane
29352
+ * ends. A leftover file would make a later cross-context send to the same
29353
+ * target bind a dead lane token and misfire with STALE_LANE instead of
29354
+ * taking the plain non-ledger path.
29355
+ */
29356
+ removeLaneContext(lane) {
29357
+ const contextPath = this.laneContextPath(lane);
29358
+ for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
29359
+ try {
29360
+ fs.rmSync(p, { force: true });
29361
+ } catch {
29594
29362
  }
29595
29363
  }
29596
29364
  }
29597
- startHeartbeat(intervalSec) {
29598
- this.stopHeartbeat();
29599
- if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
29600
- console.error("Invalid heartbeat interval from server:", intervalSec);
29601
- return;
29365
+ };
29366
+
29367
+ // ../agent-core/dist/gateway-lane-flow.js
29368
+ async function dispatchLaneGroup(host, opts) {
29369
+ const ledger = host.laneLedger;
29370
+ const event = opts.events[opts.events.length - 1];
29371
+ let lane;
29372
+ try {
29373
+ lane = await ledger.ensureLane(opts.events);
29374
+ } catch (err) {
29375
+ if (!(err instanceof LedgerUnsupportedError))
29376
+ throw err;
29377
+ host.disableLedger("claim endpoint missing");
29378
+ await host.emitDispatchReceived(event);
29379
+ const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29380
+ if (!dispatched2)
29381
+ return "shutdown";
29382
+ for (const ev of opts.events) {
29383
+ host.opts.client.ackDispatch(host.opts.config.org_id, {
29384
+ source_type: ev.ackSourceType ?? "message",
29385
+ source_id: ev.ackSourceId ?? ev.messageId
29386
+ }).catch(() => {
29387
+ });
29602
29388
  }
29603
- this.heartbeatIntervalMs = intervalSec * 1e3;
29604
- this.heartbeatTimer = setInterval(() => {
29605
- if (this.lastReceivedAt > 0 && Date.now() - this.lastReceivedAt > this.heartbeatIntervalMs * 1.5) {
29606
- this.probeConnection();
29607
- return;
29608
- }
29609
- this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29610
- }, intervalSec * 1e3);
29389
+ return "dispatched";
29611
29390
  }
29612
- stopHeartbeat() {
29613
- if (this.heartbeatTimer) {
29614
- clearInterval(this.heartbeatTimer);
29615
- this.heartbeatTimer = null;
29391
+ if (!lane) {
29392
+ for (const ev of opts.events) {
29393
+ host.dispatchedMessages.delete(ev.messageId);
29616
29394
  }
29395
+ return "foreign";
29617
29396
  }
29618
- scheduleReconnect() {
29619
- this.setState("reconnecting");
29620
- this.clearReconnect();
29621
- const base = Math.min(this.options.reconnectInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
29622
- const delay = base * (0.5 + Math.random() * 0.5);
29623
- this.reconnectAttempts++;
29624
- this.reconnectTimer = setTimeout(() => {
29625
- this.connect();
29626
- }, delay);
29397
+ let dispatched = false;
29398
+ try {
29399
+ dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29400
+ } catch (err) {
29401
+ await ledger.release(lane.laneKey).catch(() => {
29402
+ });
29403
+ throw err;
29627
29404
  }
29628
- clearReconnect() {
29629
- if (this.reconnectTimer) {
29630
- clearTimeout(this.reconnectTimer);
29631
- this.reconnectTimer = null;
29632
- }
29405
+ if (!dispatched) {
29406
+ return "shutdown";
29633
29407
  }
29634
- /** Force-close a dead/stale connection and trigger reconnect. */
29635
- forceReconnect() {
29636
- this.stopHeartbeat();
29637
- this.clearReconnect();
29638
- this.clearProbe();
29639
- if (this.ws) {
29640
- this.ws.onclose = null;
29641
- this.ws.onopen = null;
29642
- this.ws.onerror = null;
29643
- this.ws.onmessage = null;
29644
- try {
29645
- this.ws.close();
29646
- } catch {
29647
- }
29648
- this.ws = null;
29649
- }
29650
- if (this.options.reconnect && !this.intentionalClose) {
29651
- this.scheduleReconnect();
29652
- } else {
29653
- this.setState("disconnected");
29408
+ const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
29409
+ await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
29410
+ return "dispatched";
29411
+ }
29412
+ var TYPED_BACKOFF_BASE_MS = 2e3;
29413
+ var TYPED_BACKOFF_CAP_MS = 5 * 6e4;
29414
+ var TYPED_BACKOFF_MAP_CAP = 512;
29415
+ async function consumeTypedDispatch(host, ref, run, ack) {
29416
+ const backoffKey = ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`;
29417
+ const armed = host.typedRedriveBackoff.get(backoffKey);
29418
+ if (armed) {
29419
+ const waitMs = armed.until - Date.now();
29420
+ if (waitMs > 0) {
29421
+ host.opts.log?.info(`typed dispatch ${backoffKey} backing off ${Math.ceil(waitMs / 1e3)}s after ${armed.failures} failed consume(s)`);
29422
+ await new Promise((resolve3) => {
29423
+ const timer = setTimeout(resolve3, waitMs);
29424
+ timer.unref?.();
29425
+ });
29654
29426
  }
29427
+ if (host.shuttingDown)
29428
+ return;
29655
29429
  }
29656
- // ---- Browser event listeners for proactive reconnection ----
29657
- setupBrowserListeners() {
29658
- if (this.browserListenersActive)
29430
+ const settleAck = (ackResult) => ackResult !== false;
29431
+ const settle = (acked2) => {
29432
+ if (acked2) {
29433
+ host.typedRedriveBackoff.delete(backoffKey);
29659
29434
  return;
29660
- this.browserListenersActive = true;
29661
- if (typeof document !== "undefined") {
29662
- document.addEventListener("visibilitychange", this.handleVisibilityChange);
29663
29435
  }
29664
- if (typeof window !== "undefined") {
29665
- window.addEventListener("online", this.handleOnline);
29436
+ const failures = (host.typedRedriveBackoff.get(backoffKey)?.failures ?? 0) + 1;
29437
+ const backoffMs = Math.min(TYPED_BACKOFF_CAP_MS, TYPED_BACKOFF_BASE_MS * 2 ** (failures - 1));
29438
+ if (host.typedRedriveBackoff.delete(backoffKey) === false && host.typedRedriveBackoff.size >= TYPED_BACKOFF_MAP_CAP) {
29439
+ const oldest = host.typedRedriveBackoff.keys().next().value;
29440
+ if (oldest !== void 0)
29441
+ host.typedRedriveBackoff.delete(oldest);
29442
+ }
29443
+ host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
29444
+ };
29445
+ const runLegacy = async () => {
29446
+ let acked2 = false;
29447
+ try {
29448
+ if (await run(ref.dispatchEventId)) {
29449
+ acked2 = settleAck(await ack(ref.dispatchEventId));
29450
+ }
29451
+ } finally {
29452
+ settle(acked2);
29666
29453
  }
29454
+ };
29455
+ if (!host.laneLedger || host.ledgerDisabled) {
29456
+ await runLegacy();
29457
+ return;
29667
29458
  }
29668
- teardownBrowserListeners() {
29669
- if (!this.browserListenersActive)
29459
+ let lane;
29460
+ try {
29461
+ lane = await host.laneLedger.claimTyped(ref);
29462
+ } catch (err) {
29463
+ if (err instanceof LedgerUnsupportedError) {
29464
+ host.disableLedger("claim endpoint missing");
29465
+ await runLegacy();
29670
29466
  return;
29671
- this.browserListenersActive = false;
29672
- if (typeof document !== "undefined") {
29673
- document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29674
- }
29675
- if (typeof window !== "undefined") {
29676
- window.removeEventListener("online", this.handleOnline);
29677
29467
  }
29468
+ throw err;
29678
29469
  }
29679
- /**
29680
- * Send a ping and arm a short timeout. If no frame arrives within 5s the
29681
- * connection is assumed dead and force-reconnected. Any received frame
29682
- * (including the pong) cancels the timer via clearProbe() in handleFrame.
29683
- */
29684
- probeConnection() {
29685
- if (this.probeTimer)
29686
- return;
29687
- this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29688
- this.probeTimer = setTimeout(() => {
29689
- this.forceReconnect();
29690
- }, 5e3);
29470
+ if (!lane) {
29471
+ host.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} not claimable (held elsewhere or already resolved) \u2014 skipping`);
29472
+ return;
29691
29473
  }
29692
- clearProbe() {
29693
- if (this.probeTimer) {
29694
- clearTimeout(this.probeTimer);
29695
- this.probeTimer = null;
29474
+ let acked = false;
29475
+ try {
29476
+ if (await run(lane.typedDispatchEventId)) {
29477
+ acked = settleAck(await ack(lane.typedDispatchEventId));
29696
29478
  }
29479
+ } finally {
29480
+ settle(acked);
29481
+ await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
29482
+ });
29697
29483
  }
29698
- /** Tab returned to foreground — verify connection or accelerate reconnect. */
29699
- handleVisibilityChange = () => {
29700
- if (typeof document !== "undefined" && document.hidden)
29701
- return;
29702
- if (this._state === "connected") {
29703
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29704
- this.forceReconnect();
29705
- } else {
29706
- this.probeConnection();
29707
- }
29708
- } else if (this._state === "reconnecting") {
29709
- this.clearReconnect();
29710
- this.reconnectAttempts = 0;
29711
- this.connect();
29712
- }
29484
+ }
29485
+ async function consumeMessageWorkItem(host, item) {
29486
+ if (host.shuttingDown)
29487
+ return;
29488
+ if (!host.tryClaimMessage(item.source_id))
29489
+ return;
29490
+ const ackItem = () => {
29491
+ host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
29492
+ });
29713
29493
  };
29714
- /** Network restored — accelerate reconnection. */
29715
- handleOnline = () => {
29716
- if (this.intentionalClose)
29494
+ let msg = null;
29495
+ try {
29496
+ msg = await host.opts.client.getMessage(item.source_id);
29497
+ } catch (err) {
29498
+ const status = err?.status;
29499
+ if (status !== 404) {
29500
+ host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
29501
+ host.dispatchedMessages.delete(item.source_id);
29717
29502
  return;
29718
- if (this._state === "connected") {
29719
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29720
- this.forceReconnect();
29721
- } else {
29722
- this.probeConnection();
29723
- }
29724
- } else if (this._state === "reconnecting") {
29725
- this.clearReconnect();
29726
- this.reconnectAttempts = 0;
29727
- this.connect();
29728
29503
  }
29729
- };
29730
- setState(state) {
29731
- this._state = state;
29732
- for (const listener of this.stateListeners) {
29733
- listener(state);
29504
+ }
29505
+ if (!msg || msg.sender_id === host.opts.agentUserId) {
29506
+ host.dispatchedMessages.delete(item.source_id);
29507
+ ackItem();
29508
+ return;
29509
+ }
29510
+ const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
29511
+ if (decision.action === "retry") {
29512
+ host.dispatchedMessages.delete(item.source_id);
29513
+ return;
29514
+ }
29515
+ if (decision.action === "skip") {
29516
+ host.dispatchedMessages.delete(item.source_id);
29517
+ ackItem();
29518
+ return;
29519
+ }
29520
+ decision.event.dispatchEventId = item.id;
29521
+ const laneResolved = host.usesLaneLedger(decision.event);
29522
+ try {
29523
+ const dispatched = await host.handleInboundEvent(decision.event);
29524
+ if (dispatched) {
29525
+ if (!laneResolved)
29526
+ ackItem();
29527
+ } else {
29528
+ host.dispatchedMessages.delete(item.source_id);
29734
29529
  }
29530
+ } catch (err) {
29531
+ host.dispatchedMessages.delete(item.source_id);
29532
+ throw err;
29735
29533
  }
29736
- };
29534
+ }
29737
29535
 
29738
- // ../agent-core/dist/lane-ledger.js
29739
- import * as fs from "node:fs";
29740
- var LedgerUnsupportedError = class extends Error {
29741
- };
29742
- function isStaleLane(err) {
29743
- return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
29536
+ // ../agent-core/dist/session-state.js
29537
+ function normalizeSessionKey(sessionKey) {
29538
+ return sessionKey.toLowerCase();
29744
29539
  }
29745
- function isEndpointMissing(err) {
29746
- return err instanceof ApiError && err.status === 404 && !err.code;
29540
+ var sessionChatIdMap = /* @__PURE__ */ new Map();
29541
+ var sessionMessageIdMap = /* @__PURE__ */ new Map();
29542
+ var dispatchMessageIdMap = /* @__PURE__ */ new Map();
29543
+ var dispatchGroupKeyMap = /* @__PURE__ */ new Map();
29544
+ var dispatchNoReplyMap = /* @__PURE__ */ new Map();
29545
+ function setSessionChatId(sessionKey, chatId) {
29546
+ sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
29747
29547
  }
29748
- var LaneLedger = class {
29749
- opts;
29750
- lanes = /* @__PURE__ */ new Map();
29751
- constructor(opts) {
29752
- this.opts = opts;
29753
- }
29754
- get contextDir() {
29755
- return this.opts.contextDir;
29548
+ function getSessionChatId(sessionKey) {
29549
+ return sessionChatIdMap.get(normalizeSessionKey(sessionKey));
29550
+ }
29551
+ function setSessionMessageId(sessionKey, messageId) {
29552
+ sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29553
+ }
29554
+ function clearSessionMessageId(sessionKey) {
29555
+ sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
29556
+ }
29557
+ function setDispatchMessageId(sessionKey, messageId) {
29558
+ dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29559
+ }
29560
+ function getDispatchMessageId(sessionKey) {
29561
+ return dispatchMessageIdMap.get(normalizeSessionKey(sessionKey));
29562
+ }
29563
+ function clearDispatchMessageId(sessionKey) {
29564
+ dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
29565
+ }
29566
+ function setDispatchGroupKey(sessionKey, groupKey) {
29567
+ dispatchGroupKeyMap.set(normalizeSessionKey(sessionKey), groupKey);
29568
+ }
29569
+ function getDispatchGroupKey(sessionKey) {
29570
+ return dispatchGroupKeyMap.get(normalizeSessionKey(sessionKey));
29571
+ }
29572
+ function clearDispatchGroupKey(sessionKey) {
29573
+ dispatchGroupKeyMap.delete(normalizeSessionKey(sessionKey));
29574
+ }
29575
+ function setDispatchNoReply(sessionKey, noReply) {
29576
+ dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
29577
+ }
29578
+ function clearDispatchNoReply(sessionKey) {
29579
+ dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
29580
+ }
29581
+ var dispatchMetricsMap = /* @__PURE__ */ new Map();
29582
+ function resetDispatchMetrics(sessionKey) {
29583
+ dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
29584
+ deliver_text_chunks: 0,
29585
+ deliver_text_chars: 0,
29586
+ message_send_attempts: 0,
29587
+ message_send_successes: 0,
29588
+ no_reply_called: false,
29589
+ tool_call_count: 0,
29590
+ started_at: Date.now()
29591
+ });
29592
+ }
29593
+ function getDispatchMetrics(sessionKey) {
29594
+ return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29595
+ }
29596
+ function clearDispatchMetrics(sessionKey) {
29597
+ dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
29598
+ }
29599
+ function recordDeliverText(sessionKey, charCount) {
29600
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29601
+ if (!m)
29602
+ return;
29603
+ m.deliver_text_chunks++;
29604
+ m.deliver_text_chars += charCount;
29605
+ }
29606
+ function recordMessageSend(sessionKey, success) {
29607
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29608
+ if (!m)
29609
+ return;
29610
+ m.message_send_attempts++;
29611
+ if (success)
29612
+ m.message_send_successes++;
29613
+ }
29614
+ function recordNoReply(sessionKey) {
29615
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29616
+ if (!m)
29617
+ return;
29618
+ m.no_reply_called = true;
29619
+ }
29620
+ function recordToolCall(sessionKey) {
29621
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29622
+ if (!m)
29623
+ return;
29624
+ m.tool_call_count++;
29625
+ }
29626
+
29627
+ // ../agent-core/dist/routing.js
29628
+ var MAX_CONCURRENT_FORKS = 20;
29629
+ var defaultRoutingStrategy = (event, state) => {
29630
+ if (state.mainCurrentTargetId === event.targetId) {
29631
+ return { action: "buffer-main" };
29756
29632
  }
29757
- /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
29758
- handles(event) {
29759
- return event.type === "message" && event.targetId.startsWith("cht_");
29633
+ const existingForkKey = state.activeForks.get(event.targetId);
29634
+ if (existingForkKey)
29635
+ return { action: "buffer-fork", forkKey: existingForkKey };
29636
+ if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
29637
+ return { action: "buffer-main" };
29760
29638
  }
29761
- laneKeyFor(event) {
29762
- if (event.type !== "message" && event.dispatchEventId) {
29763
- return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29639
+ return { action: "new-fork" };
29640
+ };
29641
+ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
29642
+ const existingForkKey = state.activeForks.get(event.targetId);
29643
+ if (existingForkKey)
29644
+ return { action: "buffer-fork", forkKey: existingForkKey };
29645
+ if (!state.mainDispatching)
29646
+ return { action: "main" };
29647
+ return strategy(event, state);
29648
+ }
29649
+
29650
+ // ../agent-core/dist/event-format.js
29651
+ function sanitizeMeta(value) {
29652
+ return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
29653
+ }
29654
+ function buildEventBody(event) {
29655
+ const lines = [];
29656
+ if (event.type === "message") {
29657
+ lines.push(`[Event: message.new]`);
29658
+ const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29659
+ lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
29660
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29661
+ lines.push(`[Message ID: prll://${event.messageId}]`);
29662
+ if (event.threadRootId) {
29663
+ const threadMeta = [
29664
+ `prll://${event.threadRootId}`,
29665
+ event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
29666
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
29667
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
29668
+ ].filter(Boolean).join(" | ");
29669
+ lines.push(`[Thread: ${threadMeta}]`);
29764
29670
  }
29765
- return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29766
- }
29767
- getForEvent(event) {
29768
- return this.lanes.get(this.laneKeyFor(event));
29769
- }
29770
- laneContextPath(lane) {
29771
- return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29772
- }
29773
- /**
29774
- * Claim (or reuse) the lane for a group of same-lane message events and
29775
- * fold every group member into it. Returns 'foreign' when a healthy
29776
- * incumbent (another pod) holds the resource — the caller must not
29777
- * dispatch; the events stay pending server-side and re-drive after the
29778
- * incumbent completes.
29779
- */
29780
- async ensureLane(events) {
29781
- const trigger = events[events.length - 1];
29782
- const laneKey = this.laneKeyFor(trigger);
29783
- let lane = this.lanes.get(laneKey);
29784
- if (!lane) {
29785
- const targetUri = `prll://${trigger.targetId}`;
29786
- let res;
29787
- try {
29788
- res = await this.opts.client.claimDispatch(this.opts.orgId, {
29789
- target_uri: targetUri,
29790
- thread_root_id: trigger.threadRootId,
29791
- limit: 100
29792
- });
29793
- } catch (err) {
29794
- if (isEndpointMissing(err))
29795
- throw new LedgerUnsupportedError("claim endpoint unavailable");
29796
- throw err;
29797
- }
29798
- if (!res.claimed || !res.lane) {
29799
- this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
29800
- return null;
29801
- }
29802
- const leaseUntilMs = Date.parse(res.lease_until ?? "");
29803
- lane = {
29804
- laneKey,
29805
- lane: res.lane,
29806
- targetUri,
29807
- threadRootId: trigger.threadRootId,
29808
- folded: /* @__PURE__ */ new Map(),
29809
- ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29810
- };
29811
- for (const ev of res.events ?? []) {
29812
- lane.folded.set(ev.source_id, ev.id);
29671
+ if (event.unreadCount != null && event.unreadCount > 1) {
29672
+ const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
29673
+ const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
29674
+ let line = `[Unread: ${countStr} messages${sinceStr}]`;
29675
+ if (event.unreadCount > 50)
29676
+ line += ` \u2014 fetch recent context with --limit, not all`;
29677
+ lines.push(line);
29678
+ }
29679
+ if (event.noReply)
29680
+ lines.push(`[Hint: no_reply]`);
29681
+ if (event.attachments?.length) {
29682
+ for (const att of event.attachments) {
29683
+ const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
29684
+ lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
29813
29685
  }
29814
- this.lanes.set(laneKey, lane);
29815
29686
  }
29816
- for (const ev of events) {
29817
- if (lane.folded.has(ev.messageId))
29818
- continue;
29819
- try {
29820
- const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29821
- lane: lane.lane,
29822
- target_uri: lane.targetUri,
29823
- thread_root_id: lane.threadRootId,
29824
- ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
29825
- });
29826
- lane.folded.set(ev.messageId, res.dispatch_event_id);
29827
- } catch (err) {
29828
- if (isStaleLane(err)) {
29829
- this.lanes.delete(laneKey);
29830
- return null;
29831
- }
29832
- this.opts.log?.warn(`steer fold failed for ${ev.messageId} \u2014 failing closed, releasing lane: ${String(err)}`);
29833
- await this.release(laneKey);
29834
- return null;
29835
- }
29687
+ lines.push("", event.body);
29688
+ } else if (event.type === "task_comment") {
29689
+ lines.push(`[Event: task.comment.created]`);
29690
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29691
+ lines.push(`[Task: ${taskLabel}]`);
29692
+ if (event.deliveryReason)
29693
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29694
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29695
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29696
+ lines.push("", event.body);
29697
+ } else if (event.type === "wiki_comment") {
29698
+ lines.push(`[Event: wiki.comment.created]`);
29699
+ const target = event.replyTargetUri ?? `prll://${event.targetId}`;
29700
+ if (event.targetType === "changeset") {
29701
+ lines.push(`[Wiki Changeset: ${target}]`);
29702
+ } else {
29703
+ lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
29704
+ }
29705
+ if (event.deliveryReason)
29706
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29707
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29708
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29709
+ lines.push("", event.body);
29710
+ } else if (event.type === "approval") {
29711
+ lines.push(`[Event: approval.decided]`);
29712
+ lines.push(`[Approval: prll://${event.messageId}]`);
29713
+ lines.push(`[Chat: prll://${event.targetId}]`);
29714
+ lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
29715
+ lines.push("", event.body);
29716
+ } else if (event.type === "schedule") {
29717
+ lines.push(`[Event: schedule.fired]`);
29718
+ lines.push(`[Schedule: prll://${event.targetId}]`);
29719
+ lines.push(`[Run: prll://${event.messageId}]`);
29720
+ if (event.scheduledFireAt)
29721
+ lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
29722
+ if (event.attachedUri)
29723
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29724
+ lines.push("", event.body);
29725
+ } else if (event.type === "channel_message") {
29726
+ lines.push(`[Event: channel.message]`);
29727
+ const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
29728
+ const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
29729
+ lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
29730
+ lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
29731
+ if (event.channelExternalMessageId) {
29732
+ lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
29733
+ }
29734
+ 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.]`);
29735
+ lines.push("", event.body);
29736
+ } else if (event.type === "external_trigger") {
29737
+ lines.push(`[Event: external.trigger]`);
29738
+ lines.push(`[Trigger: prll://${event.targetId}]`);
29739
+ lines.push(`[Run: prll://${event.messageId}]`);
29740
+ if (event.externalConnectionId) {
29741
+ const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
29742
+ lines.push(`[Connection: ${label}]`);
29836
29743
  }
29837
- return lane;
29838
- }
29839
- /**
29840
- * Fold a live mid-turn message into its active lane BEFORE injecting it
29841
- * into the running turn. Injection without a successful fold is forbidden —
29842
- * an un-folded injected message would be re-driven after complete and the
29843
- * model would handle it twice.
29844
- */
29845
- async steerLive(event) {
29846
- const laneKey = this.laneKeyFor(event);
29847
- const lane = this.lanes.get(laneKey);
29848
- if (!lane)
29849
- return false;
29850
- if (lane.folded.has(event.messageId))
29851
- return true;
29852
- try {
29853
- const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29854
- lane: lane.lane,
29855
- target_uri: lane.targetUri,
29856
- thread_root_id: lane.threadRootId,
29857
- ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
29858
- });
29859
- lane.folded.set(event.messageId, res.dispatch_event_id);
29860
- return true;
29861
- } catch (err) {
29862
- if (isStaleLane(err)) {
29863
- this.lanes.delete(laneKey);
29864
- } else {
29865
- this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
29866
- }
29867
- return false;
29744
+ if (event.externalIngressEventId)
29745
+ lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
29746
+ if (event.attachedUri)
29747
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29748
+ if (event.externalConnectionSourceType) {
29749
+ lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
29868
29750
  }
29869
- }
29870
- /**
29871
- * Complete the lane when no local work remains for it: the server sweeps
29872
- * still-leased members as no_action, releases the occupancy row, and
29873
- * re-drives any same-target pending work. A STALE_LANE answer means a
29874
- * takeover already owns the resource — local state is dropped either way.
29875
- */
29876
- async completeIfIdle(laneKey, hasMoreLocal) {
29877
- const lane = this.lanes.get(laneKey);
29878
- if (!lane || hasMoreLocal)
29879
- return;
29880
- this.lanes.delete(laneKey);
29881
- this.removeLaneContext(lane);
29882
- try {
29883
- const res = await this.opts.client.completeDispatch(this.opts.orgId, {
29884
- lane: lane.lane,
29885
- target_uri: lane.targetUri,
29886
- thread_root_id: lane.threadRootId
29887
- });
29888
- if (res.swept_no_action > 0 || res.redriven) {
29889
- this.opts.log?.info(`lane complete for ${lane.targetUri}: swept ${res.swept_no_action} no_action, redriven=${res.redriven}`);
29890
- }
29891
- } catch (err) {
29892
- if (isStaleLane(err)) {
29893
- this.opts.log?.info(`lane complete skipped for ${lane.targetUri} \u2014 taken over`);
29894
- return;
29895
- }
29896
- this.opts.log?.warn(`lane complete failed for ${lane.targetUri}: ${String(err)}`);
29751
+ if (event.externalIngressEventType) {
29752
+ lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
29897
29753
  }
29754
+ lines.push("", event.body);
29755
+ } else {
29756
+ lines.push(`[Event: task.assigned]`);
29757
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29758
+ lines.push(`[Task: ${taskLabel}]`);
29759
+ lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
29760
+ lines.push("", event.body);
29898
29761
  }
29899
- /**
29900
- * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
29901
- * so a chatty turn doesn't spam the server. Without this, a legitimately
29902
- * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
29903
- * write misfired with STALE_LANE — the design doc's "long turns renew via
29904
- * step writes". Fire-and-forget: a failed renewal is surfaced by the next
29905
- * write's incumbency check anyway.
29906
- */
29907
- maybeRenew(lane) {
29908
- const now = Date.now();
29909
- const ttl = lane.leaseTtlMs ?? 10 * 6e4;
29910
- const until = lane.leaseUntilMs ?? now;
29911
- if (until - now > ttl / 2)
29912
- return;
29913
- lane.leaseUntilMs = now + ttl;
29914
- void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
29915
- lane: lane.lane,
29916
- target_uri: lane.targetUri,
29917
- thread_root_id: lane.threadRootId
29918
- }).then((res) => {
29919
- const until2 = Date.parse(res?.lease_until ?? "");
29920
- if (!Number.isNaN(until2))
29921
- lane.leaseUntilMs = until2;
29922
- }).catch((err) => {
29923
- if (isStaleLane(err)) {
29924
- this.lanes.delete(lane.laneKey);
29925
- this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
29926
- return;
29927
- }
29928
- this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
29929
- });
29762
+ return lines.join("\n") + buildSendMessageHint(event);
29763
+ }
29764
+ function buildEventBodyForForkResult(event) {
29765
+ return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
29766
+ }
29767
+ function buildSendMessageHint(event) {
29768
+ if (event.noReply)
29769
+ return "";
29770
+ if (event.type === "wiki_comment" && event.replyTargetUri) {
29771
+ const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
29772
+ return `
29773
+ <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>`;
29930
29774
  }
29931
- /**
29932
- * Release a lane's unresolved members back to pending (dispatch error /
29933
- * shutdown) so the next pod re-claims immediately instead of waiting out
29934
- * the lease.
29935
- */
29936
- async release(laneKey) {
29937
- const lane = this.lanes.get(laneKey);
29938
- if (!lane)
29939
- return;
29940
- this.lanes.delete(laneKey);
29941
- this.removeLaneContext(lane);
29942
- try {
29943
- await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane);
29944
- } catch (err) {
29945
- this.opts.log?.warn(`lane release failed for ${lane.targetUri}: ${String(err)}`);
29775
+ if (event.targetId.startsWith("cht_")) {
29776
+ if (event.threadRootId) {
29777
+ return `
29778
+ <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>`;
29946
29779
  }
29780
+ return `
29781
+ <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>`;
29947
29782
  }
29948
- async releaseAll() {
29949
- const keys = [...this.lanes.keys()];
29950
- for (const key of keys) {
29951
- await this.release(key);
29952
- }
29783
+ if (event.targetId.startsWith("tsk_")) {
29784
+ return `
29785
+ <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>`;
29953
29786
  }
29954
- /** True when any lane is currently active (used by shutdown logging). */
29955
- get activeCount() {
29956
- return this.lanes.size;
29787
+ if (event.targetId.startsWith("sch_")) {
29788
+ return `
29789
+ <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
29957
29790
  }
29958
- /**
29959
- * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
29960
- * by WorkItem id or by source identity (the live task.assigned event has no
29961
- * WorkItem id). Returns null when a healthy incumbent (another pod) holds
29962
- * it or the WorkItem is already resolved — the caller must skip processing.
29963
- */
29964
- async claimTyped(ref) {
29965
- let res;
29966
- try {
29967
- res = await this.opts.client.claimDispatch(this.opts.orgId, {
29968
- dispatch_event_id: ref.dispatchEventId,
29969
- source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
29970
- source_id: ref.dispatchEventId ? void 0 : ref.sourceId
29971
- });
29972
- } catch (err) {
29973
- if (isEndpointMissing(err))
29974
- throw new LedgerUnsupportedError("claim endpoint unavailable");
29975
- throw err;
29791
+ if (event.type === "channel_message") {
29792
+ if (event.channelCliCapable) {
29793
+ const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
29794
+ const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
29795
+ return `
29796
+ <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>`;
29976
29797
  }
29977
- if (!res.claimed || !res.lane || !res.events?.length)
29978
- return null;
29979
- const workItem = res.events[0];
29980
- const targetUri = `dsp:${workItem.id}`;
29981
- const leaseUntilMs = Date.parse(res.lease_until ?? "");
29982
- const lane = {
29983
- laneKey: laneKeyForTarget(targetUri),
29984
- lane: res.lane,
29985
- targetUri,
29986
- folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
29987
- typedDispatchEventId: workItem.id,
29988
- ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29989
- };
29990
- this.lanes.set(lane.laneKey, lane);
29991
- return lane;
29798
+ const platform = event.channelProvider ?? "the external platform";
29799
+ return `
29800
+ <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>`;
29992
29801
  }
29993
- /**
29994
- * Remove the per-lane context file (and its CLI sidecar) when the lane
29995
- * ends. A leftover file would make a later cross-context send to the same
29996
- * target bind a dead lane token and misfire with STALE_LANE instead of
29997
- * taking the plain non-ledger path.
29998
- */
29999
- removeLaneContext(lane) {
30000
- const contextPath = this.laneContextPath(lane);
30001
- for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
30002
- try {
30003
- fs.rmSync(p, { force: true });
30004
- } catch {
30005
- }
29802
+ if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
29803
+ return `
29804
+ <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>`;
29805
+ }
29806
+ return "";
29807
+ }
29808
+ function buildForkScopePrefix(event) {
29809
+ const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29810
+ 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.
29811
+
29812
+ 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.
29813
+
29814
+ End with a brief "Fork summary" of actions taken and decisions made.]
29815
+
29816
+ `;
29817
+ }
29818
+ function buildForkResultPrefix(results) {
29819
+ if (!results.length)
29820
+ return "";
29821
+ const blocks = results.map((result) => {
29822
+ const lines = [];
29823
+ for (const body of result.eventBodies) {
29824
+ lines.push(body);
29825
+ }
29826
+ lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
29827
+ 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."}]`);
29828
+ if (result.actions.length)
29829
+ lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
29830
+ if (result.historyPath)
29831
+ lines.push(`[Fork history: ${result.historyPath}]`);
29832
+ return lines.join("\n");
29833
+ });
29834
+ return blocks.join("\n\n") + "\n\n---\n\n";
29835
+ }
29836
+
29837
+ // ../agent-core/dist/prompt-fragments.js
29838
+ var PRLL_IDENTITY_BASE = `## You on Parall
29839
+
29840
+ Parall is a shared workspace where humans and agents work side by side as equals.
29841
+ You are a participant here, not a service. You hold tasks, own decisions, and are
29842
+ accountable for the work you take on \u2014 the same way a human teammate is.
29843
+
29844
+ The people and agents around you are collaborators, not users to serve. Be honest,
29845
+ be direct, and care about the outcome of the work \u2014 not just the request in front
29846
+ of you.`;
29847
+ function sanitizeProfileField(value) {
29848
+ return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
29849
+ }
29850
+ function sanitizeProfileBlock(value) {
29851
+ return value.replace(/\r\n?/g, "\n").trim();
29852
+ }
29853
+ function buildIdentity(agent) {
29854
+ if (!agent)
29855
+ return PRLL_IDENTITY_BASE;
29856
+ const name = sanitizeProfileField(agent.displayName);
29857
+ const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
29858
+ lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
29859
+ if (agent.description) {
29860
+ const description = sanitizeProfileBlock(agent.description);
29861
+ if (description) {
29862
+ lines.push("", "### Your Agent Profile", "", description);
30006
29863
  }
30007
29864
  }
30008
- };
29865
+ lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
29866
+ return lines.join("\n");
29867
+ }
29868
+ var PRLL_BEHAVIOR = `## How to work here
29869
+
29870
+ ### Move work forward
29871
+ Don't wait for instructions. If you see the next step, take it. If something is
29872
+ ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
29873
+ \u2014 don't go silent. Initiative is expected.
29874
+
29875
+ Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
29876
+ requests, verifying something landed. When a thing needs future attention and
29877
+ nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
29878
+
29879
+ ### Work in the open
29880
+ Nothing you do exists until the system can see it. Your progress, decisions,
29881
+ blockers, and results need to live in tasks, comments, messages, or wiki pages
29882
+ \u2014 otherwise the organization is blind to your work, and so is the next agent
29883
+ who picks up where you left off. Leave traces as you go, not at the end.
29884
+
29885
+ For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
29886
+ when status materially changes, close it when done, and link the origin that
29887
+ triggered it. Decompose multi-step work into subtasks and keep their statuses
29888
+ current \u2014 progress should be auditable without watching the work happen.
29889
+ Details: load the \`parall-tasks\` skill.
29890
+
29891
+ ### Done means landed
29892
+ Producing output does not complete a task. Work counts as done only when it has
29893
+ cleared its remaining gates \u2014 review, merge, deployment, the requester's
29894
+ verification. Until then keep the status honest (\`in_progress\` or
29895
+ \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
29896
+ self-reminder if nothing else will prompt follow-up). Never mark done what a
29897
+ human still has to accept.
29898
+
29899
+ ### Sessions, forks, and what survives
29900
+ Sessions end and context compacts. Anything that must survive \u2014 decisions,
29901
+ progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
29902
+ read the workspace, not this conversation.
29903
+
29904
+ Some events are handled by parallel fork sessions \u2014 short-lived copies of the
29905
+ same agent identity with separate context. In a fork: leave a written trace of
29906
+ what was done or deliberately not done (other sessions cannot see fork
29907
+ context), and do not start long-running processes \u2014 they die with the fork.
29908
+ When an event is marked fork-handled: do not re-handle it; verify its outcome
29909
+ instead of assuming it.
29910
+
29911
+ ### Communicate like a teammate
29912
+ Match the conversation \u2014 concise in chat, thorough in docs, plain language over
29913
+ jargon. Say what matters; stop when you're done. Don't narrate every tool call
29914
+ or pad replies to seem thorough.
29915
+
29916
+ Match the language of the person you're replying to. If someone writes in
29917
+ Chinese, reply in Chinese. If in English, reply in English. Never force a
29918
+ language switch unless explicitly asked.
29919
+
29920
+ Do not promise delivery times ("in an hour", "by tonight") unless the work is
29921
+ driven by an explicit schedule. Scope visibly; report when actually done.
29922
+
29923
+ ### Keep topics in threads
29924
+ Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
29925
+ Present \u2192 that thread is the context; reply there, passing the same root as
29926
+ \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
29927
+ never treat it as continuing your most recent thread. The sender's newest
29928
+ message is the anchor \u2014 never route a reply back into an older thread just
29929
+ because the topic used to live there.
29930
+
29931
+ Reply where the event lives: a thread message gets a thread reply, a
29932
+ top-level message gets a top-level reply. But in group chats, your later
29933
+ follow-up on that topic \u2014 progress updates, analysis, links, verification you
29934
+ post afterwards \u2014 belongs in a thread rooted at the topic's message
29935
+ (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
29936
+ the main channel stays scannable. Post follow-up at top level only when
29937
+ starting a genuinely new topic, making a channel-wide announcement, or when
29938
+ explicitly asked. Never post the same update in both the thread and the main
29939
+ channel \u2014 thread replies surface in the thread panel; no need to duplicate
29940
+ for visibility.
29941
+
29942
+ In DMs, reply top-level by default; use a thread only to continue one that
29943
+ already exists.
29944
+
29945
+ ### Group chats: mentions and unaddressed work
29946
+ An @mention is a direct request \u2014 act on it. A group message delivered to you
29947
+ without an @mention means the chat's routing lets you see the conversation:
29948
+ decide whether a reply adds value; silence is the default.
29949
+
29950
+ A message without an @mention is not an open invitation. Judge from context
29951
+ who the work belongs to \u2014 the named domain, the topic's owner, whoever is
29952
+ already on it. If it belongs to someone else, leave it. If genuinely unclear,
29953
+ ask or claim in one line ("taking this unless someone else has it") before
29954
+ starting \u2014 asking first beats duplicated or misdirected work.
29955
+
29956
+ ### Verify before you act
29957
+ Events can be redelivered \u2014 before acting, check whether it was already
29958
+ handled (your own recent replies, task comments); if handled, do nothing.
29959
+ Sends can fail silently, and creates can error after succeeding server-side \u2014
29960
+ check the chat or entity before retrying. Never blind-retry a mutating call.
29961
+
29962
+ ### Gather the full picture first
29963
+ When a request is vague, an entity may already exist, or work may already be
29964
+ underway \u2014 gather context before acting: search (\`parall search "..."\`),
29965
+ check existing tasks/chats/wiki, read the surrounding conversation. Act on the
29966
+ full picture, not the fragment that arrived in the event.
29967
+
29968
+ ### Report only work that ran
29969
+ If a scheduled job, scan, or tool call did not actually run \u2014 restarted
29970
+ session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
29971
+ or approximate results of work that did not execute.
29972
+
29973
+ ### Respect what's shared
29974
+ You have broad latitude inside your own work. But actions that are visible to
29975
+ others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
29976
+ wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
29977
+ acting, unless you've been explicitly authorized.
29978
+
29979
+ ### Shared workspace
29980
+ Other agents share this workspace. Before starting work, check whether someone
29981
+ \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
29982
+
29983
+ ### Permissions and approvals
29984
+ You have real permissions based on your roles (chat member/admin, org member).
29985
+ If you lack permission for an action, the API returns PERMISSION_DENIED with the
29986
+ \`action\` and \`resource_uri\` that were denied. The server decides whether that
29987
+ action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
29988
+ fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
29989
+ it to ask someone with permission. If it is NOT approvable, the output says so;
29990
+ ask a human with permission instead of requesting approval. A
29991
+ \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
29992
+ (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
29993
+ \`dm\` for a user). Don't retry or work around a denial; only request approval
29994
+ after an actual denial, never preemptively.
29995
+
29996
+ ### When in doubt
29997
+ Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
29998
+ credibility is what you bring to the workspace \u2014 protect it.`;
29999
+ var PRLL_REFERENCE_GUIDE = `## Parall References
30000
+
30001
+ Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
30002
+ entities when you create or update tasks, comments, messages, and wiki files.
30003
+
30004
+ All three forms work \u2014 pick whichever fits:
30005
+
30006
+ prll://tsk_abc bare URI (auto-linked)
30007
+ [](prll://tsk_abc) empty context (renders resolved title)
30008
+ [relevant context](prll://tsk_abc) with author annotation
30009
+
30010
+ Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
30011
+ resolves and renders the entity title automatically.
30012
+
30013
+ ### URI format
30014
+
30015
+ \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
30016
+
30017
+ **Entities** \u2014 the entity ID is the authority:
30018
+
30019
+ prll://usr_xxx user prll://prj_xxx project
30020
+ prll://tsk_xxx task prll://wik_xxx wiki
30021
+ prll://msg_xxx message prll://cmt_xxx comment
30022
+ prll://cht_xxx chat prll://tcm_xxx task comment (legacy)
30023
+ prll://att_xxx attachment prll://ase_xxx agent session
30024
+ prll://sch_xxx schedule prll://srn_xxx schedule run
30025
+
30026
+ **Wiki** \u2014 path is file path, fragment is a typed anchor:
30027
+
30028
+ prll://wik_xxx/docs/guide.md file
30029
+ prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
30030
+ prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
30031
+
30032
+ Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
30033
+ Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
30034
+
30035
+ **Chat message range**:
30036
+
30037
+ prll://cht_xxx#range=msg_01HA,msg_01HZ
30038
+
30039
+ **Field access** \u2014 path selects a field (omit to reference the entity itself):
30040
+
30041
+ prll://tsk_xxx/description#Implementation heading within task description
30042
+
30043
+ ### Unread context
30044
+
30045
+ When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
30046
+ This shows messages since your last interaction \u2014 your read cursor advances after each
30047
+ dispatch, so context you skip now won't appear as unread next time. Use
30048
+ \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
30049
+ counts (50+), fetch only recent messages rather than everything.
30050
+
30051
+ Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
30052
+ Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
30053
+ catch up on the thread.
30054
+
30055
+ ### Reading context on demand
30056
+
30057
+ An event only carries the single triggering message. If you're mentioned in a
30058
+ group chat and lack context, pull what you need from the chat \u2014 don't guess:
30059
+
30060
+ parall messages list cht_xxx --limit 20 --before msg_xxx
30061
+ parall messages get msg_xxx
30062
+ parall chats get cht_xxx
30063
+
30064
+ Rule of thumb: in a group chat mention, the conversation that led up to you
30065
+ being called almost always matters \u2014 read it before replying. In a DM, your
30066
+ session already has continuity, so skip the fetch unless something is unclear.
30067
+
30068
+ Same pattern for any other entity referenced in the event: \`tasks get\`,
30069
+ \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
30070
+ When one entity isn't enough \u2014 you need what's *around* it \u2014 walk the
30071
+ reference graph instead of guessing (see "Walk the reference graph" below).
30072
+
30073
+ ### Find context with search first
30074
+
30075
+ Reach for unified semantic search before paging chat history:
30076
+
30077
+ parall search "pricing decision june" --limit 10
30078
+
30079
+ It spans messages, tasks, wiki, and comments. Page \`messages list\` only for the
30080
+ verbatim recent flow of one chat, not for discovery.
30081
+
30082
+ ### Walk the reference graph
30083
+
30084
+ References form a traversable graph, and you can query it \u2014 don't stop at
30085
+ fetching entities one by one:
30086
+
30087
+ # entity metadata (title, status, preview)
30088
+ parall refs resolve prll://tsk_xxx prll://wik_xxx
30089
+ # who references this entity
30090
+ parall refs backlinks prll://tsk_xxx
30091
+ # connected sub-graph around it
30092
+ parall refs graph prll://tsk_xxx --depth 2
30093
+
30094
+ Use \`refs backlinks\` when you need "where is this discussed / used"; use
30095
+ \`refs graph\` when you need the full picture around an entity (related tasks,
30096
+ docs, conversations \u2014 edges carry the author's annotation for why they linked).
30097
+ Then \`refs resolve\` the interesting node URIs in one batch to get titles and
30098
+ status. \`refs graph\` takes entity-level URIs only (\`prll://wik_xxx\`, not
30099
+ \`prll://wik_xxx/docs/a.md\`). All results are filtered to what you can see.
30100
+ Details: parall-platform skill.
30101
+
30102
+ ### File attachments
30103
+
30104
+ Messages may include attachments. They appear in events as:
30009
30105
 
30010
- // ../agent-core/dist/gateway-lane-flow.js
30011
- async function dispatchLaneGroup(host, opts) {
30012
- const ledger = host.laneLedger;
30013
- const event = opts.events[opts.events.length - 1];
30014
- let lane;
30015
- try {
30016
- lane = await ledger.ensureLane(opts.events);
30017
- } catch (err) {
30018
- if (!(err instanceof LedgerUnsupportedError))
30019
- throw err;
30020
- host.disableLedger("claim endpoint missing");
30021
- await host.emitDispatchReceived(event);
30022
- const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
30023
- if (!dispatched2)
30024
- return "shutdown";
30025
- for (const ev of opts.events) {
30026
- host.opts.client.ackDispatch(host.opts.config.org_id, {
30027
- source_type: ev.ackSourceType ?? "message",
30028
- source_id: ev.ackSourceId ?? ev.messageId
30029
- }).catch(() => {
30030
- });
30031
- }
30032
- return "dispatched";
30033
- }
30034
- if (!lane) {
30035
- for (const ev of opts.events) {
30036
- host.dispatchedMessages.delete(ev.messageId);
30037
- }
30038
- return "foreign";
30039
- }
30040
- let dispatched = false;
30041
- try {
30042
- dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
30043
- } catch (err) {
30044
- await ledger.release(lane.laneKey).catch(() => {
30045
- });
30046
- throw err;
30047
- }
30048
- if (!dispatched) {
30049
- return "shutdown";
30106
+ [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
30107
+
30108
+ To download an attachment, use the CLI:
30109
+
30110
+ parall files download att_xxx --output /tmp/screenshot.png
30111
+
30112
+ To send a file:
30113
+
30114
+ parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
30115
+
30116
+ Or upload first and reuse across chats:
30117
+
30118
+ parall files upload /tmp/report.pdf
30119
+ parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
30120
+ parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
30121
+
30122
+ 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 \`$(...)\`.
30123
+
30124
+ ### When to reference
30125
+
30126
+ - **Origin** \u2014 always link the message or task that triggered your work
30127
+ - **Design docs / wiki** \u2014 link specs and guides relevant to the work
30128
+ - **Related tasks** \u2014 link parent, sibling, or blocking tasks
30129
+ - **People** \u2014 link assignees or stakeholders when mentioning them
30130
+ - **Conversations** \u2014 link a chat or message range as context
30131
+
30132
+ ### Why this matters
30133
+
30134
+ Other agents and humans read your output. References build a navigable context graph \u2014
30135
+ in multi-agent workflows, your references are the map that the next agent follows.`;
30136
+ function renderLocalAttachmentSection(section) {
30137
+ if (section.images.length === 0 && section.notes.length === 0)
30138
+ return "";
30139
+ const lines = ["[Local attachment files]"];
30140
+ for (const image of section.images) {
30141
+ lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
30050
30142
  }
30051
- const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
30052
- await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
30053
- return "dispatched";
30143
+ lines.push(...section.notes);
30144
+ return lines.join("\n");
30054
30145
  }
30055
- async function consumeTypedDispatch(host, ref, run, ack) {
30056
- if (!host.laneLedger || host.ledgerDisabled) {
30057
- if (await run(ref.dispatchEventId))
30058
- await ack(ref.dispatchEventId);
30059
- return;
30060
- }
30061
- let lane;
30062
- try {
30063
- lane = await host.laneLedger.claimTyped(ref);
30064
- } catch (err) {
30065
- if (err instanceof LedgerUnsupportedError) {
30066
- host.disableLedger("claim endpoint missing");
30067
- if (await run(ref.dispatchEventId))
30068
- await ack(ref.dispatchEventId);
30069
- return;
30070
- }
30071
- throw err;
30072
- }
30073
- if (!lane) {
30074
- host.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} not claimable (held elsewhere or already resolved) \u2014 skipping`);
30075
- return;
30076
- }
30077
- try {
30078
- if (await run(lane.typedDispatchEventId))
30079
- await ack(lane.typedDispatchEventId);
30080
- } finally {
30081
- await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
30082
- });
30083
- }
30146
+ function sanitizePromptMeta(value) {
30147
+ return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
30084
30148
  }
30085
- async function consumeMessageWorkItem(host, item) {
30086
- if (host.shuttingDown)
30087
- return;
30088
- if (!host.tryClaimMessage(item.source_id))
30089
- return;
30090
- const ackItem = () => {
30091
- host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
30092
- });
30093
- };
30094
- let msg = null;
30095
- try {
30096
- msg = await host.opts.client.getMessage(item.source_id);
30097
- } catch (err) {
30098
- const status = err?.status;
30099
- if (status !== 404) {
30100
- host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
30101
- host.dispatchedMessages.delete(item.source_id);
30102
- return;
30103
- }
30104
- }
30105
- if (!msg || msg.sender_id === host.opts.agentUserId) {
30106
- host.dispatchedMessages.delete(item.source_id);
30107
- ackItem();
30108
- return;
30109
- }
30110
- const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
30111
- if (decision.action === "retry") {
30112
- host.dispatchedMessages.delete(item.source_id);
30113
- return;
30114
- }
30115
- if (decision.action === "skip") {
30116
- host.dispatchedMessages.delete(item.source_id);
30117
- ackItem();
30118
- return;
30119
- }
30120
- decision.event.dispatchEventId = item.id;
30121
- const laneResolved = host.usesLaneLedger(decision.event);
30122
- try {
30123
- const dispatched = await host.handleInboundEvent(decision.event);
30124
- if (dispatched) {
30125
- if (!laneResolved)
30126
- ackItem();
30127
- } else {
30128
- host.dispatchedMessages.delete(item.source_id);
30129
- }
30130
- } catch (err) {
30131
- host.dispatchedMessages.delete(item.source_id);
30132
- throw err;
30149
+ function formatBytes(bytes) {
30150
+ if (bytes >= 1048576)
30151
+ return `${(bytes / 1048576).toFixed(1)}MB`;
30152
+ if (bytes >= 1024)
30153
+ return `${Math.round(bytes / 1024)}KB`;
30154
+ return `${bytes}B`;
30155
+ }
30156
+
30157
+ // ../agent-core/dist/bridge-workspace.js
30158
+ function extractShellCommand(input) {
30159
+ if (!input || typeof input !== "object")
30160
+ return void 0;
30161
+ const command = input.command;
30162
+ return typeof command === "string" && command.trim() ? command.trim() : void 0;
30163
+ }
30164
+ function parseParallCliInvocation(command) {
30165
+ const tokens = command.replace(/\s+/g, " ").trim().split(" ");
30166
+ let i = 0;
30167
+ if (tokens[i] === "parall") {
30168
+ i++;
30169
+ } else if (tokens[i] === "npx") {
30170
+ i++;
30171
+ while (i < tokens.length && tokens[i].startsWith("-"))
30172
+ i++;
30173
+ if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
30174
+ return null;
30175
+ i++;
30176
+ } else if (tokens[i] === "pnpm") {
30177
+ i++;
30178
+ if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
30179
+ i++;
30180
+ if (i >= tokens.length || tokens[i] !== "parall")
30181
+ return null;
30182
+ i++;
30183
+ } else {
30184
+ return null;
30133
30185
  }
30186
+ return tokens.slice(i).filter((t) => !t.startsWith("-"));
30134
30187
  }
30188
+ function isParallSendCommand(command) {
30189
+ if (!command)
30190
+ return false;
30191
+ const sub = parseParallCliInvocation(command);
30192
+ if (!sub || sub.length === 0)
30193
+ return false;
30194
+ return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
30195
+ }
30196
+ function isParallNoReplyCommand(command) {
30197
+ if (!command)
30198
+ return false;
30199
+ const sub = parseParallCliInvocation(command);
30200
+ return sub?.[0] === "no-reply";
30201
+ }
30202
+
30203
+ // ../agent-core/dist/dispatch-adapter.js
30204
+ function buildErrorStepContent(message) {
30205
+ return { text: message, suppressed: false, status: "error" };
30206
+ }
30207
+
30208
+ // ../agent-core/dist/gateway-base.js
30209
+ import * as os from "node:os";
30210
+ import * as fs2 from "node:fs";
30211
+ import * as path2 from "node:path";
30135
30212
 
30136
30213
  // ../agent-core/dist/telemetry.js
30137
30214
  init_esm();
@@ -30413,6 +30490,9 @@ var ParallAgentGateway = class {
30413
30490
  // (stable mapping; avoids one connection fetch per inbound message).
30414
30491
  channelConnectionProviders = /* @__PURE__ */ new Map();
30415
30492
  dispatchedMessages = /* @__PURE__ */ new Set();
30493
+ // Per-WorkItem failure backoff for typed dispatch consumption — see
30494
+ // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
30495
+ typedRedriveBackoff = /* @__PURE__ */ new Map();
30416
30496
  forkStates = /* @__PURE__ */ new Map();
30417
30497
  dispatchState = {
30418
30498
  mainDispatching: false,
@@ -30537,7 +30617,11 @@ var ParallAgentGateway = class {
30537
30617
  return this.opts.client.ackDispatch(this.opts.config.org_id, {
30538
30618
  source_type: "task_activity",
30539
30619
  source_id: data.id
30540
- }).then(() => void 0, () => void 0);
30620
+ }).then(() => true, (err) => {
30621
+ this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
30622
+ this.opts.log?.warn(`dispatch ack failed for task ${data.id}, releasing for re-drive: ${String(err)}`);
30623
+ return false;
30624
+ });
30541
30625
  });
30542
30626
  } catch (err) {
30543
30627
  this.opts.log?.error(`task dispatch failed for ${data.id}: ${String(err)}`);
@@ -30687,11 +30771,15 @@ var ParallAgentGateway = class {
30687
30771
  }
30688
30772
  // Typed completion must wait until the administrative ack has either
30689
30773
  // committed or failed. Errors stay best-effort: a failed ack leaves the row
30690
- // received, so Complete releases and re-drives it safely.
30774
+ // received, so Complete releases and re-drives it safely. The boolean
30775
+ // outcome feeds the typed-consume backoff — an ack that failed must count
30776
+ // as a failed consume, or an ack outage would clear the backoff entry and
30777
+ // let the release re-drive spin at wire speed.
30691
30778
  ackDispatchEvent(dispatchEventId, onFailure) {
30692
- return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => void 0, (err) => {
30779
+ return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => true, (err) => {
30693
30780
  onFailure?.();
30694
30781
  this.opts.log?.warn(`dispatch ack failed for ${dispatchEventId}, releasing for re-drive: ${String(err)}`);
30782
+ return false;
30695
30783
  });
30696
30784
  }
30697
30785
  clearTypedDispatchDedupe(item) {
@@ -32014,6 +32102,8 @@ var ParallAgentGateway = class {
32014
32102
  provider = void 0;
32015
32103
  }
32016
32104
  }
32105
+ const keys = this.opts.getCapabilityKeys?.() ?? [];
32106
+ const cliCapable = provider ? keys.includes(`${provider}-cli`) : keys.some((k) => k.endsWith("-cli"));
32017
32107
  const event = {
32018
32108
  type: "channel_message",
32019
32109
  targetId: conv.id,
@@ -32028,6 +32118,7 @@ var ParallAgentGateway = class {
32028
32118
  channelConversationType: conv.conversation_type || void 0,
32029
32119
  channelExternalConversationId: conv.external_conversation_id,
32030
32120
  channelExternalMessageId: msg.external_message_id,
32121
+ channelCliCapable: cliCapable,
32031
32122
  ackSourceType: "channel_message",
32032
32123
  ackSourceId: msg.id
32033
32124
  };
@@ -32361,12 +32452,116 @@ ${fullSummary}` : fullSummary;
32361
32452
  }
32362
32453
  };
32363
32454
 
32455
+ // ../agent-core/dist/platform-config.js
32456
+ function extractCapabilities(config) {
32457
+ const agents = config.agents ?? {};
32458
+ const raw = agents.capabilities;
32459
+ if (!Array.isArray(raw))
32460
+ return [];
32461
+ const out = [];
32462
+ for (const entry of raw) {
32463
+ if (typeof entry !== "object" || entry === null)
32464
+ continue;
32465
+ const e = entry;
32466
+ if (typeof e.key !== "string" || !e.key)
32467
+ continue;
32468
+ if (typeof e.fragment !== "string" || !e.fragment)
32469
+ continue;
32470
+ out.push({
32471
+ key: e.key,
32472
+ source: typeof e.source === "string" ? e.source : "",
32473
+ fragment: e.fragment
32474
+ });
32475
+ }
32476
+ return out;
32477
+ }
32478
+
32479
+ // ../agent-core/dist/channel-capability.js
32480
+ import * as fs3 from "node:fs";
32481
+ import * as path3 from "node:path";
32482
+ import { fileURLToPath } from "node:url";
32483
+ var CAPABILITY_FEISHU_CLI = "feishu-cli";
32484
+ var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
32485
+ function capabilityBinDir(stateDir) {
32486
+ return path3.join(stateDir, "bin");
32487
+ }
32488
+ function channelExecEntryPath() {
32489
+ const selfDir = path3.dirname(fileURLToPath(import.meta.url));
32490
+ const sibling = path3.join(selfDir, "parall-channel-exec.js");
32491
+ if (fs3.existsSync(sibling))
32492
+ return sibling;
32493
+ return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
32494
+ }
32495
+ function materializeChannelCapabilities(stateDir, capabilities, log) {
32496
+ try {
32497
+ reconcileFeishuCli(stateDir, capabilities, log);
32498
+ } catch (err) {
32499
+ log?.warn(`channel capability materialization failed: ${String(err)}`);
32500
+ }
32501
+ }
32502
+ function reconcileFeishuCli(stateDir, capabilities, log) {
32503
+ const binDir = capabilityBinDir(stateDir);
32504
+ const posixPath = path3.join(binDir, "lark-cli");
32505
+ const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
32506
+ const hadPointer = fs3.existsSync(posixPath);
32507
+ if (!granted && !hadPointer)
32508
+ return;
32509
+ fs3.mkdirSync(binDir, { recursive: true });
32510
+ const entry = channelExecEntryPath();
32511
+ const nodeExec = process.execPath;
32512
+ writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log);
32513
+ writePointerIfChanged(path3.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log);
32514
+ }
32515
+ function writePointerIfChanged(filePath, content, log) {
32516
+ let existing = null;
32517
+ try {
32518
+ existing = fs3.readFileSync(filePath, "utf8");
32519
+ } catch {
32520
+ existing = null;
32521
+ }
32522
+ if (existing !== content) {
32523
+ fs3.writeFileSync(filePath, content, { mode: 493 });
32524
+ log?.info(`channel capability: pointer materialized (${path3.basename(filePath)})`);
32525
+ }
32526
+ fs3.chmodSync(filePath, 493);
32527
+ }
32528
+ function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
32529
+ return [
32530
+ "#!/bin/sh",
32531
+ `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32532
+ "# Credential + exec logic lives in the agent-core package; revocation is",
32533
+ "# enforced by the platform mint endpoint, so this pointer stays constant.",
32534
+ // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
32535
+ // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
32536
+ // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
32537
+ // the mint. The pointer is a platform-authored trust-boundary artifact whose
32538
+ // whole job is a CONTROLLED launch of the broker (absolute node, magic
32539
+ // guard, skip-dir); this closes the same env-hijack class for node startup
32540
+ // that the absolute node path closes for PATH, keeping the launch deterministic.
32541
+ "unset NODE_OPTIONS NODE_PATH",
32542
+ // "$@" preserves argv exactly (this is the agent's main path via git-bash).
32543
+ `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
32544
+ ""
32545
+ ].join("\n");
32546
+ }
32547
+ function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
32548
+ return [
32549
+ "@echo off",
32550
+ `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32551
+ // Clear Node preload-hijack vars before launching node (see the sh pointer).
32552
+ 'set "NODE_OPTIONS="',
32553
+ 'set "NODE_PATH="',
32554
+ `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
32555
+ ""
32556
+ ].join("\r\n");
32557
+ }
32558
+
32364
32559
  // ../agent-core/dist/internal/attachment-input.js
32365
32560
  import { execSync } from "node:child_process";
32366
32561
  import { constants } from "node:fs";
32367
32562
  import * as fsSync from "node:fs";
32368
- import * as fs3 from "node:fs/promises";
32369
- import * as path3 from "node:path";
32563
+ import * as fs4 from "node:fs/promises";
32564
+ import * as path4 from "node:path";
32370
32565
  var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
32371
32566
  var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
32372
32567
  var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
@@ -32396,11 +32591,11 @@ async function prepareLocalImageAttachments(event, context2, opts) {
32396
32591
  };
32397
32592
  }
32398
32593
  const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
32399
- const messageDir = path3.join(rootDir, sanitizePathSegment(event.messageId));
32594
+ const messageDir = path4.join(rootDir, sanitizePathSegment(event.messageId));
32400
32595
  await ensurePathIsNotSymlink(messageDir);
32401
- await fs3.mkdir(messageDir, { recursive: true });
32596
+ await fs4.mkdir(messageDir, { recursive: true });
32402
32597
  await ensurePathIsNotSymlink(messageDir);
32403
- const activeMessageDir = path3.resolve(messageDir);
32598
+ const activeMessageDir = path4.resolve(messageDir);
32404
32599
  activeAttachmentDirs.add(activeMessageDir);
32405
32600
  const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
32406
32601
  const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
@@ -32417,7 +32612,7 @@ async function prepareLocalImageAttachments(event, context2, opts) {
32417
32612
  const notes = [];
32418
32613
  let downloadedBytes = 0;
32419
32614
  for (const att of imageAttachments) {
32420
- const localPath = path3.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
32615
+ const localPath = path4.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
32421
32616
  const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
32422
32617
  const fetchFresh = async () => {
32423
32618
  const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
@@ -32474,7 +32669,7 @@ async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
32474
32669
  return { body: appendLocalAttachmentRefs(body, attachments), attachments };
32475
32670
  }
32476
32671
  function pinLocalAttachmentPaths(images) {
32477
- const dirs = new Set(images.map((image) => path3.resolve(path3.dirname(image.localPath))));
32672
+ const dirs = new Set(images.map((image) => path4.resolve(path4.dirname(image.localPath))));
32478
32673
  for (const dir of dirs) {
32479
32674
  activeAttachmentDirs.add(dir);
32480
32675
  }
@@ -32489,7 +32684,7 @@ function pinLocalAttachmentPaths(images) {
32489
32684
  };
32490
32685
  }
32491
32686
  function attachmentRootDir(workspaceDir) {
32492
- return path3.join(path3.resolve(workspaceDir), ".parall", "attachments");
32687
+ return path4.join(path4.resolve(workspaceDir), ".parall", "attachments");
32493
32688
  }
32494
32689
  function ensureLocalAttachmentGitExclude(workingDirectory) {
32495
32690
  try {
@@ -32498,8 +32693,8 @@ function ensureLocalAttachmentGitExclude(workingDirectory) {
32498
32693
  encoding: "utf8",
32499
32694
  stdio: ["ignore", "pipe", "ignore"]
32500
32695
  }).trim();
32501
- const excludePath = path3.isAbsolute(rel) ? rel : path3.join(workingDirectory, rel);
32502
- fsSync.mkdirSync(path3.dirname(excludePath), { recursive: true });
32696
+ const excludePath = path4.isAbsolute(rel) ? rel : path4.join(workingDirectory, rel);
32697
+ fsSync.mkdirSync(path4.dirname(excludePath), { recursive: true });
32503
32698
  const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
32504
32699
  if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
32505
32700
  return;
@@ -32535,18 +32730,18 @@ function scheduleAttachmentMaintenance(rootDir, opts) {
32535
32730
  return run;
32536
32731
  }
32537
32732
  async function ensureAttachmentRootDir(workspaceDir) {
32538
- const workspaceRoot = path3.resolve(workspaceDir);
32539
- const parallDir = path3.join(workspaceRoot, ".parall");
32733
+ const workspaceRoot = path4.resolve(workspaceDir);
32734
+ const parallDir = path4.join(workspaceRoot, ".parall");
32540
32735
  const rootDir = attachmentRootDir(workspaceRoot);
32541
- await fs3.mkdir(workspaceRoot, { recursive: true });
32736
+ await fs4.mkdir(workspaceRoot, { recursive: true });
32542
32737
  await ensurePathIsNotSymlink(parallDir);
32543
- await fs3.mkdir(parallDir, { recursive: true, mode: 448 });
32738
+ await fs4.mkdir(parallDir, { recursive: true, mode: 448 });
32544
32739
  await ensurePathIsNotSymlink(parallDir);
32545
32740
  await ensurePathIsNotSymlink(rootDir);
32546
- await fs3.mkdir(rootDir, { recursive: true, mode: 448 });
32741
+ await fs4.mkdir(rootDir, { recursive: true, mode: 448 });
32547
32742
  await ensurePathIsNotSymlink(rootDir);
32548
- const realWorkspace = await fs3.realpath(workspaceRoot);
32549
- const realRoot = await fs3.realpath(rootDir);
32743
+ const realWorkspace = await fs4.realpath(workspaceRoot);
32744
+ const realRoot = await fs4.realpath(rootDir);
32550
32745
  if (!isPathInside(realRoot, realWorkspace)) {
32551
32746
  throw new Error(`attachment root escapes workspace: ${rootDir}`);
32552
32747
  }
@@ -32554,7 +32749,7 @@ async function ensureAttachmentRootDir(workspaceDir) {
32554
32749
  }
32555
32750
  async function ensurePathIsNotSymlink(filePath) {
32556
32751
  try {
32557
- const stat = await fs3.lstat(filePath);
32752
+ const stat = await fs4.lstat(filePath);
32558
32753
  if (stat.isSymbolicLink()) {
32559
32754
  throw new Error(`refusing to use symlinked attachment path ${filePath}`);
32560
32755
  }
@@ -32565,8 +32760,8 @@ async function ensurePathIsNotSymlink(filePath) {
32565
32760
  }
32566
32761
  }
32567
32762
  function isPathInside(childPath, parentPath) {
32568
- const rel = path3.relative(parentPath, childPath);
32569
- return rel === "" || !!rel && !rel.startsWith("..") && !path3.isAbsolute(rel);
32763
+ const rel = path4.relative(parentPath, childPath);
32764
+ return rel === "" || !!rel && !rel.startsWith("..") && !path4.isAbsolute(rel);
32570
32765
  }
32571
32766
  async function existingUsableFile(filePath, expectedSize, rootDir) {
32572
32767
  try {
@@ -32577,30 +32772,30 @@ async function existingUsableFile(filePath, expectedSize, rootDir) {
32577
32772
  }
32578
32773
  }
32579
32774
  async function localFileStatInsideRoot(filePath, rootDir) {
32580
- const stat = await fs3.lstat(filePath);
32775
+ const stat = await fs4.lstat(filePath);
32581
32776
  if (stat.isSymbolicLink()) {
32582
32777
  throw new Error(`refusing to use symlinked attachment file ${filePath}`);
32583
32778
  }
32584
32779
  if (!stat.isFile()) {
32585
32780
  throw new Error(`attachment path is not a file ${filePath}`);
32586
32781
  }
32587
- const realRoot = await fs3.realpath(rootDir);
32588
- const realFile = await fs3.realpath(filePath);
32782
+ const realRoot = await fs4.realpath(rootDir);
32783
+ const realFile = await fs4.realpath(filePath);
32589
32784
  if (!isPathInside(realFile, realRoot)) {
32590
32785
  throw new Error(`attachment file escapes workspace: ${filePath}`);
32591
32786
  }
32592
32787
  return stat;
32593
32788
  }
32594
32789
  async function localDirectoryStatInsideRoot(dirPath, rootDir) {
32595
- const stat = await fs3.lstat(dirPath);
32790
+ const stat = await fs4.lstat(dirPath);
32596
32791
  if (stat.isSymbolicLink()) {
32597
32792
  throw new Error(`refusing to use symlinked attachment directory ${dirPath}`);
32598
32793
  }
32599
32794
  if (!stat.isDirectory()) {
32600
32795
  throw new Error(`attachment path is not a directory ${dirPath}`);
32601
32796
  }
32602
- const realRoot = await fs3.realpath(rootDir);
32603
- const realDir = await fs3.realpath(dirPath);
32797
+ const realRoot = await fs4.realpath(rootDir);
32798
+ const realDir = await fs4.realpath(dirPath);
32604
32799
  if (!isPathInside(realDir, realRoot)) {
32605
32800
  throw new Error(`attachment directory escapes workspace: ${dirPath}`);
32606
32801
  }
@@ -32608,7 +32803,7 @@ async function localDirectoryStatInsideRoot(dirPath, rootDir) {
32608
32803
  }
32609
32804
  async function openLocalFileInsideRoot(filePath, rootDir) {
32610
32805
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
32611
- const file = await fs3.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
32806
+ const file = await fs4.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
32612
32807
  let keepOpen = false;
32613
32808
  try {
32614
32809
  const openedStat = await file.stat();
@@ -32624,8 +32819,8 @@ async function openLocalFileInsideRoot(filePath, rootDir) {
32624
32819
  }
32625
32820
  }
32626
32821
  async function openLocalTempFileInsideRoot(filePath, rootDir) {
32627
- await localDirectoryStatInsideRoot(path3.dirname(filePath), rootDir);
32628
- const file = await fs3.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
32822
+ await localDirectoryStatInsideRoot(path4.dirname(filePath), rootDir);
32823
+ const file = await fs4.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
32629
32824
  let keepOpen = false;
32630
32825
  try {
32631
32826
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
@@ -32650,7 +32845,7 @@ async function assertLocalFileIdentity(filePath, rootDir, expected) {
32650
32845
  async function removeLocalFileIfInside(filePath, rootDir) {
32651
32846
  try {
32652
32847
  await localFileStatInsideRoot(filePath, rootDir);
32653
- await fs3.rm(filePath, { force: true });
32848
+ await fs4.rm(filePath, { force: true });
32654
32849
  } catch {
32655
32850
  }
32656
32851
  }
@@ -32663,7 +32858,7 @@ function sameFile(a, b) {
32663
32858
  async function cleanupOldAttachmentFiles(rootDir, ttlMs, log, preserveDirs) {
32664
32859
  let entries;
32665
32860
  try {
32666
- entries = await fs3.readdir(rootDir, { withFileTypes: true });
32861
+ entries = await fs4.readdir(rootDir, { withFileTypes: true });
32667
32862
  } catch {
32668
32863
  return;
32669
32864
  }
@@ -32671,15 +32866,15 @@ async function cleanupOldAttachmentFiles(rootDir, ttlMs, log, preserveDirs) {
32671
32866
  await Promise.all(entries.map(async (entry) => {
32672
32867
  if (!entry.isDirectory())
32673
32868
  return;
32674
- const fullPath = path3.join(rootDir, entry.name);
32869
+ const fullPath = path4.join(rootDir, entry.name);
32675
32870
  try {
32676
- if (preserveDirs?.has(path3.resolve(fullPath)))
32871
+ if (preserveDirs?.has(path4.resolve(fullPath)))
32677
32872
  return;
32678
- const stat = await fs3.lstat(fullPath);
32873
+ const stat = await fs4.lstat(fullPath);
32679
32874
  if (!stat.isDirectory())
32680
32875
  return;
32681
32876
  if (stat.mtimeMs < cutoff) {
32682
- await fs3.rm(fullPath, { recursive: true, force: true });
32877
+ await fs4.rm(fullPath, { recursive: true, force: true });
32683
32878
  }
32684
32879
  } catch (err) {
32685
32880
  log?.warn?.(`agent-core: failed to clean attachment temp dir ${fullPath}: ${String(err)}`);
@@ -32691,7 +32886,7 @@ async function pruneAttachmentCache(rootDir, maxBytes, log, preserveDirs) {
32691
32886
  return;
32692
32887
  let entries;
32693
32888
  try {
32694
- entries = await fs3.readdir(rootDir, { withFileTypes: true });
32889
+ entries = await fs4.readdir(rootDir, { withFileTypes: true });
32695
32890
  } catch {
32696
32891
  return;
32697
32892
  }
@@ -32700,9 +32895,9 @@ async function pruneAttachmentCache(rootDir, maxBytes, log, preserveDirs) {
32700
32895
  for (const entry of entries) {
32701
32896
  if (!entry.isDirectory())
32702
32897
  continue;
32703
- const fullPath = path3.join(rootDir, entry.name);
32898
+ const fullPath = path4.join(rootDir, entry.name);
32704
32899
  try {
32705
- const stat = await fs3.lstat(fullPath);
32900
+ const stat = await fs4.lstat(fullPath);
32706
32901
  if (!stat.isDirectory())
32707
32902
  continue;
32708
32903
  const size = await directorySize(fullPath);
@@ -32718,10 +32913,10 @@ async function pruneAttachmentCache(rootDir, maxBytes, log, preserveDirs) {
32718
32913
  for (const dir of dirs) {
32719
32914
  if (total <= maxBytes)
32720
32915
  break;
32721
- if (preserveDirs?.has(path3.resolve(dir.path)))
32916
+ if (preserveDirs?.has(path4.resolve(dir.path)))
32722
32917
  continue;
32723
32918
  try {
32724
- await fs3.rm(dir.path, { recursive: true, force: true });
32919
+ await fs4.rm(dir.path, { recursive: true, force: true });
32725
32920
  total -= dir.size;
32726
32921
  } catch (err) {
32727
32922
  log?.warn?.(`agent-core: failed to prune attachment cache dir ${dir.path}: ${String(err)}`);
@@ -32730,12 +32925,12 @@ async function pruneAttachmentCache(rootDir, maxBytes, log, preserveDirs) {
32730
32925
  }
32731
32926
  async function directorySize(dirPath) {
32732
32927
  let total = 0;
32733
- const entries = await fs3.readdir(dirPath, { withFileTypes: true });
32928
+ const entries = await fs4.readdir(dirPath, { withFileTypes: true });
32734
32929
  for (const entry of entries) {
32735
- const fullPath = path3.join(dirPath, entry.name);
32930
+ const fullPath = path4.join(dirPath, entry.name);
32736
32931
  let stat;
32737
32932
  try {
32738
- stat = await fs3.lstat(fullPath);
32933
+ stat = await fs4.lstat(fullPath);
32739
32934
  } catch {
32740
32935
  continue;
32741
32936
  }
@@ -32750,10 +32945,10 @@ async function directorySize(dirPath) {
32750
32945
  return total;
32751
32946
  }
32752
32947
  function activeDirsForRoot(rootDir) {
32753
- const root = path3.resolve(rootDir);
32948
+ const root = path4.resolve(rootDir);
32754
32949
  const dirs = /* @__PURE__ */ new Set();
32755
32950
  for (const dir of activeAttachmentDirs) {
32756
- if (dir === root || dir.startsWith(`${root}${path3.sep}`)) {
32951
+ if (dir === root || dir.startsWith(`${root}${path4.sep}`)) {
32757
32952
  dirs.add(dir);
32758
32953
  }
32759
32954
  }
@@ -32850,9 +33045,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
32850
33045
  }
32851
33046
  writtenStat = await file.stat();
32852
33047
  await closeFile();
32853
- await localDirectoryStatInsideRoot(path3.dirname(filePath), rootDir);
33048
+ await localDirectoryStatInsideRoot(path4.dirname(filePath), rootDir);
32854
33049
  await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
32855
- await fs3.rename(tmpPath, filePath);
33050
+ await fs4.rename(tmpPath, filePath);
32856
33051
  completed = true;
32857
33052
  return written;
32858
33053
  } finally {
@@ -32868,9 +33063,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
32868
33063
  }
32869
33064
  }
32870
33065
  function localFileName(attachmentId, fileName, mimeType) {
32871
- const safeName = sanitizePathSegment(path3.basename(fileName || attachmentId));
32872
- const ext = path3.extname(safeName) || extensionForMime(mimeType);
32873
- const stem = path3.basename(safeName, path3.extname(safeName)) || attachmentId;
33066
+ const safeName = sanitizePathSegment(path4.basename(fileName || attachmentId));
33067
+ const ext = path4.extname(safeName) || extensionForMime(mimeType);
33068
+ const stem = path4.basename(safeName, path4.extname(safeName)) || attachmentId;
32874
33069
  return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
32875
33070
  }
32876
33071
  function extensionForMime(mimeType) {
@@ -32936,7 +33131,7 @@ function parseContentLength(value) {
32936
33131
  // dist/gateway.js
32937
33132
  import * as crypto2 from "node:crypto";
32938
33133
  import * as os2 from "node:os";
32939
- import * as path7 from "node:path";
33134
+ import * as path8 from "node:path";
32940
33135
 
32941
33136
  // dist/runtime.js
32942
33137
  var runtime = null;
@@ -32994,15 +33189,27 @@ function buildOrchestratorSessionKey(accountId) {
32994
33189
  }
32995
33190
 
32996
33191
  // dist/config-manager.js
32997
- import * as fs4 from "node:fs";
32998
- import * as path4 from "node:path";
33192
+ import * as fs5 from "node:fs";
33193
+ import * as path5 from "node:path";
33194
+ var currentCapabilities = [];
33195
+ function getChannelCapabilityFragments() {
33196
+ return currentCapabilities.map((c) => c.fragment);
33197
+ }
33198
+ function getChannelCapabilityKeys() {
33199
+ return currentCapabilities.map((c) => c.key);
33200
+ }
33201
+ function applyChannelCapabilitySnapshot(stateDir, config, log) {
33202
+ const caps = extractCapabilities(config);
33203
+ materializeChannelCapabilities(stateDir, caps, log);
33204
+ currentCapabilities = caps;
33205
+ }
32999
33206
  var CACHE_FILENAME = "parall-platform-config.json";
33000
33207
  function cachePath(stateDir) {
33001
- return path4.join(stateDir, CACHE_FILENAME);
33208
+ return path5.join(stateDir, CACHE_FILENAME);
33002
33209
  }
33003
33210
  function loadCachedConfig(stateDir) {
33004
33211
  try {
33005
- const raw = fs4.readFileSync(cachePath(stateDir), "utf-8");
33212
+ const raw = fs5.readFileSync(cachePath(stateDir), "utf-8");
33006
33213
  return JSON.parse(raw);
33007
33214
  } catch {
33008
33215
  return null;
@@ -33016,14 +33223,14 @@ function saveCachedConfig(stateDir, config) {
33016
33223
  };
33017
33224
  const filePath = cachePath(stateDir);
33018
33225
  const tmpPath = `${filePath}.tmp`;
33019
- fs4.mkdirSync(path4.dirname(filePath), { recursive: true });
33020
- fs4.writeFileSync(tmpPath, JSON.stringify(cached, null, 2), "utf-8");
33021
- fs4.renameSync(tmpPath, filePath);
33226
+ fs5.mkdirSync(path5.dirname(filePath), { recursive: true });
33227
+ fs5.writeFileSync(tmpPath, JSON.stringify(cached, null, 2), "utf-8");
33228
+ fs5.renameSync(tmpPath, filePath);
33022
33229
  }
33023
33230
  function applyToOpenClawConfig(configPath, platformConfig, credentials) {
33024
33231
  let existing = {};
33025
33232
  try {
33026
- const raw = fs4.readFileSync(configPath, "utf-8");
33233
+ const raw = fs5.readFileSync(configPath, "utf-8");
33027
33234
  existing = JSON.parse(raw);
33028
33235
  } catch {
33029
33236
  }
@@ -33095,9 +33302,9 @@ function applyToOpenClawConfig(configPath, platformConfig, credentials) {
33095
33302
  agents.defaults = cleanedExisting;
33096
33303
  existing.agents = agents;
33097
33304
  const tmpPath = `${configPath}.tmp`;
33098
- fs4.mkdirSync(path4.dirname(configPath), { recursive: true });
33099
- fs4.writeFileSync(tmpPath, JSON.stringify(existing, null, 2), "utf-8");
33100
- fs4.renameSync(tmpPath, configPath);
33305
+ fs5.mkdirSync(path5.dirname(configPath), { recursive: true });
33306
+ fs5.writeFileSync(tmpPath, JSON.stringify(existing, null, 2), "utf-8");
33307
+ fs5.renameSync(tmpPath, configPath);
33101
33308
  }
33102
33309
  async function fetchAndApplyPlatformConfig(opts) {
33103
33310
  const { client, stateDir, configPath, credentials, log } = opts;
@@ -33109,6 +33316,7 @@ async function fetchAndApplyPlatformConfig(opts) {
33109
33316
  if (cached) {
33110
33317
  log?.warn(`platform config fetch failed, using cached version ${cached.version}: ${String(err)}`);
33111
33318
  applyToOpenClawConfig(configPath, cached.config, credentials);
33319
+ applyChannelCapabilitySnapshot(stateDir, cached.config, log);
33112
33320
  return;
33113
33321
  }
33114
33322
  log?.error(`platform config fetch failed and no cache available: ${String(err)}`);
@@ -33118,6 +33326,7 @@ async function fetchAndApplyPlatformConfig(opts) {
33118
33326
  log?.info("platform config unchanged (304)");
33119
33327
  if (cached) {
33120
33328
  applyToOpenClawConfig(configPath, cached.config, credentials);
33329
+ applyChannelCapabilitySnapshot(stateDir, cached.config, log);
33121
33330
  }
33122
33331
  return;
33123
33332
  }
@@ -33126,17 +33335,19 @@ async function fetchAndApplyPlatformConfig(opts) {
33126
33335
  log?.error(`platform config schema_version ${fresh.schema_version} is newer than supported (${SUPPORTED_SCHEMA_VERSION}), keeping current config`);
33127
33336
  if (cached) {
33128
33337
  applyToOpenClawConfig(configPath, cached.config, credentials);
33338
+ applyChannelCapabilitySnapshot(stateDir, cached.config, log);
33129
33339
  }
33130
33340
  return;
33131
33341
  }
33132
33342
  log?.info(`platform config updated to version ${fresh.version}`);
33133
33343
  saveCachedConfig(stateDir, fresh);
33344
+ applyChannelCapabilitySnapshot(stateDir, fresh.config, log);
33134
33345
  applyToOpenClawConfig(configPath, fresh.config, credentials);
33135
33346
  }
33136
33347
 
33137
33348
  // dist/wiki-helper.js
33138
33349
  import { spawn, spawnSync } from "node:child_process";
33139
- import path5 from "node:path";
33350
+ import path6 from "node:path";
33140
33351
  var DEFAULT_SYNC_TIMEOUT_MS = 9e4;
33141
33352
  var DEFAULT_WATCH_INTERVAL_SEC = 30;
33142
33353
  function isCommandMissing(error) {
@@ -33151,7 +33362,7 @@ function resolveParallCli() {
33151
33362
  return _cli;
33152
33363
  }
33153
33364
  function resolveMountRoot(stateDir) {
33154
- return process.env.PRLL_WIKI_MOUNT_ROOT?.trim() || path5.join(stateDir, "workspace");
33365
+ return process.env.PRLL_WIKI_MOUNT_ROOT?.trim() || path6.join(stateDir, "workspace");
33155
33366
  }
33156
33367
  function resolveWatchIntervalSec() {
33157
33368
  const raw = process.env.PRLL_WIKI_REFRESH_INTERVAL_SEC?.trim();
@@ -33266,8 +33477,8 @@ async function startWikiHelper(params) {
33266
33477
 
33267
33478
  // dist/oc-session.js
33268
33479
  import { randomUUID } from "node:crypto";
33269
- import { existsSync as existsSync2, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
33270
- import { join as join4, resolve as resolve2 } from "node:path";
33480
+ import { existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "node:fs";
33481
+ import { join as join5, resolve as resolve2 } from "node:path";
33271
33482
  var CURRENT_SESSION_VERSION = 3;
33272
33483
  function generateId(existing) {
33273
33484
  for (let i = 0; i < 100; i++) {
@@ -33278,9 +33489,9 @@ function generateId(existing) {
33278
33489
  return randomUUID();
33279
33490
  }
33280
33491
  function loadEntries(filePath) {
33281
- if (!existsSync2(filePath))
33492
+ if (!existsSync3(filePath))
33282
33493
  return [];
33283
- const lines = readFileSync4(filePath, "utf-8").trim().split("\n");
33494
+ const lines = readFileSync5(filePath, "utf-8").trim().split("\n");
33284
33495
  const entries = [];
33285
33496
  for (const line of lines) {
33286
33497
  if (!line.trim())
@@ -33359,8 +33570,8 @@ var SessionManager = class _SessionManager {
33359
33570
  constructor(cwd, sessionDir, sessionFile) {
33360
33571
  this.cwd = cwd;
33361
33572
  this.sessionDir = sessionDir;
33362
- if (sessionDir && !existsSync2(sessionDir)) {
33363
- mkdirSync4(sessionDir, { recursive: true });
33573
+ if (sessionDir && !existsSync3(sessionDir)) {
33574
+ mkdirSync5(sessionDir, { recursive: true });
33364
33575
  }
33365
33576
  if (sessionFile) {
33366
33577
  this.load(sessionFile);
@@ -33371,7 +33582,7 @@ var SessionManager = class _SessionManager {
33371
33582
  // -- Init / load -----------------------------------------------------------
33372
33583
  load(file) {
33373
33584
  this.sessionFile = resolve2(file);
33374
- if (!existsSync2(this.sessionFile)) {
33585
+ if (!existsSync3(this.sessionFile)) {
33375
33586
  const p = this.sessionFile;
33376
33587
  this.initEmpty();
33377
33588
  this.sessionFile = p;
@@ -33413,7 +33624,7 @@ var SessionManager = class _SessionManager {
33413
33624
  this.leafId = null;
33414
33625
  this.flushed = false;
33415
33626
  const ts = timestamp.replace(/[:.]/g, "-");
33416
- this.sessionFile = join4(this.sessionDir, `${ts}_${this.sessionId}.jsonl`);
33627
+ this.sessionFile = join5(this.sessionDir, `${ts}_${this.sessionId}.jsonl`);
33417
33628
  }
33418
33629
  buildIndex() {
33419
33630
  this.byId.clear();
@@ -33440,7 +33651,7 @@ var SessionManager = class _SessionManager {
33440
33651
  rewrite() {
33441
33652
  if (!this.sessionFile)
33442
33653
  return;
33443
- writeFileSync3(this.sessionFile, this.fileEntries.map((e) => JSON.stringify(e)).join("\n") + "\n");
33654
+ writeFileSync4(this.sessionFile, this.fileEntries.map((e) => JSON.stringify(e)).join("\n") + "\n");
33444
33655
  }
33445
33656
  // -- Public accessors ------------------------------------------------------
33446
33657
  getLeafId() {
@@ -33460,14 +33671,14 @@ var SessionManager = class _SessionManager {
33460
33671
  }
33461
33672
  // -- Branching -------------------------------------------------------------
33462
33673
  getBranch(fromId) {
33463
- const path8 = [];
33674
+ const path9 = [];
33464
33675
  const startId = fromId ?? this.leafId;
33465
33676
  let current = startId ? this.byId.get(startId) : void 0;
33466
33677
  while (current) {
33467
- path8.unshift(current);
33678
+ path9.unshift(current);
33468
33679
  current = current.parentId ? this.byId.get(current.parentId) : void 0;
33469
33680
  }
33470
- return path8;
33681
+ return path9;
33471
33682
  }
33472
33683
  createBranchedSession(leafId) {
33473
33684
  const branch = this.getBranch(leafId);
@@ -33477,7 +33688,7 @@ var SessionManager = class _SessionManager {
33477
33688
  const newId = randomUUID();
33478
33689
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
33479
33690
  const ts = timestamp.replace(/[:.]/g, "-");
33480
- const newFile = join4(this.sessionDir, `${ts}_${newId}.jsonl`);
33691
+ const newFile = join5(this.sessionDir, `${ts}_${newId}.jsonl`);
33481
33692
  const header = {
33482
33693
  type: "session",
33483
33694
  version: CURRENT_SESSION_VERSION,
@@ -33523,50 +33734,50 @@ var SessionManager = class _SessionManager {
33523
33734
  return newFile;
33524
33735
  }
33525
33736
  // -- Factory ---------------------------------------------------------------
33526
- static open(path8) {
33527
- const entries = loadEntries(path8);
33737
+ static open(path9) {
33738
+ const entries = loadEntries(path9);
33528
33739
  const header = entries.find((e) => e.type === "session");
33529
33740
  const cwd = header?.cwd ?? process.cwd();
33530
- const dir = resolve2(path8, "..");
33531
- return new _SessionManager(cwd, dir, path8);
33741
+ const dir = resolve2(path9, "..");
33742
+ return new _SessionManager(cwd, dir, path9);
33532
33743
  }
33533
33744
  };
33534
33745
 
33535
33746
  // dist/fork.js
33536
- import * as fs5 from "node:fs";
33537
- import * as path6 from "node:path";
33747
+ import * as fs6 from "node:fs";
33748
+ import * as path7 from "node:path";
33538
33749
  import * as crypto from "node:crypto";
33539
33750
  function readStoreEntry(sessionsDir, sessionKey) {
33540
- const storeFile = path6.join(sessionsDir, "sessions.json");
33751
+ const storeFile = path7.join(sessionsDir, "sessions.json");
33541
33752
  try {
33542
- const store = JSON.parse(fs5.readFileSync(storeFile, "utf-8"));
33753
+ const store = JSON.parse(fs6.readFileSync(storeFile, "utf-8"));
33543
33754
  return store[sessionKey] ?? store[sessionKey.toLowerCase()] ?? null;
33544
33755
  } catch {
33545
33756
  return null;
33546
33757
  }
33547
33758
  }
33548
33759
  function writeStoreEntry(sessionsDir, sessionKey, entry) {
33549
- const storeFile = path6.join(sessionsDir, "sessions.json");
33760
+ const storeFile = path7.join(sessionsDir, "sessions.json");
33550
33761
  try {
33551
33762
  let store = {};
33552
33763
  try {
33553
- store = JSON.parse(fs5.readFileSync(storeFile, "utf-8"));
33764
+ store = JSON.parse(fs6.readFileSync(storeFile, "utf-8"));
33554
33765
  } catch {
33555
33766
  }
33556
33767
  store[sessionKey.toLowerCase()] = entry;
33557
- fs5.writeFileSync(storeFile, JSON.stringify(store, null, 2), { encoding: "utf-8" });
33768
+ fs6.writeFileSync(storeFile, JSON.stringify(store, null, 2), { encoding: "utf-8" });
33558
33769
  return true;
33559
33770
  } catch {
33560
33771
  return false;
33561
33772
  }
33562
33773
  }
33563
33774
  function deleteStoreEntry(sessionsDir, sessionKey) {
33564
- const storeFile = path6.join(sessionsDir, "sessions.json");
33775
+ const storeFile = path7.join(sessionsDir, "sessions.json");
33565
33776
  try {
33566
- const store = JSON.parse(fs5.readFileSync(storeFile, "utf-8"));
33777
+ const store = JSON.parse(fs6.readFileSync(storeFile, "utf-8"));
33567
33778
  delete store[sessionKey];
33568
33779
  delete store[sessionKey.toLowerCase()];
33569
- fs5.writeFileSync(storeFile, JSON.stringify(store, null, 2), { encoding: "utf-8" });
33780
+ fs6.writeFileSync(storeFile, JSON.stringify(store, null, 2), { encoding: "utf-8" });
33570
33781
  } catch {
33571
33782
  }
33572
33783
  }
@@ -33578,17 +33789,17 @@ function resolveTranscriptFile(sessionsDir, sessionKey) {
33578
33789
  if (!entry?.sessionId)
33579
33790
  return null;
33580
33791
  if (entry.sessionFile) {
33581
- const resolved = path6.isAbsolute(entry.sessionFile) ? entry.sessionFile : path6.join(sessionsDir, entry.sessionFile);
33582
- if (fs5.existsSync(resolved))
33792
+ const resolved = path7.isAbsolute(entry.sessionFile) ? entry.sessionFile : path7.join(sessionsDir, entry.sessionFile);
33793
+ if (fs6.existsSync(resolved))
33583
33794
  return resolved;
33584
33795
  }
33585
- const conventional = path6.join(sessionsDir, `${entry.sessionId}.jsonl`);
33586
- if (fs5.existsSync(conventional))
33796
+ const conventional = path7.join(sessionsDir, `${entry.sessionId}.jsonl`);
33797
+ if (fs6.existsSync(conventional))
33587
33798
  return conventional;
33588
33799
  try {
33589
- const files = fs5.readdirSync(sessionsDir);
33800
+ const files = fs6.readdirSync(sessionsDir);
33590
33801
  const match = files.find((file) => file.includes(entry.sessionId) && file.endsWith(".jsonl"));
33591
- return match ? path6.join(sessionsDir, match) : null;
33802
+ return match ? path7.join(sessionsDir, match) : null;
33592
33803
  } catch {
33593
33804
  return null;
33594
33805
  }
@@ -33599,7 +33810,7 @@ function resolveSessionId(sessionsDir, sessionKey) {
33599
33810
  }
33600
33811
  function forkOrchestratorSession(opts) {
33601
33812
  const { orchestratorSessionKey, accountId, transcriptFile, sessionsDir } = opts;
33602
- if (!fs5.existsSync(transcriptFile))
33813
+ if (!fs6.existsSync(transcriptFile))
33603
33814
  return null;
33604
33815
  try {
33605
33816
  const manager = SessionManager.open(transcriptFile);
@@ -33619,7 +33830,7 @@ function forkOrchestratorSession(opts) {
33619
33830
  sessionId = crypto.randomUUID();
33620
33831
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
33621
33832
  const fileTimestamp = timestamp.replace(/[:.]/g, "-");
33622
- sessionFile = path6.join(manager.getSessionDir(), `${fileTimestamp}_${sessionId}.jsonl`);
33833
+ sessionFile = path7.join(manager.getSessionDir(), `${fileTimestamp}_${sessionId}.jsonl`);
33623
33834
  const header = {
33624
33835
  type: "session",
33625
33836
  version: CURRENT_SESSION_VERSION,
@@ -33628,7 +33839,7 @@ function forkOrchestratorSession(opts) {
33628
33839
  cwd: manager.getCwd(),
33629
33840
  parentSession: transcriptFile
33630
33841
  };
33631
- fs5.writeFileSync(sessionFile, `${JSON.stringify(header)}
33842
+ fs6.writeFileSync(sessionFile, `${JSON.stringify(header)}
33632
33843
  `, {
33633
33844
  encoding: "utf-8",
33634
33845
  mode: 384,
@@ -33638,7 +33849,7 @@ function forkOrchestratorSession(opts) {
33638
33849
  const forkSessionKey = `${orchestratorSessionKey}:fork:${sessionId}`;
33639
33850
  const wrote = writeStoreEntry(sessionsDir, forkSessionKey, {
33640
33851
  sessionId,
33641
- sessionFile: path6.relative(sessionsDir, sessionFile),
33852
+ sessionFile: path7.relative(sessionsDir, sessionFile),
33642
33853
  updatedAt: Date.now(),
33643
33854
  spawnedBy: orchestratorSessionKey,
33644
33855
  parentSessionKey: orchestratorSessionKey,
@@ -33653,8 +33864,8 @@ function forkOrchestratorSession(opts) {
33653
33864
  }
33654
33865
  function cleanupForkSession(opts) {
33655
33866
  try {
33656
- if (fs5.existsSync(opts.sessionFile)) {
33657
- fs5.unlinkSync(opts.sessionFile);
33867
+ if (fs6.existsSync(opts.sessionFile)) {
33868
+ fs6.unlinkSync(opts.sessionFile);
33658
33869
  }
33659
33870
  } catch {
33660
33871
  }
@@ -33964,8 +34175,13 @@ var parallGateway = {
33964
34175
  const telemetry = await initAgentTelemetry("parall-openclaw-agent", "openclaw");
33965
34176
  const otelLog = createOtelLogger("agent", "openclaw-agent");
33966
34177
  try {
33967
- const stateDir = process.env.OPENCLAW_STATE_DIR || path7.join(process.env.HOME || "/data", ".openclaw");
33968
- const openclawConfigPath = path7.join(stateDir, "openclaw.json");
34178
+ const stateDir = process.env.OPENCLAW_STATE_DIR || path8.join(process.env.HOME || "/data", ".openclaw");
34179
+ const openclawConfigPath = path8.join(stateDir, "openclaw.json");
34180
+ const shimDir = capabilityBinDir(stateDir);
34181
+ const currentPath = process.env.PATH ?? "";
34182
+ if (!currentPath.split(path8.delimiter).includes(shimDir)) {
34183
+ process.env.PATH = currentPath ? `${shimDir}${path8.delimiter}${currentPath}` : shimDir;
34184
+ }
33969
34185
  const configManagerOpts = {
33970
34186
  client,
33971
34187
  stateDir,
@@ -34001,7 +34217,7 @@ var parallGateway = {
34001
34217
  wsUrl
34002
34218
  });
34003
34219
  const orchestratorKey = buildOrchestratorSessionKey(ctx.accountId);
34004
- const sessionsDir = path7.join(stateDir, "agents", "main", "sessions");
34220
+ const sessionsDir = path8.join(stateDir, "agents", "main", "sessions");
34005
34221
  const workspaceDir = process.cwd();
34006
34222
  ensureLocalAttachmentGitExclude(workspaceDir);
34007
34223
  const dispatchAdapter = createOpenClawDispatchAdapter({
@@ -34027,6 +34243,9 @@ var parallGateway = {
34027
34243
  runtimeRef: { hostname: os2.hostname(), pid: process.pid },
34028
34244
  dispatchAdapter,
34029
34245
  log: otelLog,
34246
+ // Live capability view for hint routing: the channel reply hint
34247
+ // points at the vendor CLI only while the grant is active.
34248
+ getCapabilityKeys: getChannelCapabilityKeys,
34030
34249
  shutdownDeadlineMs: parseShutdownDeadlineMs(process.env.PRLL_SHUTDOWN_DEADLINE_MS),
34031
34250
  forkDeadlineMs: parseForkDeadlineMs(process.env.PRLL_FORK_DEADLINE_MS),
34032
34251
  dispatchDeadlineMs: parseDispatchDeadlineMs(process.env.PRLL_DISPATCH_DEADLINE_MS),
@@ -34220,7 +34439,13 @@ function registerParallHooks(api) {
34220
34439
  buildIdentity(getAgentIdentity()),
34221
34440
  PRLL_CHANNEL_CONTEXT,
34222
34441
  PRLL_BEHAVIOR,
34223
- PRLL_REFERENCE_GUIDE
34442
+ PRLL_REFERENCE_GUIDE,
34443
+ // Channel-capability declarations (platform-config
34444
+ // agents.capabilities[]). Evaluated on EVERY prompt build, so a
34445
+ // capability grant/revocation reaches the next turn without any
34446
+ // restart — the openclaw analogue of the CLI bridges' prompt-file
34447
+ // rewrite + respawn.
34448
+ ...getChannelCapabilityFragments()
34224
34449
  ].join("\n\n")
34225
34450
  };
34226
34451
  });