@parall/parall 1.42.1 → 1.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;
@@ -26479,664 +26479,18 @@ function laneKeyForTarget(targetUri, threadRootId) {
26479
26479
  return Buffer.from(`${targetUri}
26480
26480
  ${threadRootId ?? ""}`, "utf8").toString("base64url");
26481
26481
  }
26482
+ function dispatchLaneContextDir(stateDir) {
26483
+ return path.join(stateDir, "dispatch-lane-context");
26484
+ }
26482
26485
  function laneContextFilePath(contextDir, targetUri, threadRootId) {
26483
26486
  return path.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
26484
26487
  }
26485
26488
 
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
- }
26489
+ // ../agent-core/dist/lane-ledger.js
26490
+ import * as fs from "node:fs";
26576
26491
 
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";
27137
-
27138
- // ../sdk/dist/types.js
27139
- var MENTION_ALL_USER_ID = "all";
26492
+ // ../sdk/dist/types.js
26493
+ var MENTION_ALL_USER_ID = "all";
27140
26494
 
27141
26495
  // ../sdk/dist/constants.js
27142
26496
  var API_BASE = "/api/v1";
@@ -27579,6 +26933,7 @@ var ParallClient = class _ParallClient {
27579
26933
  setTokens;
27580
26934
  refreshPromise = null;
27581
26935
  swimlaneName;
26936
+ getFeatureFlagOverrides;
27582
26937
  /** Auth endpoints excluded from automatic 401 refresh to prevent recursion. */
27583
26938
  static AUTH_PATHS = /* @__PURE__ */ new Set([
27584
26939
  "/auth/login",
@@ -27609,7 +26964,7 @@ var ParallClient = class _ParallClient {
27609
26964
  return apiError;
27610
26965
  }
27611
26966
  /** Build headers common to all requests (auth, swimlane). */
27612
- buildHeaders(extra) {
26967
+ buildHeaders(path9, extra) {
27613
26968
  const headers = {
27614
26969
  "Content-Type": "application/json",
27615
26970
  ...extra
@@ -27620,6 +26975,11 @@ var ParallClient = class _ParallClient {
27620
26975
  if (this.swimlaneName) {
27621
26976
  headers["X-Prll-Swimlane"] = this.swimlaneName;
27622
26977
  }
26978
+ if (path9.startsWith(API_BASE)) {
26979
+ const overrides = this.getFeatureFlagOverrides?.();
26980
+ if (overrides)
26981
+ headers["X-Prll-FF-Override"] = overrides;
26982
+ }
27623
26983
  return headers;
27624
26984
  }
27625
26985
  constructor(options = {}) {
@@ -27630,6 +26990,7 @@ var ParallClient = class _ParallClient {
27630
26990
  this.getRefreshToken = options.getRefreshToken;
27631
26991
  this.setTokens = options.setTokens;
27632
26992
  this.swimlaneName = options.swimlaneName;
26993
+ this.getFeatureFlagOverrides = options.getFeatureFlagOverrides;
27633
26994
  }
27634
26995
  /**
27635
26996
  * Pick the origin for a request path: wiki-service base for `/wiki/v1`
@@ -27637,8 +26998,8 @@ var ParallClient = class _ParallClient {
27637
26998
  * is authoritative, so wiki vs api routing can't drift from how a caller
27638
26999
  * happens to invoke the client.
27639
27000
  */
27640
- baseUrlFor(path8) {
27641
- return path8.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
27001
+ baseUrlFor(path9) {
27002
+ return path9.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
27642
27003
  }
27643
27004
  setToken(token) {
27644
27005
  this.token = token;
@@ -27665,10 +27026,10 @@ var ParallClient = class _ParallClient {
27665
27026
  * REFRESH_THRESHOLD_S, refresh it **before** sending the request.
27666
27027
  * No-op when the token is still fresh, missing, or un-parseable.
27667
27028
  */
27668
- async ensureFreshToken(path8) {
27029
+ async ensureFreshToken(path9) {
27669
27030
  if (!this.token || !this.getRefreshToken)
27670
27031
  return;
27671
- const pathSuffix = path8.replace(/^\/api\/v1/, "");
27032
+ const pathSuffix = path9.replace(/^\/api\/v1/, "");
27672
27033
  if (_ParallClient.AUTH_PATHS.has(pathSuffix))
27673
27034
  return;
27674
27035
  const exp = _ParallClient.decodeJwtExp(this.token);
@@ -27700,11 +27061,11 @@ var ParallClient = class _ParallClient {
27700
27061
  this.refreshPromise = null;
27701
27062
  }
27702
27063
  }
27703
- async request(method, path8, body, query, retried = false, opts) {
27064
+ async request(method, path9, body, query, retried = false, opts) {
27704
27065
  if (!retried) {
27705
- await this.ensureFreshToken(path8);
27066
+ await this.ensureFreshToken(path9);
27706
27067
  }
27707
- let url = `${this.baseUrlFor(path8)}${path8}`;
27068
+ let url = `${this.baseUrlFor(path9)}${path9}`;
27708
27069
  if (query) {
27709
27070
  const params = new URLSearchParams();
27710
27071
  for (const [key, value] of Object.entries(query)) {
@@ -27716,7 +27077,7 @@ var ParallClient = class _ParallClient {
27716
27077
  if (qs)
27717
27078
  url += `?${qs}`;
27718
27079
  }
27719
- const headers = this.buildHeaders();
27080
+ const headers = this.buildHeaders(path9);
27720
27081
  const timeoutSignal = AbortSignal.timeout(opts?.timeoutMs ?? 15e3);
27721
27082
  const signal = opts?.signal ? AbortSignal.any([opts.signal, timeoutSignal]) : timeoutSignal;
27722
27083
  let res;
@@ -27734,12 +27095,12 @@ var ParallClient = class _ParallClient {
27734
27095
  throw _ParallClient.normalizeFetchError(err);
27735
27096
  }
27736
27097
  if (res.status === 401) {
27737
- const pathSuffix = path8.replace(/^\/api\/v1/, "");
27098
+ const pathSuffix = path9.replace(/^\/api\/v1/, "");
27738
27099
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
27739
27100
  if (!retried && !isAuthPath && this.getRefreshToken) {
27740
27101
  const refreshed = await this.tryRefresh();
27741
27102
  if (refreshed) {
27742
- return this.request(method, path8, body, query, true, opts);
27103
+ return this.request(method, path9, body, query, true, opts);
27743
27104
  }
27744
27105
  }
27745
27106
  if (this.onTokenExpired && !isAuthPath) {
@@ -27769,15 +27130,15 @@ var ParallClient = class _ParallClient {
27769
27130
  * hit the 100 MiB cap, so a longer 5-minute timeout is used so a
27770
27131
  * 50 MiB blob on a slow connection doesn't get chopped at 15 s.
27771
27132
  */
27772
- async multipartRequest(method, path8, body, retried = false) {
27133
+ async multipartRequest(method, path9, body, retried = false) {
27773
27134
  if (!retried) {
27774
- await this.ensureFreshToken(path8);
27135
+ await this.ensureFreshToken(path9);
27775
27136
  }
27776
- const { "Content-Type": _drop, ...headers } = this.buildHeaders();
27137
+ const { "Content-Type": _drop, ...headers } = this.buildHeaders(path9);
27777
27138
  void _drop;
27778
27139
  let res;
27779
27140
  try {
27780
- res = await fetch(`${this.baseUrlFor(path8)}${path8}`, {
27141
+ res = await fetch(`${this.baseUrlFor(path9)}${path9}`, {
27781
27142
  method,
27782
27143
  headers,
27783
27144
  body,
@@ -27787,12 +27148,12 @@ var ParallClient = class _ParallClient {
27787
27148
  throw _ParallClient.normalizeFetchError(err);
27788
27149
  }
27789
27150
  if (res.status === 401) {
27790
- const pathSuffix = path8.replace(/^\/api\/v1/, "");
27151
+ const pathSuffix = path9.replace(/^\/api\/v1/, "");
27791
27152
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
27792
27153
  if (!retried && !isAuthPath && this.getRefreshToken) {
27793
27154
  const refreshed = await this.tryRefresh();
27794
27155
  if (refreshed) {
27795
- return this.multipartRequest(method, path8, body, true);
27156
+ return this.multipartRequest(method, path9, body, true);
27796
27157
  }
27797
27158
  }
27798
27159
  if (this.onTokenExpired && !isAuthPath) {
@@ -28496,8 +27857,8 @@ var ParallClient = class _ParallClient {
28496
27857
  async requestMachineUpdate(orgId, machineId, mandatory = false) {
28497
27858
  await this.request("POST", ENDPOINTS.MACHINE_REQUEST_UPDATE(orgId, machineId), { mandatory });
28498
27859
  }
28499
- async browseMachineFilesystem(orgId, machineId, path8) {
28500
- return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path8 }, void 0, false, { timeoutMs: 15e3 });
27860
+ async browseMachineFilesystem(orgId, machineId, path9) {
27861
+ return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path9 }, void 0, false, { timeoutMs: 15e3 });
28501
27862
  }
28502
27863
  /** Create a new machine key. Returns the raw key string (shown once) + metadata. */
28503
27864
  async createMachineKey(orgId, machineId, name) {
@@ -28582,7 +27943,6 @@ var ParallClient = class _ParallClient {
28582
27943
  async steerDispatch(orgId, req) {
28583
27944
  return this.request("POST", ENDPOINTS.DISPATCH_STEER(orgId), req);
28584
27945
  }
28585
- /** End a turn: no_action sweep of the lane's members + lane release + re-drive check. */
28586
27946
  async completeDispatch(orgId, req) {
28587
27947
  return this.request("POST", ENDPOINTS.DISPATCH_COMPLETE(orgId), req);
28588
27948
  }
@@ -28590,6 +27950,10 @@ var ParallClient = class _ParallClient {
28590
27950
  * End a turn for a lane-less runtime: resolve the turn's folded WorkItems
28591
27951
  * by source — broad-cover to the turn's reply Effect when one exists,
28592
27952
  * no_action sweep otherwise. Idempotent.
27953
+ *
27954
+ * @deprecated Legacy ok-only alias — use {@link completeDispatch} with the
27955
+ * `sources` form, which also carries `turn_outcome`. The endpoint retires
27956
+ * at S3b (dispatch-convergence-design.md §3).
28593
27957
  */
28594
27958
  async completeDispatchSources(orgId, req) {
28595
27959
  return this.request("POST", ENDPOINTS.DISPATCH_COMPLETE_SOURCES(orgId), req);
@@ -28618,7 +27982,7 @@ var ParallClient = class _ParallClient {
28618
27982
  if (currentVersion !== void 0) {
28619
27983
  extra["If-None-Match"] = currentVersion;
28620
27984
  }
28621
- const headers = this.buildHeaders(extra);
27985
+ const headers = this.buildHeaders(ENDPOINTS.PLATFORM_CONFIG, extra);
28622
27986
  let res;
28623
27987
  try {
28624
27988
  res = await fetch(url, {
@@ -29066,8 +28430,8 @@ var ParallClient = class _ParallClient {
29066
28430
  async deleteWikiRestriction(orgId, wikiId, restrictionId) {
29067
28431
  await this.request("DELETE", ENDPOINTS.WIKI_RESTRICTION(orgId, wikiId, restrictionId));
29068
28432
  }
29069
- async getWikiAccessStatus(orgId, wikiId, path8) {
29070
- return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path8 ? { path: path8 } : void 0);
28433
+ async getWikiAccessStatus(orgId, wikiId, path9) {
28434
+ return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path9 ? { path: path9 } : void 0);
29071
28435
  }
29072
28436
  async createWikiAccessRequest(orgId, wikiId, data) {
29073
28437
  await this.request("POST", ENDPOINTS.WIKI_ACCESS_REQUESTS(orgId, wikiId), data);
@@ -29076,14 +28440,14 @@ var ParallClient = class _ParallClient {
29076
28440
  async getWikiCommits(orgId, wikiId, params) {
29077
28441
  return this.request("GET", ENDPOINTS.WIKI_COMMITS(orgId, wikiId), void 0, params);
29078
28442
  }
29079
- async getWikiFileCommits(orgId, wikiId, path8, params) {
28443
+ async getWikiFileCommits(orgId, wikiId, path9, params) {
29080
28444
  return this.request("GET", ENDPOINTS.WIKI_FILE_COMMITS(orgId, wikiId), void 0, {
29081
- path: path8,
28445
+ path: path9,
29082
28446
  ...params
29083
28447
  });
29084
28448
  }
29085
- async getWikiBlame(orgId, wikiId, path8, ref) {
29086
- return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path8, ref });
28449
+ async getWikiBlame(orgId, wikiId, path9, ref) {
28450
+ return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path9, ref });
29087
28451
  }
29088
28452
  // ---- Wiki Operations (audit log) ----
29089
28453
  async getWikiOperations(orgId, wikiId, params) {
@@ -29281,858 +28645,1624 @@ var ParallClient = class _ParallClient {
29281
28645
  const resp = await this.request("GET", ENDPOINTS.CLIP_ONLINE(orgId));
29282
28646
  return resp.data;
29283
28647
  }
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));
28648
+ /** Deployment-wide hosted browser runtime availability — drives whether the
28649
+ * create UI offers the platform-hosted placement. Fail-closed server-side. */
28650
+ async getBrowserRuntimeStatus(orgId) {
28651
+ return this.request("GET", ENDPOINTS.BROWSER_RUNTIME_STATUS(orgId));
28652
+ }
28653
+ /** Org-wide browser-profile discovery list. Returns the sanitized
28654
+ * {@link BrowserProfileListItem} shape (not the full domain model), each row
28655
+ * carrying a per-viewer `can_open` control hint. */
28656
+ async listBrowserProfiles(orgId) {
28657
+ const resp = await this.request("GET", ENDPOINTS.BROWSER_PROFILES(orgId));
28658
+ return resp.data;
28659
+ }
28660
+ async createBrowserProfile(orgId, req) {
28661
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILES(orgId), req);
28662
+ }
28663
+ async getBrowserProfile(orgId, profileId) {
28664
+ return this.request("GET", ENDPOINTS.BROWSER_PROFILE(orgId, profileId));
28665
+ }
28666
+ async updateBrowserProfile(orgId, profileId, req) {
28667
+ return this.request("PATCH", ENDPOINTS.BROWSER_PROFILE(orgId, profileId), req);
28668
+ }
28669
+ async deleteBrowserProfile(orgId, profileId) {
28670
+ await this.request("DELETE", ENDPOINTS.BROWSER_PROFILE(orgId, profileId));
28671
+ }
28672
+ async openBrowserProfile(orgId, profileId, req = {}) {
28673
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILE_OPEN(orgId, profileId), req);
28674
+ }
28675
+ async stopBrowserProfile(orgId, profileId) {
28676
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILE_STOP(orgId, profileId), {});
28677
+ }
28678
+ async resetBrowserProfile(orgId, profileId) {
28679
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILE_RESET(orgId, profileId));
28680
+ }
28681
+ async listBrowserProfileConsents(orgId, profileId) {
28682
+ const resp = await this.request("GET", ENDPOINTS.BROWSER_PROFILE_CONSENTS(orgId, profileId));
28683
+ return resp.data;
28684
+ }
28685
+ async grantBrowserProfileConsent(orgId, profileId, req) {
28686
+ return this.request("POST", ENDPOINTS.BROWSER_PROFILE_CONSENTS(orgId, profileId), req);
28687
+ }
28688
+ async revokeBrowserProfileConsent(orgId, profileId, clipId) {
28689
+ await this.request("DELETE", ENDPOINTS.BROWSER_PROFILE_CONSENT(orgId, profileId, clipId));
28690
+ }
28691
+ async listRegistryClips(q) {
28692
+ const url = ENDPOINTS.CLIP_REGISTRY() + (q ? `?q=${encodeURIComponent(q)}` : "");
28693
+ const resp = await this.request("GET", url);
28694
+ return resp.data;
28695
+ }
28696
+ // ---- Edge devices ----
28697
+ async listEdgeDevices(orgId) {
28698
+ return this.request("GET", ENDPOINTS.ORG_EDGE_DEVICES(orgId));
28699
+ }
28700
+ async getEdgeOnboarding(orgId) {
28701
+ return this.request("GET", ENDPOINTS.ORG_EDGE_ONBOARDING(orgId));
28702
+ }
28703
+ async listEdgeProfiles(orgId, edgeId) {
28704
+ return this.request("GET", ENDPOINTS.ORG_EDGE_PROFILES(orgId, edgeId));
28705
+ }
28706
+ // ---- Clip connections ----
28707
+ async listClipConnections(orgId, clipId) {
28708
+ return this.request("GET", ENDPOINTS.CLIP_CONNECTIONS(orgId, clipId));
28709
+ }
28710
+ async createClipConnection(orgId, clipId, input) {
28711
+ return this.request("POST", ENDPOINTS.CLIP_CONNECTIONS(orgId, clipId), input);
28712
+ }
28713
+ async deleteClipConnection(orgId, connId) {
28714
+ return this.request("DELETE", ENDPOINTS.CLIP_CONNECTION(orgId, connId));
28715
+ }
28716
+ };
28717
+ function normalizeWikiChangeset(changeset) {
28718
+ return {
28719
+ ...changeset,
28720
+ changed_paths: changeset.changed_paths ?? [],
28721
+ file_changes: changeset.file_changes ?? []
28722
+ };
28723
+ }
28724
+ var ApiError = class extends Error {
28725
+ status;
28726
+ code;
28727
+ extras;
28728
+ /** Attempted action (authorization denials) — e.g. "chat.add_member". */
28729
+ action;
28730
+ /** Target resource URI that was evaluated — e.g. "prll://cht_…". */
28731
+ resourceUri;
28732
+ /** Whether the action is approval-executable (PERMISSION_DENIED only). */
28733
+ approvable;
28734
+ constructor(status, message, code) {
28735
+ super(message);
28736
+ this.status = status;
28737
+ this.code = code;
28738
+ this.name = "ApiError";
28739
+ }
28740
+ };
28741
+ function buildApiError(res, rawErrorBody) {
28742
+ const errorBody = rawErrorBody !== null && typeof rawErrorBody === "object" ? rawErrorBody : {};
28743
+ const errorObj = errorBody.error && typeof errorBody.error === "object" ? errorBody.error : void 0;
28744
+ 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);
28745
+ const errCode = (typeof errorObj?.code === "string" ? errorObj.code : void 0) ?? (typeof errorBody.code === "string" ? errorBody.code : void 0);
28746
+ const apiError = new ApiError(res.status, errMsg ?? res.statusText, errCode);
28747
+ const anchors = errorObj ?? errorBody;
28748
+ if (typeof anchors.action === "string")
28749
+ apiError.action = anchors.action;
28750
+ if (typeof anchors.resource_uri === "string")
28751
+ apiError.resourceUri = anchors.resource_uri;
28752
+ if (typeof anchors.approvable === "boolean")
28753
+ apiError.approvable = anchors.approvable;
28754
+ const structural = /* @__PURE__ */ new Set(["error", "code", "message", "status"]);
28755
+ const extras = {};
28756
+ for (const [k, v] of Object.entries(errorBody))
28757
+ if (!structural.has(k))
28758
+ extras[k] = v;
28759
+ if (errorObj) {
28760
+ for (const [k, v] of Object.entries(errorObj))
28761
+ if (!structural.has(k))
28762
+ extras[k] = v;
28763
+ }
28764
+ if (Object.keys(extras).length > 0)
28765
+ apiError.extras = extras;
28766
+ return apiError;
28767
+ }
28768
+
28769
+ // ../sdk/dist/ws.js
28770
+ function isRetryableNetworkError(err) {
28771
+ return err instanceof Error && err.name === "ApiError" && "status" in err && err.status === 0;
28772
+ }
28773
+ function isBrowserRuntime() {
28774
+ return typeof window !== "undefined";
28775
+ }
28776
+ var ParallWs = class {
28777
+ ws = null;
28778
+ options;
28779
+ listeners = /* @__PURE__ */ new Map();
28780
+ stateListeners = /* @__PURE__ */ new Set();
28781
+ heartbeatTimer = null;
28782
+ reconnectTimer = null;
28783
+ reconnectAttempts = 0;
28784
+ lastSeq = 0;
28785
+ _state = "disconnected";
28786
+ intentionalClose = false;
28787
+ lastReceivedAt = 0;
28788
+ heartbeatIntervalMs = 0;
28789
+ probeTimer = null;
28790
+ browserListenersActive = false;
28791
+ constructor(options) {
28792
+ this.options = {
28793
+ reconnect: true,
28794
+ reconnectInterval: 1e3,
28795
+ maxReconnectInterval: 3e4,
28796
+ ...options
28797
+ };
28798
+ this.lastSeq = options.lastSeq ?? 0;
28799
+ }
28800
+ get state() {
28801
+ return this._state;
28802
+ }
28803
+ async connect() {
28804
+ this.intentionalClose = false;
28805
+ this.setupBrowserListeners();
28806
+ this.setState("connecting");
28807
+ let ticket;
28808
+ try {
28809
+ ticket = await this.options.getTicket();
28810
+ } catch (err) {
28811
+ if (isBrowserRuntime() && isRetryableNetworkError(err)) {
28812
+ console.warn("Failed to get WS ticket:", err);
28813
+ } else {
28814
+ console.error("Failed to get WS ticket:", err);
28815
+ }
28816
+ if (this.options.reconnect) {
28817
+ this.scheduleReconnect();
28818
+ } else {
28819
+ this.setState("disconnected");
28820
+ }
28821
+ return;
28822
+ }
28823
+ const wsUrl = ticket.ws_url || this.options.wsUrl;
28824
+ if (!wsUrl) {
28825
+ console.error("No WS URL available");
28826
+ this.setState("disconnected");
28827
+ return;
28828
+ }
28829
+ const url = new URL(wsUrl);
28830
+ url.searchParams.set("ticket", ticket.ticket);
28831
+ if (this.lastSeq > 0) {
28832
+ url.searchParams.set("last_seq", String(this.lastSeq));
28833
+ }
28834
+ this.ws = new WebSocket(url.toString());
28835
+ const ws = this.ws;
28836
+ const connectTimeout = setTimeout(() => {
28837
+ if (this._state === "connected" || this.intentionalClose)
28838
+ return;
28839
+ ws.onclose = null;
28840
+ ws.onopen = null;
28841
+ ws.onerror = null;
28842
+ try {
28843
+ ws.close();
28844
+ } catch {
28845
+ }
28846
+ if (ws !== this.ws)
28847
+ return;
28848
+ if (this.options.reconnect) {
28849
+ this.scheduleReconnect();
28850
+ } else {
28851
+ this.setState("disconnected");
28852
+ }
28853
+ }, 15e3);
28854
+ this.ws.onopen = () => {
28855
+ clearTimeout(connectTimeout);
28856
+ this.reconnectAttempts = 0;
28857
+ this.lastReceivedAt = Date.now();
28858
+ this.setState("connected");
28859
+ };
28860
+ this.ws.onmessage = (event) => {
28861
+ try {
28862
+ const frame = JSON.parse(event.data);
28863
+ this.handleFrame(frame);
28864
+ } catch {
28865
+ }
28866
+ };
28867
+ this.ws.onclose = () => {
28868
+ clearTimeout(connectTimeout);
28869
+ this.stopHeartbeat();
28870
+ this.clearProbe();
28871
+ if (this.intentionalClose) {
28872
+ this.setState("disconnected");
28873
+ return;
28874
+ }
28875
+ if (this.options.reconnect) {
28876
+ this.scheduleReconnect();
28877
+ } else {
28878
+ this.setState("disconnected");
28879
+ }
28880
+ };
28881
+ this.ws.onerror = () => {
28882
+ };
28883
+ }
28884
+ disconnect() {
28885
+ this.intentionalClose = true;
28886
+ this.stopHeartbeat();
28887
+ this.clearReconnect();
28888
+ this.clearProbe();
28889
+ this.teardownBrowserListeners();
28890
+ if (this.ws) {
28891
+ this.ws.close();
28892
+ this.ws = null;
28893
+ }
28894
+ this.setState("disconnected");
29288
28895
  }
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;
28896
+ // ---- Client -> Server messages ----
28897
+ /** Tell the server which chats the user is currently viewing (no auth implications). */
28898
+ watch(chatIds) {
28899
+ this.send({ type: WS_EVENTS.WATCH, data: { chat_ids: chatIds } });
29295
28900
  }
29296
- async createBrowserProfile(orgId, req) {
29297
- return this.request("POST", ENDPOINTS.BROWSER_PROFILES(orgId), req);
28901
+ sendTyping(chatId, action, threadRootId) {
28902
+ this.send({
28903
+ type: WS_EVENTS.TYPING,
28904
+ data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
28905
+ });
29298
28906
  }
29299
- async getBrowserProfile(orgId, profileId) {
29300
- return this.request("GET", ENDPOINTS.BROWSER_PROFILE(orgId, profileId));
28907
+ /** Send an agent heartbeat with telemetry data. */
28908
+ sendAgentHeartbeat(sessionId, telemetry) {
28909
+ this.send({
28910
+ type: WS_EVENTS.AGENT_HEARTBEAT,
28911
+ data: { session_id: sessionId, telemetry }
28912
+ });
29301
28913
  }
29302
- async updateBrowserProfile(orgId, profileId, req) {
29303
- return this.request("PATCH", ENDPOINTS.BROWSER_PROFILE(orgId, profileId), req);
28914
+ sendEvent(type, data) {
28915
+ this.send({ type, data });
29304
28916
  }
29305
- async deleteBrowserProfile(orgId, profileId) {
29306
- await this.request("DELETE", ENDPOINTS.BROWSER_PROFILE(orgId, profileId));
28917
+ // ---- Event listeners ----
28918
+ on(event, handler) {
28919
+ let set = this.listeners.get(event);
28920
+ if (!set) {
28921
+ set = /* @__PURE__ */ new Set();
28922
+ this.listeners.set(event, set);
28923
+ }
28924
+ set.add(handler);
28925
+ return () => {
28926
+ set.delete(handler);
28927
+ };
29307
28928
  }
29308
- async openBrowserProfile(orgId, profileId, req = {}) {
29309
- return this.request("POST", ENDPOINTS.BROWSER_PROFILE_OPEN(orgId, profileId), req);
28929
+ off(event, handler) {
28930
+ this.listeners.get(event)?.delete(handler);
29310
28931
  }
29311
- async stopBrowserProfile(orgId, profileId) {
29312
- return this.request("POST", ENDPOINTS.BROWSER_PROFILE_STOP(orgId, profileId), {});
28932
+ onStateChange(handler) {
28933
+ this.stateListeners.add(handler);
28934
+ return () => {
28935
+ this.stateListeners.delete(handler);
28936
+ };
29313
28937
  }
29314
- async resetBrowserProfile(orgId, profileId) {
29315
- return this.request("POST", ENDPOINTS.BROWSER_PROFILE_RESET(orgId, profileId));
28938
+ // ---- Internal ----
28939
+ send(frame) {
28940
+ if (this.ws?.readyState === WebSocket.OPEN) {
28941
+ this.ws.send(JSON.stringify(frame));
28942
+ }
29316
28943
  }
29317
- async listBrowserProfileConsents(orgId, profileId) {
29318
- const resp = await this.request("GET", ENDPOINTS.BROWSER_PROFILE_CONSENTS(orgId, profileId));
29319
- return resp.data;
28944
+ handleFrame(frame) {
28945
+ this.lastReceivedAt = Date.now();
28946
+ this.clearProbe();
28947
+ if (frame.seq !== void 0) {
28948
+ this.lastSeq = frame.seq;
28949
+ }
28950
+ if (frame.type === WS_EVENTS.HELLO) {
28951
+ const interval = frame.data.heartbeat_interval;
28952
+ this.startHeartbeat(interval);
28953
+ }
28954
+ const handlers = this.listeners.get(frame.type);
28955
+ if (handlers) {
28956
+ for (const handler of handlers) {
28957
+ handler(frame.data, frame.seq);
28958
+ }
28959
+ }
29320
28960
  }
29321
- async grantBrowserProfileConsent(orgId, profileId, req) {
29322
- return this.request("POST", ENDPOINTS.BROWSER_PROFILE_CONSENTS(orgId, profileId), req);
28961
+ startHeartbeat(intervalSec) {
28962
+ this.stopHeartbeat();
28963
+ if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
28964
+ console.error("Invalid heartbeat interval from server:", intervalSec);
28965
+ return;
28966
+ }
28967
+ this.heartbeatIntervalMs = intervalSec * 1e3;
28968
+ this.heartbeatTimer = setInterval(() => {
28969
+ if (this.lastReceivedAt > 0 && Date.now() - this.lastReceivedAt > this.heartbeatIntervalMs * 1.5) {
28970
+ this.probeConnection();
28971
+ return;
28972
+ }
28973
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
28974
+ }, intervalSec * 1e3);
29323
28975
  }
29324
- async revokeBrowserProfileConsent(orgId, profileId, clipId) {
29325
- await this.request("DELETE", ENDPOINTS.BROWSER_PROFILE_CONSENT(orgId, profileId, clipId));
28976
+ stopHeartbeat() {
28977
+ if (this.heartbeatTimer) {
28978
+ clearInterval(this.heartbeatTimer);
28979
+ this.heartbeatTimer = null;
28980
+ }
29326
28981
  }
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;
28982
+ scheduleReconnect() {
28983
+ this.setState("reconnecting");
28984
+ this.clearReconnect();
28985
+ const base = Math.min(this.options.reconnectInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
28986
+ const delay = base * (0.5 + Math.random() * 0.5);
28987
+ this.reconnectAttempts++;
28988
+ this.reconnectTimer = setTimeout(() => {
28989
+ this.connect();
28990
+ }, delay);
29331
28991
  }
29332
- // ---- Edge devices ----
29333
- async listEdgeDevices(orgId) {
29334
- return this.request("GET", ENDPOINTS.ORG_EDGE_DEVICES(orgId));
28992
+ clearReconnect() {
28993
+ if (this.reconnectTimer) {
28994
+ clearTimeout(this.reconnectTimer);
28995
+ this.reconnectTimer = null;
28996
+ }
29335
28997
  }
29336
- async getEdgeOnboarding(orgId) {
29337
- return this.request("GET", ENDPOINTS.ORG_EDGE_ONBOARDING(orgId));
28998
+ /** Force-close a dead/stale connection and trigger reconnect. */
28999
+ forceReconnect() {
29000
+ this.stopHeartbeat();
29001
+ this.clearReconnect();
29002
+ this.clearProbe();
29003
+ if (this.ws) {
29004
+ this.ws.onclose = null;
29005
+ this.ws.onopen = null;
29006
+ this.ws.onerror = null;
29007
+ this.ws.onmessage = null;
29008
+ try {
29009
+ this.ws.close();
29010
+ } catch {
29011
+ }
29012
+ this.ws = null;
29013
+ }
29014
+ if (this.options.reconnect && !this.intentionalClose) {
29015
+ this.scheduleReconnect();
29016
+ } else {
29017
+ this.setState("disconnected");
29018
+ }
29338
29019
  }
29339
- async listEdgeProfiles(orgId, edgeId) {
29340
- return this.request("GET", ENDPOINTS.ORG_EDGE_PROFILES(orgId, edgeId));
29020
+ // ---- Browser event listeners for proactive reconnection ----
29021
+ setupBrowserListeners() {
29022
+ if (this.browserListenersActive)
29023
+ return;
29024
+ this.browserListenersActive = true;
29025
+ if (typeof document !== "undefined") {
29026
+ document.addEventListener("visibilitychange", this.handleVisibilityChange);
29027
+ }
29028
+ if (typeof window !== "undefined") {
29029
+ window.addEventListener("online", this.handleOnline);
29030
+ }
29341
29031
  }
29342
- // ---- Clip connections ----
29343
- async listClipConnections(orgId, clipId) {
29344
- return this.request("GET", ENDPOINTS.CLIP_CONNECTIONS(orgId, clipId));
29032
+ teardownBrowserListeners() {
29033
+ if (!this.browserListenersActive)
29034
+ return;
29035
+ this.browserListenersActive = false;
29036
+ if (typeof document !== "undefined") {
29037
+ document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29038
+ }
29039
+ if (typeof window !== "undefined") {
29040
+ window.removeEventListener("online", this.handleOnline);
29041
+ }
29345
29042
  }
29346
- async createClipConnection(orgId, clipId, input) {
29347
- return this.request("POST", ENDPOINTS.CLIP_CONNECTIONS(orgId, clipId), input);
29043
+ /**
29044
+ * Send a ping and arm a short timeout. If no frame arrives within 5s the
29045
+ * connection is assumed dead and force-reconnected. Any received frame
29046
+ * (including the pong) cancels the timer via clearProbe() in handleFrame.
29047
+ */
29048
+ probeConnection() {
29049
+ if (this.probeTimer)
29050
+ return;
29051
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29052
+ this.probeTimer = setTimeout(() => {
29053
+ this.forceReconnect();
29054
+ }, 5e3);
29348
29055
  }
29349
- async deleteClipConnection(orgId, connId) {
29350
- return this.request("DELETE", ENDPOINTS.CLIP_CONNECTION(orgId, connId));
29056
+ clearProbe() {
29057
+ if (this.probeTimer) {
29058
+ clearTimeout(this.probeTimer);
29059
+ this.probeTimer = null;
29060
+ }
29351
29061
  }
29352
- };
29353
- function normalizeWikiChangeset(changeset) {
29354
- return {
29355
- ...changeset,
29356
- changed_paths: changeset.changed_paths ?? [],
29357
- file_changes: changeset.file_changes ?? []
29062
+ /** Tab returned to foreground — verify connection or accelerate reconnect. */
29063
+ handleVisibilityChange = () => {
29064
+ if (typeof document !== "undefined" && document.hidden)
29065
+ return;
29066
+ if (this._state === "connected") {
29067
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29068
+ this.forceReconnect();
29069
+ } else {
29070
+ this.probeConnection();
29071
+ }
29072
+ } else if (this._state === "reconnecting") {
29073
+ this.clearReconnect();
29074
+ this.reconnectAttempts = 0;
29075
+ this.connect();
29076
+ }
29358
29077
  };
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";
29078
+ /** Network restored — accelerate reconnection. */
29079
+ handleOnline = () => {
29080
+ if (this.intentionalClose)
29081
+ return;
29082
+ if (this._state === "connected") {
29083
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29084
+ this.forceReconnect();
29085
+ } else {
29086
+ this.probeConnection();
29087
+ }
29088
+ } else if (this._state === "reconnecting") {
29089
+ this.clearReconnect();
29090
+ this.reconnectAttempts = 0;
29091
+ this.connect();
29092
+ }
29093
+ };
29094
+ setState(state) {
29095
+ this._state = state;
29096
+ for (const listener of this.stateListeners) {
29097
+ listener(state);
29098
+ }
29375
29099
  }
29376
29100
  };
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
29101
 
29405
- // ../sdk/dist/ws.js
29406
- function isRetryableNetworkError(err) {
29407
- return err instanceof Error && err.name === "ApiError" && "status" in err && err.status === 0;
29102
+ // ../agent-core/dist/lane-ledger.js
29103
+ var LedgerUnsupportedError = class extends Error {
29104
+ };
29105
+ function isStaleLane(err) {
29106
+ return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
29408
29107
  }
29409
- function isBrowserRuntime() {
29410
- return typeof window !== "undefined";
29108
+ function isEndpointMissing(err) {
29109
+ return err instanceof ApiError && err.status === 404 && !err.code;
29411
29110
  }
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;
29111
+ var LaneLedger = class {
29112
+ opts;
29113
+ lanes = /* @__PURE__ */ new Map();
29114
+ constructor(opts) {
29115
+ this.opts = opts;
29435
29116
  }
29436
- get state() {
29437
- return this._state;
29117
+ get contextDir() {
29118
+ return this.opts.contextDir;
29438
29119
  }
29439
- async connect() {
29440
- this.intentionalClose = false;
29441
- this.setupBrowserListeners();
29442
- this.setState("connecting");
29443
- let ticket;
29444
- try {
29445
- ticket = await this.options.getTicket();
29446
- } 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);
29120
+ /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
29121
+ handles(event) {
29122
+ return event.type === "message" && event.targetId.startsWith("cht_");
29123
+ }
29124
+ laneKeyFor(event) {
29125
+ if (event.type !== "message" && event.dispatchEventId) {
29126
+ return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29127
+ }
29128
+ return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29129
+ }
29130
+ getForEvent(event) {
29131
+ return this.lanes.get(this.laneKeyFor(event));
29132
+ }
29133
+ laneContextPath(lane) {
29134
+ return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29135
+ }
29136
+ /**
29137
+ * Claim (or reuse) the lane for a group of same-lane message events and
29138
+ * fold every group member into it. Returns 'foreign' when a healthy
29139
+ * incumbent (another pod) holds the resource — the caller must not
29140
+ * dispatch; the events stay pending server-side and re-drive after the
29141
+ * incumbent completes.
29142
+ */
29143
+ async ensureLane(events) {
29144
+ const trigger = events[events.length - 1];
29145
+ const laneKey = this.laneKeyFor(trigger);
29146
+ let lane = this.lanes.get(laneKey);
29147
+ if (!lane) {
29148
+ const targetUri = `prll://${trigger.targetId}`;
29149
+ let res;
29150
+ try {
29151
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29152
+ target_uri: targetUri,
29153
+ thread_root_id: trigger.threadRootId,
29154
+ limit: 100
29155
+ });
29156
+ } catch (err) {
29157
+ if (isEndpointMissing(err))
29158
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29159
+ throw err;
29451
29160
  }
29452
- if (this.options.reconnect) {
29453
- this.scheduleReconnect();
29454
- } else {
29455
- this.setState("disconnected");
29161
+ if (!res.claimed || !res.lane) {
29162
+ if (res.reason === "empty") {
29163
+ this.opts.log?.warn(`claim for ${targetUri} came back empty \u2014 nothing foldable; leaving to the reconciler`);
29164
+ } else {
29165
+ this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
29166
+ }
29167
+ return null;
29456
29168
  }
29457
- return;
29458
- }
29459
- const wsUrl = ticket.ws_url || this.options.wsUrl;
29460
- if (!wsUrl) {
29461
- console.error("No WS URL available");
29462
- this.setState("disconnected");
29463
- 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));
29169
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29170
+ lane = {
29171
+ laneKey,
29172
+ lane: res.lane,
29173
+ targetUri,
29174
+ threadRootId: trigger.threadRootId,
29175
+ folded: /* @__PURE__ */ new Map(),
29176
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29177
+ };
29178
+ for (const ev of res.events ?? []) {
29179
+ lane.folded.set(ev.source_id, ev.id);
29180
+ }
29181
+ this.lanes.set(laneKey, lane);
29469
29182
  }
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;
29183
+ for (const ev of events) {
29184
+ if (lane.folded.has(ev.messageId))
29185
+ continue;
29478
29186
  try {
29479
- ws.close();
29480
- } catch {
29187
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29188
+ lane: lane.lane,
29189
+ target_uri: lane.targetUri,
29190
+ thread_root_id: lane.threadRootId,
29191
+ ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
29192
+ });
29193
+ lane.folded.set(ev.messageId, res.dispatch_event_id);
29194
+ } catch (err) {
29195
+ if (isStaleLane(err)) {
29196
+ this.lanes.delete(laneKey);
29197
+ return null;
29198
+ }
29199
+ this.opts.log?.warn(`steer fold failed for ${ev.messageId} \u2014 failing closed, releasing lane: ${String(err)}`);
29200
+ await this.release(laneKey);
29201
+ return null;
29481
29202
  }
29482
- if (ws !== this.ws)
29483
- return;
29484
- if (this.options.reconnect) {
29485
- this.scheduleReconnect();
29203
+ }
29204
+ return lane;
29205
+ }
29206
+ /**
29207
+ * Fold a live mid-turn message into its active lane BEFORE injecting it
29208
+ * into the running turn. Injection without a successful fold is forbidden —
29209
+ * an un-folded injected message would be re-driven after complete and the
29210
+ * model would handle it twice.
29211
+ */
29212
+ async steerLive(event) {
29213
+ const laneKey = this.laneKeyFor(event);
29214
+ const lane = this.lanes.get(laneKey);
29215
+ if (!lane)
29216
+ return false;
29217
+ if (lane.folded.has(event.messageId))
29218
+ return true;
29219
+ try {
29220
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29221
+ lane: lane.lane,
29222
+ target_uri: lane.targetUri,
29223
+ thread_root_id: lane.threadRootId,
29224
+ ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
29225
+ });
29226
+ lane.folded.set(event.messageId, res.dispatch_event_id);
29227
+ return true;
29228
+ } catch (err) {
29229
+ if (isStaleLane(err)) {
29230
+ this.lanes.delete(laneKey);
29486
29231
  } else {
29487
- this.setState("disconnected");
29232
+ this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
29488
29233
  }
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 {
29234
+ return false;
29235
+ }
29236
+ }
29237
+ /**
29238
+ * Complete the lane when no local work remains for it: the server sweeps
29239
+ * still-leased members as no_action, releases the occupancy row, and
29240
+ * re-drives any same-target pending work. A STALE_LANE answer means a
29241
+ * takeover already owns the resource — local state is dropped either way.
29242
+ */
29243
+ /**
29244
+ * Record that the turn on this lane surfaced a runtime error. The flow
29245
+ * settles an errored lane immediately (dispatchLaneGroup returns 'failed'
29246
+ * after a forced complete), so the bit normally lives for one turn only —
29247
+ * it is the transport between the gateway's per-session error signal and
29248
+ * this lane's complete request.
29249
+ */
29250
+ markTurnError(laneKey) {
29251
+ const lane = this.lanes.get(laneKey);
29252
+ if (lane)
29253
+ lane.turnError = true;
29254
+ }
29255
+ async completeIfIdle(laneKey, hasMoreLocal) {
29256
+ const lane = this.lanes.get(laneKey);
29257
+ if (!lane || hasMoreLocal)
29258
+ return;
29259
+ this.lanes.delete(laneKey);
29260
+ this.removeLaneContext(lane);
29261
+ try {
29262
+ const res = await this.opts.client.completeDispatch(this.opts.orgId, {
29263
+ lane: lane.lane,
29264
+ target_uri: lane.targetUri,
29265
+ thread_root_id: lane.threadRootId,
29266
+ // An error turn releases its members for retry instead of sweeping
29267
+ // them as handled (ignored by older servers).
29268
+ turn_outcome: lane.turnError ? "error" : "ok"
29269
+ });
29270
+ if (res.swept_no_action > 0 || res.redriven) {
29271
+ this.opts.log?.info(`lane complete for ${lane.targetUri}: swept ${res.swept_no_action} no_action, redriven=${res.redriven}`);
29501
29272
  }
29502
- };
29503
- this.ws.onclose = () => {
29504
- clearTimeout(connectTimeout);
29505
- this.stopHeartbeat();
29506
- this.clearProbe();
29507
- if (this.intentionalClose) {
29508
- this.setState("disconnected");
29273
+ } catch (err) {
29274
+ if (isStaleLane(err)) {
29275
+ this.opts.log?.info(`lane complete skipped for ${lane.targetUri} \u2014 taken over`);
29509
29276
  return;
29510
29277
  }
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;
29278
+ this.opts.log?.warn(`lane complete failed for ${lane.targetUri}: ${String(err)}`);
29529
29279
  }
29530
- this.setState("disconnected");
29531
29280
  }
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 } });
29281
+ /**
29282
+ * Renew one lane by its key the external runtime-activity hook for
29283
+ * adapters whose tool traffic bypasses the RuntimeEvent stream (openclaw
29284
+ * hooks). Scoped to the session's own lane: renewing every lane would let
29285
+ * one busy fork keep an unrelated stalled fork's lane leased forever.
29286
+ */
29287
+ renewByKey(laneKey) {
29288
+ const lane = this.lanes.get(laneKey);
29289
+ if (lane)
29290
+ this.maybeRenew(lane);
29536
29291
  }
29537
- sendTyping(chatId, action, threadRootId) {
29538
- this.send({
29539
- type: WS_EVENTS.TYPING,
29540
- data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
29292
+ /**
29293
+ * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
29294
+ * so a chatty turn doesn't spam the server. Without this, a legitimately
29295
+ * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
29296
+ * write misfired with STALE_LANE — the design doc's "long turns renew via
29297
+ * step writes". Fire-and-forget: a failed renewal is surfaced by the next
29298
+ * write's incumbency check anyway.
29299
+ */
29300
+ maybeRenew(lane) {
29301
+ const now = Date.now();
29302
+ const ttl = lane.leaseTtlMs ?? 10 * 6e4;
29303
+ const until = lane.leaseUntilMs ?? now;
29304
+ if (until - now > ttl / 2)
29305
+ return;
29306
+ lane.leaseUntilMs = now + ttl;
29307
+ void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
29308
+ lane: lane.lane,
29309
+ target_uri: lane.targetUri,
29310
+ thread_root_id: lane.threadRootId
29311
+ }).then((res) => {
29312
+ const until2 = Date.parse(res?.lease_until ?? "");
29313
+ if (!Number.isNaN(until2))
29314
+ lane.leaseUntilMs = until2;
29315
+ }).catch((err) => {
29316
+ if (isStaleLane(err)) {
29317
+ this.lanes.delete(lane.laneKey);
29318
+ this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
29319
+ return;
29320
+ }
29321
+ this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
29541
29322
  });
29542
29323
  }
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 }
29548
- });
29324
+ /**
29325
+ * Release a lane's unresolved members back to pending (dispatch error /
29326
+ * shutdown) so the next pod re-claims immediately instead of waiting out
29327
+ * the lease.
29328
+ */
29329
+ async release(laneKey) {
29330
+ const lane = this.lanes.get(laneKey);
29331
+ if (!lane)
29332
+ return;
29333
+ this.lanes.delete(laneKey);
29334
+ this.removeLaneContext(lane);
29335
+ try {
29336
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane);
29337
+ } catch (err) {
29338
+ this.opts.log?.warn(`lane release failed for ${lane.targetUri}: ${String(err)}`);
29339
+ }
29549
29340
  }
29550
- sendEvent(type, data) {
29551
- this.send({ type, data });
29341
+ async releaseAll() {
29342
+ const keys = [...this.lanes.keys()];
29343
+ for (const key of keys) {
29344
+ await this.release(key);
29345
+ }
29552
29346
  }
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);
29347
+ /** True when any lane is currently active (used by shutdown logging). */
29348
+ get activeCount() {
29349
+ return this.lanes.size;
29350
+ }
29351
+ /**
29352
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
29353
+ * by WorkItem id or by source identity (the live task.assigned event has no
29354
+ * WorkItem id). Returns null when a healthy incumbent (another pod) holds
29355
+ * it or the WorkItem is already resolved — the caller must skip processing.
29356
+ */
29357
+ async claimTyped(ref) {
29358
+ let res;
29359
+ try {
29360
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29361
+ dispatch_event_id: ref.dispatchEventId,
29362
+ source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
29363
+ source_id: ref.dispatchEventId ? void 0 : ref.sourceId
29364
+ });
29365
+ } catch (err) {
29366
+ if (isEndpointMissing(err))
29367
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29368
+ throw err;
29559
29369
  }
29560
- set.add(handler);
29561
- return () => {
29562
- set.delete(handler);
29370
+ if (!res.claimed || !res.lane || !res.events?.length)
29371
+ return null;
29372
+ const workItem = res.events[0];
29373
+ const targetUri = `dsp:${workItem.id}`;
29374
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29375
+ const lane = {
29376
+ laneKey: laneKeyForTarget(targetUri),
29377
+ lane: res.lane,
29378
+ targetUri,
29379
+ folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
29380
+ typedDispatchEventId: workItem.id,
29381
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29563
29382
  };
29383
+ this.lanes.set(lane.laneKey, lane);
29384
+ return lane;
29564
29385
  }
29565
- off(event, handler) {
29566
- this.listeners.get(event)?.delete(handler);
29386
+ /**
29387
+ * Remove the per-lane context file (and its CLI sidecar) when the lane
29388
+ * ends. A leftover file would make a later cross-context send to the same
29389
+ * target bind a dead lane token and misfire with STALE_LANE instead of
29390
+ * taking the plain non-ledger path.
29391
+ */
29392
+ removeLaneContext(lane) {
29393
+ const contextPath = this.laneContextPath(lane);
29394
+ for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
29395
+ try {
29396
+ fs.rmSync(p, { force: true });
29397
+ } catch {
29398
+ }
29399
+ }
29567
29400
  }
29568
- onStateChange(handler) {
29569
- this.stateListeners.add(handler);
29570
- return () => {
29571
- this.stateListeners.delete(handler);
29572
- };
29401
+ };
29402
+
29403
+ // ../agent-core/dist/gateway-lane-flow.js
29404
+ async function dispatchLaneGroup(host, opts) {
29405
+ const ledger = host.laneLedger;
29406
+ const event = opts.events[opts.events.length - 1];
29407
+ let lane;
29408
+ try {
29409
+ lane = await ledger.ensureLane(opts.events);
29410
+ } catch (err) {
29411
+ if (!(err instanceof LedgerUnsupportedError))
29412
+ throw err;
29413
+ host.disableLedger("claim endpoint missing");
29414
+ await host.emitDispatchReceived(event);
29415
+ const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29416
+ if (!dispatched2)
29417
+ return "shutdown";
29418
+ for (const ev of opts.events) {
29419
+ host.opts.client.ackDispatch(host.opts.config.org_id, {
29420
+ source_type: ev.ackSourceType ?? "message",
29421
+ source_id: ev.ackSourceId ?? ev.messageId
29422
+ }).catch(() => {
29423
+ });
29424
+ }
29425
+ return "dispatched";
29573
29426
  }
29574
- // ---- Internal ----
29575
- send(frame) {
29576
- if (this.ws?.readyState === WebSocket.OPEN) {
29577
- this.ws.send(JSON.stringify(frame));
29427
+ if (!lane) {
29428
+ for (const ev of opts.events) {
29429
+ host.dispatchedMessages.delete(ev.messageId);
29578
29430
  }
29431
+ return "foreign";
29432
+ }
29433
+ host.noteSessionLane(opts.sessionKey, lane.laneKey);
29434
+ let dispatched = false;
29435
+ try {
29436
+ dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29437
+ } catch (err) {
29438
+ host.noteSessionLane(opts.sessionKey, null);
29439
+ await ledger.release(lane.laneKey).catch(() => {
29440
+ });
29441
+ throw err;
29442
+ } finally {
29443
+ if (dispatched)
29444
+ host.noteSessionLane(opts.sessionKey, null);
29445
+ }
29446
+ if (!dispatched) {
29447
+ return "shutdown";
29579
29448
  }
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);
29449
+ if (host.consumeTurnError(opts.sessionKey)) {
29450
+ ledger.markTurnError(lane.laneKey);
29451
+ for (const msgId of lane.folded.keys()) {
29452
+ host.dispatchedMessages.delete(msgId);
29589
29453
  }
29590
- const handlers = this.listeners.get(frame.type);
29591
- if (handlers) {
29592
- for (const handler of handlers) {
29593
- handler(frame.data, frame.seq);
29594
- }
29454
+ try {
29455
+ host.opts.dispatchAdapter.abortDispatch?.(opts.sessionKey);
29456
+ } catch {
29595
29457
  }
29458
+ await ledger.completeIfIdle(lane.laneKey, false);
29459
+ return "failed";
29596
29460
  }
29597
- startHeartbeat(intervalSec) {
29598
- this.stopHeartbeat();
29599
- if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
29600
- console.error("Invalid heartbeat interval from server:", intervalSec);
29601
- return;
29461
+ const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
29462
+ await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
29463
+ return "dispatched";
29464
+ }
29465
+ var TYPED_BACKOFF_BASE_MS = 2e3;
29466
+ var TYPED_BACKOFF_CAP_MS = 5 * 6e4;
29467
+ var TYPED_BACKOFF_MAP_CAP = 512;
29468
+ async function consumeTypedDispatch(host, ref, run, ack) {
29469
+ const backoffKey = ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`;
29470
+ const armed = host.typedRedriveBackoff.get(backoffKey);
29471
+ if (armed) {
29472
+ const waitMs = armed.until - Date.now();
29473
+ if (waitMs > 0) {
29474
+ host.opts.log?.info(`typed dispatch ${backoffKey} backing off ${Math.ceil(waitMs / 1e3)}s after ${armed.failures} failed consume(s)`);
29475
+ await new Promise((resolve3) => {
29476
+ const timer = setTimeout(resolve3, waitMs);
29477
+ timer.unref?.();
29478
+ });
29602
29479
  }
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);
29480
+ if (host.shuttingDown)
29481
+ return;
29611
29482
  }
29612
- stopHeartbeat() {
29613
- if (this.heartbeatTimer) {
29614
- clearInterval(this.heartbeatTimer);
29615
- this.heartbeatTimer = null;
29483
+ const settleAck = (ackResult) => ackResult !== false;
29484
+ const settle = (acked2) => {
29485
+ if (acked2) {
29486
+ host.typedRedriveBackoff.delete(backoffKey);
29487
+ return;
29616
29488
  }
29617
- }
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);
29627
- }
29628
- clearReconnect() {
29629
- if (this.reconnectTimer) {
29630
- clearTimeout(this.reconnectTimer);
29631
- this.reconnectTimer = null;
29489
+ const failures = (host.typedRedriveBackoff.get(backoffKey)?.failures ?? 0) + 1;
29490
+ const backoffMs = Math.min(TYPED_BACKOFF_CAP_MS, TYPED_BACKOFF_BASE_MS * 2 ** (failures - 1));
29491
+ if (host.typedRedriveBackoff.delete(backoffKey) === false && host.typedRedriveBackoff.size >= TYPED_BACKOFF_MAP_CAP) {
29492
+ const oldest = host.typedRedriveBackoff.keys().next().value;
29493
+ if (oldest !== void 0)
29494
+ host.typedRedriveBackoff.delete(oldest);
29632
29495
  }
29633
- }
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 {
29496
+ host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
29497
+ };
29498
+ const runLegacy = async () => {
29499
+ let acked2 = false;
29500
+ try {
29501
+ if (await run(ref.dispatchEventId)) {
29502
+ acked2 = settleAck(await ack(ref.dispatchEventId));
29647
29503
  }
29648
- this.ws = null;
29649
- }
29650
- if (this.options.reconnect && !this.intentionalClose) {
29651
- this.scheduleReconnect();
29652
- } else {
29653
- this.setState("disconnected");
29504
+ } finally {
29505
+ settle(acked2);
29654
29506
  }
29507
+ };
29508
+ if (!host.laneLedger || host.ledgerDisabled) {
29509
+ await runLegacy();
29510
+ return;
29655
29511
  }
29656
- // ---- Browser event listeners for proactive reconnection ----
29657
- setupBrowserListeners() {
29658
- if (this.browserListenersActive)
29512
+ let lane;
29513
+ try {
29514
+ lane = await host.laneLedger.claimTyped(ref);
29515
+ } catch (err) {
29516
+ if (err instanceof LedgerUnsupportedError) {
29517
+ host.disableLedger("claim endpoint missing");
29518
+ await runLegacy();
29659
29519
  return;
29660
- this.browserListenersActive = true;
29661
- if (typeof document !== "undefined") {
29662
- document.addEventListener("visibilitychange", this.handleVisibilityChange);
29663
29520
  }
29664
- if (typeof window !== "undefined") {
29665
- window.addEventListener("online", this.handleOnline);
29521
+ throw err;
29522
+ }
29523
+ if (!lane) {
29524
+ host.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} not claimable (held elsewhere or already resolved) \u2014 skipping`);
29525
+ return;
29526
+ }
29527
+ let acked = false;
29528
+ try {
29529
+ if (await run(lane.typedDispatchEventId)) {
29530
+ acked = settleAck(await ack(lane.typedDispatchEventId));
29666
29531
  }
29532
+ } finally {
29533
+ settle(acked);
29534
+ await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
29535
+ });
29667
29536
  }
29668
- teardownBrowserListeners() {
29669
- if (!this.browserListenersActive)
29537
+ }
29538
+ async function consumeMessageWorkItem(host, item) {
29539
+ if (host.shuttingDown)
29540
+ return;
29541
+ if (!host.tryClaimMessage(item.source_id))
29542
+ return;
29543
+ const ackItem = () => {
29544
+ host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
29545
+ });
29546
+ };
29547
+ let msg = null;
29548
+ try {
29549
+ msg = await host.opts.client.getMessage(item.source_id);
29550
+ } catch (err) {
29551
+ const status = err?.status;
29552
+ if (status !== 404) {
29553
+ host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
29554
+ host.dispatchedMessages.delete(item.source_id);
29670
29555
  return;
29671
- this.browserListenersActive = false;
29672
- if (typeof document !== "undefined") {
29673
- document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29674
29556
  }
29675
- if (typeof window !== "undefined") {
29676
- window.removeEventListener("online", this.handleOnline);
29557
+ }
29558
+ if (!msg || msg.sender_id === host.opts.agentUserId) {
29559
+ host.dispatchedMessages.delete(item.source_id);
29560
+ ackItem();
29561
+ return;
29562
+ }
29563
+ const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
29564
+ if (decision.action === "retry") {
29565
+ host.dispatchedMessages.delete(item.source_id);
29566
+ return;
29567
+ }
29568
+ if (decision.action === "skip") {
29569
+ host.dispatchedMessages.delete(item.source_id);
29570
+ ackItem();
29571
+ return;
29572
+ }
29573
+ decision.event.dispatchEventId = item.id;
29574
+ const laneResolved = host.usesLaneLedger(decision.event);
29575
+ try {
29576
+ const dispatched = await host.handleInboundEvent(decision.event);
29577
+ if (dispatched) {
29578
+ if (!laneResolved)
29579
+ ackItem();
29580
+ } else {
29581
+ host.dispatchedMessages.delete(item.source_id);
29677
29582
  }
29583
+ } catch (err) {
29584
+ host.dispatchedMessages.delete(item.source_id);
29585
+ throw err;
29586
+ }
29587
+ }
29588
+
29589
+ // ../agent-core/dist/session-state.js
29590
+ function normalizeSessionKey(sessionKey) {
29591
+ return sessionKey.toLowerCase();
29592
+ }
29593
+ var sessionChatIdMap = /* @__PURE__ */ new Map();
29594
+ var sessionMessageIdMap = /* @__PURE__ */ new Map();
29595
+ var dispatchMessageIdMap = /* @__PURE__ */ new Map();
29596
+ var dispatchGroupKeyMap = /* @__PURE__ */ new Map();
29597
+ var dispatchNoReplyMap = /* @__PURE__ */ new Map();
29598
+ function setSessionChatId(sessionKey, chatId) {
29599
+ sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
29600
+ }
29601
+ function getSessionChatId(sessionKey) {
29602
+ return sessionChatIdMap.get(normalizeSessionKey(sessionKey));
29603
+ }
29604
+ function setSessionMessageId(sessionKey, messageId) {
29605
+ sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29606
+ }
29607
+ function clearSessionMessageId(sessionKey) {
29608
+ sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
29609
+ }
29610
+ function setDispatchMessageId(sessionKey, messageId) {
29611
+ dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29612
+ }
29613
+ function getDispatchMessageId(sessionKey) {
29614
+ return dispatchMessageIdMap.get(normalizeSessionKey(sessionKey));
29615
+ }
29616
+ function clearDispatchMessageId(sessionKey) {
29617
+ dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
29618
+ }
29619
+ function setDispatchGroupKey(sessionKey, groupKey) {
29620
+ dispatchGroupKeyMap.set(normalizeSessionKey(sessionKey), groupKey);
29621
+ }
29622
+ function getDispatchGroupKey(sessionKey) {
29623
+ return dispatchGroupKeyMap.get(normalizeSessionKey(sessionKey));
29624
+ }
29625
+ function clearDispatchGroupKey(sessionKey) {
29626
+ dispatchGroupKeyMap.delete(normalizeSessionKey(sessionKey));
29627
+ }
29628
+ function setDispatchNoReply(sessionKey, noReply) {
29629
+ dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
29630
+ }
29631
+ function clearDispatchNoReply(sessionKey) {
29632
+ dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
29633
+ }
29634
+ var dispatchMetricsMap = /* @__PURE__ */ new Map();
29635
+ function resetDispatchMetrics(sessionKey) {
29636
+ dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
29637
+ deliver_text_chunks: 0,
29638
+ deliver_text_chars: 0,
29639
+ message_send_attempts: 0,
29640
+ message_send_successes: 0,
29641
+ no_reply_called: false,
29642
+ tool_call_count: 0,
29643
+ started_at: Date.now()
29644
+ });
29645
+ }
29646
+ function getDispatchMetrics(sessionKey) {
29647
+ return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29648
+ }
29649
+ function clearDispatchMetrics(sessionKey) {
29650
+ dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
29651
+ }
29652
+ function recordDeliverText(sessionKey, charCount) {
29653
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29654
+ if (!m)
29655
+ return;
29656
+ m.deliver_text_chunks++;
29657
+ m.deliver_text_chars += charCount;
29658
+ }
29659
+ function recordMessageSend(sessionKey, success) {
29660
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29661
+ if (!m)
29662
+ return;
29663
+ m.message_send_attempts++;
29664
+ if (success)
29665
+ m.message_send_successes++;
29666
+ }
29667
+ function recordNoReply(sessionKey) {
29668
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29669
+ if (!m)
29670
+ return;
29671
+ m.no_reply_called = true;
29672
+ }
29673
+ function recordToolCall(sessionKey) {
29674
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29675
+ if (!m)
29676
+ return;
29677
+ m.tool_call_count++;
29678
+ }
29679
+
29680
+ // ../agent-core/dist/routing.js
29681
+ var MAX_CONCURRENT_FORKS = 20;
29682
+ var defaultRoutingStrategy = (event, state) => {
29683
+ if (state.mainCurrentTargetId === event.targetId) {
29684
+ return { action: "buffer-main" };
29678
29685
  }
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);
29686
+ const existingForkKey = state.activeForks.get(event.targetId);
29687
+ if (existingForkKey)
29688
+ return { action: "buffer-fork", forkKey: existingForkKey };
29689
+ if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
29690
+ return { action: "buffer-main" };
29691
29691
  }
29692
- clearProbe() {
29693
- if (this.probeTimer) {
29694
- clearTimeout(this.probeTimer);
29695
- this.probeTimer = null;
29692
+ return { action: "new-fork" };
29693
+ };
29694
+ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
29695
+ const existingForkKey = state.activeForks.get(event.targetId);
29696
+ if (existingForkKey)
29697
+ return { action: "buffer-fork", forkKey: existingForkKey };
29698
+ if (!state.mainDispatching)
29699
+ return { action: "main" };
29700
+ return strategy(event, state);
29701
+ }
29702
+
29703
+ // ../agent-core/dist/event-format.js
29704
+ function sanitizeMeta(value) {
29705
+ return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
29706
+ }
29707
+ function buildEventBody(event) {
29708
+ const lines = [];
29709
+ if (event.type === "message") {
29710
+ lines.push(`[Event: message.new]`);
29711
+ const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29712
+ lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
29713
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29714
+ lines.push(`[Message ID: prll://${event.messageId}]`);
29715
+ if (event.threadRootId) {
29716
+ const threadMeta = [
29717
+ `prll://${event.threadRootId}`,
29718
+ event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
29719
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
29720
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
29721
+ ].filter(Boolean).join(" | ");
29722
+ lines.push(`[Thread: ${threadMeta}]`);
29696
29723
  }
29697
- }
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();
29724
+ if (event.unreadCount != null && event.unreadCount > 1) {
29725
+ const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
29726
+ const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
29727
+ let line = `[Unread: ${countStr} messages${sinceStr}]`;
29728
+ if (event.unreadCount > 50)
29729
+ line += ` \u2014 fetch recent context with --limit, not all`;
29730
+ lines.push(line);
29712
29731
  }
29713
- };
29714
- /** Network restored — accelerate reconnection. */
29715
- handleOnline = () => {
29716
- if (this.intentionalClose)
29717
- return;
29718
- if (this._state === "connected") {
29719
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29720
- this.forceReconnect();
29721
- } else {
29722
- this.probeConnection();
29732
+ if (event.noReply)
29733
+ lines.push(`[Hint: no_reply]`);
29734
+ if (event.attachments?.length) {
29735
+ for (const att of event.attachments) {
29736
+ const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
29737
+ lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
29723
29738
  }
29724
- } else if (this._state === "reconnecting") {
29725
- this.clearReconnect();
29726
- this.reconnectAttempts = 0;
29727
- this.connect();
29728
29739
  }
29729
- };
29730
- setState(state) {
29731
- this._state = state;
29732
- for (const listener of this.stateListeners) {
29733
- listener(state);
29740
+ lines.push("", event.body);
29741
+ } else if (event.type === "task_comment") {
29742
+ lines.push(`[Event: task.comment.created]`);
29743
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29744
+ lines.push(`[Task: ${taskLabel}]`);
29745
+ if (event.deliveryReason)
29746
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29747
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29748
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29749
+ lines.push("", event.body);
29750
+ } else if (event.type === "wiki_comment") {
29751
+ lines.push(`[Event: wiki.comment.created]`);
29752
+ const target = event.replyTargetUri ?? `prll://${event.targetId}`;
29753
+ if (event.targetType === "changeset") {
29754
+ lines.push(`[Wiki Changeset: ${target}]`);
29755
+ } else {
29756
+ lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
29734
29757
  }
29735
- }
29736
- };
29737
-
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";
29744
- }
29745
- function isEndpointMissing(err) {
29746
- return err instanceof ApiError && err.status === 404 && !err.code;
29747
- }
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;
29756
- }
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_");
29760
- }
29761
- laneKeyFor(event) {
29762
- if (event.type !== "message" && event.dispatchEventId) {
29763
- return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29758
+ if (event.deliveryReason)
29759
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29760
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29761
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29762
+ lines.push("", event.body);
29763
+ } else if (event.type === "approval") {
29764
+ lines.push(`[Event: approval.decided]`);
29765
+ lines.push(`[Approval: prll://${event.messageId}]`);
29766
+ lines.push(`[Chat: prll://${event.targetId}]`);
29767
+ lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
29768
+ lines.push("", event.body);
29769
+ } else if (event.type === "schedule") {
29770
+ lines.push(`[Event: schedule.fired]`);
29771
+ lines.push(`[Schedule: prll://${event.targetId}]`);
29772
+ lines.push(`[Run: prll://${event.messageId}]`);
29773
+ if (event.scheduledFireAt)
29774
+ lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
29775
+ if (event.attachedUri)
29776
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29777
+ lines.push("", event.body);
29778
+ } else if (event.type === "channel_message") {
29779
+ lines.push(`[Event: channel.message]`);
29780
+ const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
29781
+ const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
29782
+ lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
29783
+ lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
29784
+ if (event.channelExternalMessageId) {
29785
+ lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
29764
29786
  }
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);
29813
- }
29814
- this.lanes.set(laneKey, lane);
29787
+ 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.]`);
29788
+ lines.push("", event.body);
29789
+ } else if (event.type === "external_trigger") {
29790
+ lines.push(`[Event: external.trigger]`);
29791
+ lines.push(`[Trigger: prll://${event.targetId}]`);
29792
+ lines.push(`[Run: prll://${event.messageId}]`);
29793
+ if (event.externalConnectionId) {
29794
+ const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
29795
+ lines.push(`[Connection: ${label}]`);
29815
29796
  }
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
- }
29797
+ if (event.externalIngressEventId)
29798
+ lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
29799
+ if (event.attachedUri)
29800
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29801
+ if (event.externalConnectionSourceType) {
29802
+ lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
29836
29803
  }
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;
29804
+ if (event.externalIngressEventType) {
29805
+ lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
29868
29806
  }
29807
+ lines.push("", event.body);
29808
+ } else {
29809
+ lines.push(`[Event: task.assigned]`);
29810
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29811
+ lines.push(`[Task: ${taskLabel}]`);
29812
+ lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
29813
+ lines.push("", event.body);
29869
29814
  }
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)}`);
29815
+ return lines.join("\n") + buildSendMessageHint(event);
29816
+ }
29817
+ function buildEventBodyForForkResult(event) {
29818
+ return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
29819
+ }
29820
+ function buildSendMessageHint(event) {
29821
+ if (event.noReply)
29822
+ return "";
29823
+ if (event.type === "wiki_comment" && event.replyTargetUri) {
29824
+ const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
29825
+ return `
29826
+ <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>`;
29827
+ }
29828
+ if (event.targetId.startsWith("cht_")) {
29829
+ if (event.threadRootId) {
29830
+ return `
29831
+ <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>`;
29897
29832
  }
29833
+ return `
29834
+ <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>`;
29898
29835
  }
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
- });
29836
+ if (event.targetId.startsWith("tsk_")) {
29837
+ return `
29838
+ <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>`;
29930
29839
  }
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)}`);
29946
- }
29840
+ if (event.targetId.startsWith("sch_")) {
29841
+ return `
29842
+ <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
29947
29843
  }
29948
- async releaseAll() {
29949
- const keys = [...this.lanes.keys()];
29950
- for (const key of keys) {
29951
- await this.release(key);
29844
+ if (event.type === "channel_message") {
29845
+ if (event.channelCliCapable) {
29846
+ const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
29847
+ const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
29848
+ return `
29849
+ <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>`;
29952
29850
  }
29851
+ const platform = event.channelProvider ?? "the external platform";
29852
+ return `
29853
+ <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>`;
29953
29854
  }
29954
- /** True when any lane is currently active (used by shutdown logging). */
29955
- get activeCount() {
29956
- return this.lanes.size;
29855
+ if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
29856
+ return `
29857
+ <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>`;
29957
29858
  }
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;
29859
+ return "";
29860
+ }
29861
+ function buildForkScopePrefix(event) {
29862
+ const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29863
+ 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.
29864
+
29865
+ 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.
29866
+
29867
+ End with a brief "Fork summary" of actions taken and decisions made.]
29868
+
29869
+ `;
29870
+ }
29871
+ function buildForkResultPrefix(results) {
29872
+ if (!results.length)
29873
+ return "";
29874
+ const blocks = results.map((result) => {
29875
+ const lines = [];
29876
+ for (const body of result.eventBodies) {
29877
+ lines.push(body);
29976
29878
  }
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;
29992
- }
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
- }
29879
+ lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
29880
+ 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."}]`);
29881
+ if (result.actions.length)
29882
+ lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
29883
+ if (result.historyPath)
29884
+ lines.push(`[Fork history: ${result.historyPath}]`);
29885
+ return lines.join("\n");
29886
+ });
29887
+ return blocks.join("\n\n") + "\n\n---\n\n";
29888
+ }
29889
+
29890
+ // ../agent-core/dist/prompt-fragments.js
29891
+ var PRLL_IDENTITY_BASE = `## You on Parall
29892
+
29893
+ Parall is a shared workspace where humans and agents work side by side as equals.
29894
+ You are a participant here, not a service. You hold tasks, own decisions, and are
29895
+ accountable for the work you take on \u2014 the same way a human teammate is.
29896
+
29897
+ The people and agents around you are collaborators, not users to serve. Be honest,
29898
+ be direct, and care about the outcome of the work \u2014 not just the request in front
29899
+ of you.`;
29900
+ function sanitizeProfileField(value) {
29901
+ return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
29902
+ }
29903
+ function sanitizeProfileBlock(value) {
29904
+ return value.replace(/\r\n?/g, "\n").trim();
29905
+ }
29906
+ function buildIdentity(agent) {
29907
+ if (!agent)
29908
+ return PRLL_IDENTITY_BASE;
29909
+ const name = sanitizeProfileField(agent.displayName);
29910
+ const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
29911
+ lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
29912
+ if (agent.description) {
29913
+ const description = sanitizeProfileBlock(agent.description);
29914
+ if (description) {
29915
+ lines.push("", "### Your Agent Profile", "", description);
30006
29916
  }
30007
29917
  }
30008
- };
29918
+ lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
29919
+ return lines.join("\n");
29920
+ }
29921
+ var PRLL_BEHAVIOR = `## How to work here
30009
29922
 
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";
29923
+ ### Move work forward
29924
+ Don't wait for instructions. If you see the next step, take it. If something is
29925
+ ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
29926
+ \u2014 don't go silent. Initiative is expected.
29927
+
29928
+ Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
29929
+ requests, verifying something landed. When a thing needs future attention and
29930
+ nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
29931
+
29932
+ ### Work in the open
29933
+ Nothing you do exists until the system can see it. Your progress, decisions,
29934
+ blockers, and results need to live in tasks, comments, messages, or wiki pages
29935
+ \u2014 otherwise the organization is blind to your work, and so is the next agent
29936
+ who picks up where you left off. Leave traces as you go, not at the end.
29937
+
29938
+ For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
29939
+ when status materially changes, close it when done, and link the origin that
29940
+ triggered it. Decompose multi-step work into subtasks and keep their statuses
29941
+ current \u2014 progress should be auditable without watching the work happen.
29942
+ Details: load the \`parall-tasks\` skill.
29943
+
29944
+ ### Done means landed
29945
+ Producing output does not complete a task. Work counts as done only when it has
29946
+ cleared its remaining gates \u2014 review, merge, deployment, the requester's
29947
+ verification. Until then keep the status honest (\`in_progress\` or
29948
+ \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
29949
+ self-reminder if nothing else will prompt follow-up). Never mark done what a
29950
+ human still has to accept.
29951
+
29952
+ ### Sessions, forks, and what survives
29953
+ Sessions end and context compacts. Anything that must survive \u2014 decisions,
29954
+ progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
29955
+ read the workspace, not this conversation.
29956
+
29957
+ Some events are handled by parallel fork sessions \u2014 short-lived copies of the
29958
+ same agent identity with separate context. In a fork: leave a written trace of
29959
+ what was done or deliberately not done (other sessions cannot see fork
29960
+ context), and do not start long-running processes \u2014 they die with the fork.
29961
+ When an event is marked fork-handled: do not re-handle it; verify its outcome
29962
+ instead of assuming it.
29963
+
29964
+ ### Communicate like a teammate
29965
+ Match the conversation \u2014 concise in chat, thorough in docs, plain language over
29966
+ jargon. Say what matters; stop when you're done. Don't narrate every tool call
29967
+ or pad replies to seem thorough.
29968
+
29969
+ Match the language of the person you're replying to. If someone writes in
29970
+ Chinese, reply in Chinese. If in English, reply in English. Never force a
29971
+ language switch unless explicitly asked.
29972
+
29973
+ Do not promise delivery times ("in an hour", "by tonight") unless the work is
29974
+ driven by an explicit schedule. Scope visibly; report when actually done.
29975
+
29976
+ ### Keep topics in threads
29977
+ Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
29978
+ Present \u2192 that thread is the context; reply there, passing the same root as
29979
+ \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
29980
+ never treat it as continuing your most recent thread. The sender's newest
29981
+ message is the anchor \u2014 never route a reply back into an older thread just
29982
+ because the topic used to live there.
29983
+
29984
+ Reply where the event lives: a thread message gets a thread reply, a
29985
+ top-level message gets a top-level reply. But in group chats, your later
29986
+ follow-up on that topic \u2014 progress updates, analysis, links, verification you
29987
+ post afterwards \u2014 belongs in a thread rooted at the topic's message
29988
+ (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
29989
+ the main channel stays scannable. Post follow-up at top level only when
29990
+ starting a genuinely new topic, making a channel-wide announcement, or when
29991
+ explicitly asked. Never post the same update in both the thread and the main
29992
+ channel \u2014 thread replies surface in the thread panel; no need to duplicate
29993
+ for visibility.
29994
+
29995
+ In DMs, reply top-level by default; use a thread only to continue one that
29996
+ already exists.
29997
+
29998
+ ### Group chats: mentions and unaddressed work
29999
+ An @mention is a direct request \u2014 act on it. A group message delivered to you
30000
+ without an @mention means the chat's routing lets you see the conversation:
30001
+ decide whether a reply adds value; silence is the default.
30002
+
30003
+ A message without an @mention is not an open invitation. Judge from context
30004
+ who the work belongs to \u2014 the named domain, the topic's owner, whoever is
30005
+ already on it. If it belongs to someone else, leave it. If genuinely unclear,
30006
+ ask or claim in one line ("taking this unless someone else has it") before
30007
+ starting \u2014 asking first beats duplicated or misdirected work.
30008
+
30009
+ ### Verify before you act
30010
+ Events can be redelivered \u2014 before acting, check whether it was already
30011
+ handled (your own recent replies, task comments); if handled, do nothing.
30012
+ Sends can fail silently, and creates can error after succeeding server-side \u2014
30013
+ check the chat or entity before retrying. Never blind-retry a mutating call.
30014
+
30015
+ ### Gather the full picture first
30016
+ When a request is vague, an entity may already exist, or work may already be
30017
+ underway \u2014 gather context before acting: search (\`parall search "..."\`),
30018
+ check existing tasks/chats/wiki, read the surrounding conversation. Act on the
30019
+ full picture, not the fragment that arrived in the event.
30020
+
30021
+ ### Report only work that ran
30022
+ If a scheduled job, scan, or tool call did not actually run \u2014 restarted
30023
+ session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
30024
+ or approximate results of work that did not execute.
30025
+
30026
+ ### Respect what's shared
30027
+ You have broad latitude inside your own work. But actions that are visible to
30028
+ others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
30029
+ wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
30030
+ acting, unless you've been explicitly authorized.
30031
+
30032
+ ### Shared workspace
30033
+ Other agents share this workspace. Before starting work, check whether someone
30034
+ \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
30035
+
30036
+ ### Permissions and approvals
30037
+ You have real permissions based on your roles (chat member/admin, org member).
30038
+ If you lack permission for an action, the API returns PERMISSION_DENIED with the
30039
+ \`action\` and \`resource_uri\` that were denied. The server decides whether that
30040
+ action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
30041
+ fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
30042
+ it to ask someone with permission. If it is NOT approvable, the output says so;
30043
+ ask a human with permission instead of requesting approval. A
30044
+ \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
30045
+ (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
30046
+ \`dm\` for a user). Don't retry or work around a denial; only request approval
30047
+ after an actual denial, never preemptively.
30048
+
30049
+ ### When in doubt
30050
+ Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
30051
+ credibility is what you bring to the workspace \u2014 protect it.`;
30052
+ var PRLL_REFERENCE_GUIDE = `## Parall References
30053
+
30054
+ Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
30055
+ entities when you create or update tasks, comments, messages, and wiki files.
30056
+
30057
+ All three forms work \u2014 pick whichever fits:
30058
+
30059
+ prll://tsk_abc bare URI (auto-linked)
30060
+ [](prll://tsk_abc) empty context (renders resolved title)
30061
+ [relevant context](prll://tsk_abc) with author annotation
30062
+
30063
+ Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
30064
+ resolves and renders the entity title automatically.
30065
+
30066
+ ### URI format
30067
+
30068
+ \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
30069
+
30070
+ **Entities** \u2014 the entity ID is the authority:
30071
+
30072
+ prll://usr_xxx user prll://prj_xxx project
30073
+ prll://tsk_xxx task prll://wik_xxx wiki
30074
+ prll://msg_xxx message prll://cmt_xxx comment
30075
+ prll://cht_xxx chat prll://tcm_xxx task comment (legacy)
30076
+ prll://att_xxx attachment prll://ase_xxx agent session
30077
+ prll://sch_xxx schedule prll://srn_xxx schedule run
30078
+
30079
+ **Wiki** \u2014 path is file path, fragment is a typed anchor:
30080
+
30081
+ prll://wik_xxx/docs/guide.md file
30082
+ prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
30083
+ prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
30084
+
30085
+ Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
30086
+ Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
30087
+
30088
+ **Chat message range**:
30089
+
30090
+ prll://cht_xxx#range=msg_01HA,msg_01HZ
30091
+
30092
+ **Field access** \u2014 path selects a field (omit to reference the entity itself):
30093
+
30094
+ prll://tsk_xxx/description#Implementation heading within task description
30095
+
30096
+ ### Unread context
30097
+
30098
+ When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
30099
+ This shows messages since your last interaction \u2014 your read cursor advances after each
30100
+ dispatch, so context you skip now won't appear as unread next time. Use
30101
+ \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
30102
+ counts (50+), fetch only recent messages rather than everything.
30103
+
30104
+ Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
30105
+ Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
30106
+ catch up on the thread.
30107
+
30108
+ ### Reading context on demand
30109
+
30110
+ An event only carries the single triggering message. If you're mentioned in a
30111
+ group chat and lack context, pull what you need from the chat \u2014 don't guess:
30112
+
30113
+ parall messages list cht_xxx --limit 20 --before msg_xxx
30114
+ parall messages get msg_xxx
30115
+ parall chats get cht_xxx
30116
+
30117
+ Rule of thumb: in a group chat mention, the conversation that led up to you
30118
+ being called almost always matters \u2014 read it before replying. In a DM, your
30119
+ session already has continuity, so skip the fetch unless something is unclear.
30120
+
30121
+ Same pattern for any other entity referenced in the event: \`tasks get\`,
30122
+ \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
30123
+ When one entity isn't enough \u2014 you need what's *around* it \u2014 walk the
30124
+ reference graph instead of guessing (see "Walk the reference graph" below).
30125
+
30126
+ ### Find context with search first
30127
+
30128
+ Reach for unified semantic search before paging chat history:
30129
+
30130
+ parall search "pricing decision june" --limit 10
30131
+
30132
+ It spans messages, tasks, wiki, and comments. Page \`messages list\` only for the
30133
+ verbatim recent flow of one chat, not for discovery.
30134
+
30135
+ ### Walk the reference graph
30136
+
30137
+ References form a traversable graph, and you can query it \u2014 don't stop at
30138
+ fetching entities one by one:
30139
+
30140
+ # entity metadata (title, status, preview)
30141
+ parall refs resolve prll://tsk_xxx prll://wik_xxx
30142
+ # who references this entity
30143
+ parall refs backlinks prll://tsk_xxx
30144
+ # connected sub-graph around it
30145
+ parall refs graph prll://tsk_xxx --depth 2
30146
+
30147
+ Use \`refs backlinks\` when you need "where is this discussed / used"; use
30148
+ \`refs graph\` when you need the full picture around an entity (related tasks,
30149
+ docs, conversations \u2014 edges carry the author's annotation for why they linked).
30150
+ Then \`refs resolve\` the interesting node URIs in one batch to get titles and
30151
+ status. \`refs graph\` takes entity-level URIs only (\`prll://wik_xxx\`, not
30152
+ \`prll://wik_xxx/docs/a.md\`). All results are filtered to what you can see.
30153
+ Details: parall-platform skill.
30154
+
30155
+ ### File attachments
30156
+
30157
+ Messages may include attachments. They appear in events as:
30158
+
30159
+ [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
30160
+
30161
+ To download an attachment, use the CLI:
30162
+
30163
+ parall files download att_xxx --output /tmp/screenshot.png
30164
+
30165
+ To send a file:
30166
+
30167
+ parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
30168
+
30169
+ Or upload first and reuse across chats:
30170
+
30171
+ parall files upload /tmp/report.pdf
30172
+ parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
30173
+ parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
30174
+
30175
+ 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 \`$(...)\`.
30176
+
30177
+ ### When to reference
30178
+
30179
+ - **Origin** \u2014 always link the message or task that triggered your work
30180
+ - **Design docs / wiki** \u2014 link specs and guides relevant to the work
30181
+ - **Related tasks** \u2014 link parent, sibling, or blocking tasks
30182
+ - **People** \u2014 link assignees or stakeholders when mentioning them
30183
+ - **Conversations** \u2014 link a chat or message range as context
30184
+
30185
+ ### Why this matters
30186
+
30187
+ Other agents and humans read your output. References build a navigable context graph \u2014
30188
+ in multi-agent workflows, your references are the map that the next agent follows.`;
30189
+ function renderLocalAttachmentSection(section) {
30190
+ if (section.images.length === 0 && section.notes.length === 0)
30191
+ return "";
30192
+ const lines = ["[Local attachment files]"];
30193
+ for (const image of section.images) {
30194
+ lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
30050
30195
  }
30051
- const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
30052
- await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
30053
- return "dispatched";
30196
+ lines.push(...section.notes);
30197
+ return lines.join("\n");
30054
30198
  }
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
- }
30199
+ function sanitizePromptMeta(value) {
30200
+ return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
30084
30201
  }
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;
30202
+ function formatBytes(bytes) {
30203
+ if (bytes >= 1048576)
30204
+ return `${(bytes / 1048576).toFixed(1)}MB`;
30205
+ if (bytes >= 1024)
30206
+ return `${Math.round(bytes / 1024)}KB`;
30207
+ return `${bytes}B`;
30208
+ }
30209
+
30210
+ // ../agent-core/dist/bridge-workspace.js
30211
+ function extractShellCommand(input) {
30212
+ if (!input || typeof input !== "object")
30213
+ return void 0;
30214
+ const command = input.command;
30215
+ return typeof command === "string" && command.trim() ? command.trim() : void 0;
30216
+ }
30217
+ function parseParallCliInvocation(command) {
30218
+ const tokens = command.replace(/\s+/g, " ").trim().split(" ");
30219
+ let i = 0;
30220
+ if (tokens[i] === "parall") {
30221
+ i++;
30222
+ } else if (tokens[i] === "npx") {
30223
+ i++;
30224
+ while (i < tokens.length && tokens[i].startsWith("-"))
30225
+ i++;
30226
+ if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
30227
+ return null;
30228
+ i++;
30229
+ } else if (tokens[i] === "pnpm") {
30230
+ i++;
30231
+ if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
30232
+ i++;
30233
+ if (i >= tokens.length || tokens[i] !== "parall")
30234
+ return null;
30235
+ i++;
30236
+ } else {
30237
+ return null;
30133
30238
  }
30239
+ return tokens.slice(i).filter((t) => !t.startsWith("-"));
30240
+ }
30241
+ function isParallSendCommand(command) {
30242
+ if (!command)
30243
+ return false;
30244
+ const sub = parseParallCliInvocation(command);
30245
+ if (!sub || sub.length === 0)
30246
+ return false;
30247
+ return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
30248
+ }
30249
+ function isParallNoReplyCommand(command) {
30250
+ if (!command)
30251
+ return false;
30252
+ const sub = parseParallCliInvocation(command);
30253
+ return sub?.[0] === "no-reply";
30134
30254
  }
30135
30255
 
30256
+ // ../agent-core/dist/dispatch-adapter.js
30257
+ function buildErrorStepContent(message) {
30258
+ return { text: message, suppressed: false, status: "error" };
30259
+ }
30260
+
30261
+ // ../agent-core/dist/gateway-base.js
30262
+ import * as os from "node:os";
30263
+ import * as fs2 from "node:fs";
30264
+ import * as path2 from "node:path";
30265
+
30136
30266
  // ../agent-core/dist/telemetry.js
30137
30267
  init_esm();
30138
30268
  var import_api_logs = __toESM(require_src(), 1);
@@ -30413,6 +30543,9 @@ var ParallAgentGateway = class {
30413
30543
  // (stable mapping; avoids one connection fetch per inbound message).
30414
30544
  channelConnectionProviders = /* @__PURE__ */ new Map();
30415
30545
  dispatchedMessages = /* @__PURE__ */ new Set();
30546
+ // Per-WorkItem failure backoff for typed dispatch consumption — see
30547
+ // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
30548
+ typedRedriveBackoff = /* @__PURE__ */ new Map();
30416
30549
  forkStates = /* @__PURE__ */ new Map();
30417
30550
  dispatchState = {
30418
30551
  mainDispatching: false,
@@ -30537,7 +30670,11 @@ var ParallAgentGateway = class {
30537
30670
  return this.opts.client.ackDispatch(this.opts.config.org_id, {
30538
30671
  source_type: "task_activity",
30539
30672
  source_id: data.id
30540
- }).then(() => void 0, () => void 0);
30673
+ }).then(() => true, (err) => {
30674
+ this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
30675
+ this.opts.log?.warn(`dispatch ack failed for task ${data.id}, releasing for re-drive: ${String(err)}`);
30676
+ return false;
30677
+ });
30541
30678
  });
30542
30679
  } catch (err) {
30543
30680
  this.opts.log?.error(`task dispatch failed for ${data.id}: ${String(err)}`);
@@ -30644,6 +30781,44 @@ var ParallAgentGateway = class {
30644
30781
  this.dispatchedMessages.add(id);
30645
30782
  return true;
30646
30783
  }
30784
+ /**
30785
+ * Lane currently being dispatched per session — lets external activity
30786
+ * signals renew exactly the caller's lane (renewing all lanes would keep
30787
+ * an unrelated stalled fork's lane leased forever).
30788
+ */
30789
+ sessionActiveLanes = /* @__PURE__ */ new Map();
30790
+ noteSessionLane(sessionKey, laneKey) {
30791
+ if (laneKey == null)
30792
+ this.sessionActiveLanes.delete(sessionKey);
30793
+ else
30794
+ this.sessionActiveLanes.set(sessionKey, laneKey);
30795
+ }
30796
+ /**
30797
+ * External runtime-activity signal for adapters whose tool activity does
30798
+ * not flow through the RuntimeEvent stream (openclaw hooks call this from
30799
+ * the tool-call lifecycle): renews the session's OWN active ledger lane so
30800
+ * a long tool call cannot outlive the lease and get dethroned mid-turn.
30801
+ * No-op without an active ledger lane for the session.
30802
+ */
30803
+ touchRuntimeActivity(sessionKey) {
30804
+ if (this.ledgerDisabled)
30805
+ return;
30806
+ const laneKey = this.sessionActiveLanes.get(sessionKey);
30807
+ if (laneKey)
30808
+ this.laneLedger?.renewByKey(laneKey);
30809
+ }
30810
+ /** Sessions whose in-flight turn surfaced a runtime error event. */
30811
+ turnErrorSessions = /* @__PURE__ */ new Set();
30812
+ /**
30813
+ * Consume (read-and-clear) the error marker for sessionKey's last turn.
30814
+ * Feeds complete's turn_outcome so an error turn's lane members are
30815
+ * released for retry instead of no_action-swept (design §3). Consuming
30816
+ * (rather than peeking) keeps one-shot fork session keys from accumulating
30817
+ * in the set forever.
30818
+ */
30819
+ consumeTurnError(sessionKey) {
30820
+ return this.turnErrorSessions.delete(sessionKey);
30821
+ }
30647
30822
  async emitDispatchReceived(event) {
30648
30823
  const sourceType = event.ackSourceType ?? (event.type === "task" ? "task_activity" : "message");
30649
30824
  const sourceId = event.ackSourceId ?? event.messageId;
@@ -30687,11 +30862,15 @@ var ParallAgentGateway = class {
30687
30862
  }
30688
30863
  // Typed completion must wait until the administrative ack has either
30689
30864
  // committed or failed. Errors stay best-effort: a failed ack leaves the row
30690
- // received, so Complete releases and re-drives it safely.
30865
+ // received, so Complete releases and re-drives it safely. The boolean
30866
+ // outcome feeds the typed-consume backoff — an ack that failed must count
30867
+ // as a failed consume, or an ack outage would clear the backoff entry and
30868
+ // let the release re-drive spin at wire speed.
30691
30869
  ackDispatchEvent(dispatchEventId, onFailure) {
30692
- return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => void 0, (err) => {
30870
+ return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => true, (err) => {
30693
30871
  onFailure?.();
30694
30872
  this.opts.log?.warn(`dispatch ack failed for ${dispatchEventId}, releasing for re-drive: ${String(err)}`);
30873
+ return false;
30695
30874
  });
30696
30875
  }
30697
30876
  clearTypedDispatchDedupe(item) {
@@ -30989,6 +31168,7 @@ var ParallAgentGateway = class {
30989
31168
  this.pendingRestartNotification = null;
30990
31169
  }
30991
31170
  resetDispatchMetrics(sessionKey);
31171
+ this.turnErrorSessions.delete(sessionKey);
30992
31172
  return runWithSessionKey(sessionKey, async () => {
30993
31173
  let dispatchSpan = null;
30994
31174
  setSessionChatId(sessionKey, event.targetId);
@@ -31096,6 +31276,9 @@ var ParallAgentGateway = class {
31096
31276
  } else if (runtimeEvent.type === "tool_result" && pendingSendCallIds.delete(runtimeEvent.callId)) {
31097
31277
  recordMessageSend(sessionKey, !runtimeEvent.error);
31098
31278
  }
31279
+ if (runtimeEvent.type === "error") {
31280
+ this.turnErrorSessions.add(sessionKey);
31281
+ }
31099
31282
  await this.createRuntimeStep(binding.agentSessionId, event, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2);
31100
31283
  }
31101
31284
  if (!binding) {
@@ -31243,13 +31426,23 @@ var ParallAgentGateway = class {
31243
31426
  body: buildForkScopePrefix(last) + buildEventBody(last),
31244
31427
  earlier,
31245
31428
  captureText: batchText,
31246
- hasMoreLocal: () => fork.queue.length > 0
31429
+ // Per-LANE residue check (parity with the main-buffer path):
31430
+ // the fork queue can hold several lanes (channel + thread of
31431
+ // the same chat). A whole-queue check would defer THIS lane's
31432
+ // complete behind another lane's items and never revisit it —
31433
+ // its members would sit received until lease expiry.
31434
+ hasMoreLocal: () => fork.queue.some((it) => this.dispatchGroupKey(it.event) === this.dispatchGroupKey(last))
31247
31435
  });
31248
31436
  if (outcome === "foreign") {
31249
31437
  for (const item of items)
31250
31438
  item.resolve(false);
31251
31439
  break;
31252
31440
  }
31441
+ if (outcome === "failed") {
31442
+ for (const item of items)
31443
+ item.resolve(false);
31444
+ continue;
31445
+ }
31253
31446
  dispatched = outcome === "dispatched";
31254
31447
  } else {
31255
31448
  dispatched = await this.runDispatch(last, fork.fork.sessionKey, buildForkScopePrefix(last) + buildEventBody(last), earlier, batchText);
@@ -31283,6 +31476,7 @@ var ParallAgentGateway = class {
31283
31476
  remaining.resolve(false);
31284
31477
  }
31285
31478
  } finally {
31479
+ this.turnErrorSessions.delete(fork.fork.sessionKey);
31286
31480
  if (fork.deadlineTimer) {
31287
31481
  clearTimeout(fork.deadlineTimer);
31288
31482
  fork.deadlineTimer = null;
@@ -31395,6 +31589,10 @@ var ParallAgentGateway = class {
31395
31589
  this.dispatchState.pendingForkResults.unshift(...pendingFork);
31396
31590
  continue;
31397
31591
  }
31592
+ if (outcome === "failed") {
31593
+ this.dispatchState.pendingForkResults.unshift(...pendingFork);
31594
+ continue;
31595
+ }
31398
31596
  continue;
31399
31597
  }
31400
31598
  try {
@@ -31498,7 +31696,7 @@ var ParallAgentGateway = class {
31498
31696
  }
31499
31697
  this.dispatchState.mainBuffer.push(event);
31500
31698
  if (this.usesLaneLedger(event)) {
31501
- if (this.mainCurrentGroupKey === this.dispatchGroupKey(event) && await this.laneLedger?.steerLive(event) && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, buildEventBody(event))) {
31699
+ if (this.mainCurrentGroupKey === this.dispatchGroupKey(event) && this.opts.dispatchAdapter.enqueueDuringDispatch != null && await this.laneLedger?.steerLive(event) && await this.opts.dispatchAdapter.enqueueDuringDispatch(this.opts.runtimeKey, buildEventBody(event))) {
31502
31700
  this.opts.log?.info(`steer folded+injected for ${event.messageId} (will drain for bookkeeping)`);
31503
31701
  }
31504
31702
  } else if (this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, buildEventBody(event))) {
@@ -31525,12 +31723,14 @@ var ParallAgentGateway = class {
31525
31723
  this.dispatchState.mainBuffer.push(event);
31526
31724
  return false;
31527
31725
  }
31528
- try {
31529
- await this.emitDispatchReceived(event);
31530
- } catch (err) {
31531
- this.opts.log?.warn?.(`mark-received failed for fork dispatch, leaving unacked for retry: ${String(err)}`);
31532
- this.dispatchState.mainBuffer.push(event);
31533
- return false;
31726
+ if (!this.usesLaneLedger(event)) {
31727
+ try {
31728
+ await this.emitDispatchReceived(event);
31729
+ } catch (err) {
31730
+ this.opts.log?.warn?.(`mark-received failed for fork dispatch, leaving unacked for retry: ${String(err)}`);
31731
+ this.dispatchState.mainBuffer.push(event);
31732
+ return false;
31733
+ }
31534
31734
  }
31535
31735
  const fork = await this.opts.dispatchAdapter.forkSession({
31536
31736
  sessionKey: this.opts.runtimeKey,
@@ -32014,6 +32214,8 @@ var ParallAgentGateway = class {
32014
32214
  provider = void 0;
32015
32215
  }
32016
32216
  }
32217
+ const keys = this.opts.getCapabilityKeys?.() ?? [];
32218
+ const cliCapable = provider ? keys.includes(`${provider}-cli`) : keys.some((k) => k.endsWith("-cli"));
32017
32219
  const event = {
32018
32220
  type: "channel_message",
32019
32221
  targetId: conv.id,
@@ -32028,6 +32230,7 @@ var ParallAgentGateway = class {
32028
32230
  channelConversationType: conv.conversation_type || void 0,
32029
32231
  channelExternalConversationId: conv.external_conversation_id,
32030
32232
  channelExternalMessageId: msg.external_message_id,
32233
+ channelCliCapable: cliCapable,
32031
32234
  ackSourceType: "channel_message",
32032
32235
  ackSourceId: msg.id
32033
32236
  };
@@ -32361,12 +32564,116 @@ ${fullSummary}` : fullSummary;
32361
32564
  }
32362
32565
  };
32363
32566
 
32567
+ // ../agent-core/dist/platform-config.js
32568
+ function extractCapabilities(config) {
32569
+ const agents = config.agents ?? {};
32570
+ const raw = agents.capabilities;
32571
+ if (!Array.isArray(raw))
32572
+ return [];
32573
+ const out = [];
32574
+ for (const entry of raw) {
32575
+ if (typeof entry !== "object" || entry === null)
32576
+ continue;
32577
+ const e = entry;
32578
+ if (typeof e.key !== "string" || !e.key)
32579
+ continue;
32580
+ if (typeof e.fragment !== "string" || !e.fragment)
32581
+ continue;
32582
+ out.push({
32583
+ key: e.key,
32584
+ source: typeof e.source === "string" ? e.source : "",
32585
+ fragment: e.fragment
32586
+ });
32587
+ }
32588
+ return out;
32589
+ }
32590
+
32591
+ // ../agent-core/dist/channel-capability.js
32592
+ import * as fs3 from "node:fs";
32593
+ import * as path3 from "node:path";
32594
+ import { fileURLToPath } from "node:url";
32595
+ var CAPABILITY_FEISHU_CLI = "feishu-cli";
32596
+ var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
32597
+ function capabilityBinDir(stateDir) {
32598
+ return path3.join(stateDir, "bin");
32599
+ }
32600
+ function channelExecEntryPath() {
32601
+ const selfDir = path3.dirname(fileURLToPath(import.meta.url));
32602
+ const sibling = path3.join(selfDir, "parall-channel-exec.js");
32603
+ if (fs3.existsSync(sibling))
32604
+ return sibling;
32605
+ return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
32606
+ }
32607
+ function materializeChannelCapabilities(stateDir, capabilities, log) {
32608
+ try {
32609
+ reconcileFeishuCli(stateDir, capabilities, log);
32610
+ } catch (err) {
32611
+ log?.warn(`channel capability materialization failed: ${String(err)}`);
32612
+ }
32613
+ }
32614
+ function reconcileFeishuCli(stateDir, capabilities, log) {
32615
+ const binDir = capabilityBinDir(stateDir);
32616
+ const posixPath = path3.join(binDir, "lark-cli");
32617
+ const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
32618
+ const hadPointer = fs3.existsSync(posixPath);
32619
+ if (!granted && !hadPointer)
32620
+ return;
32621
+ fs3.mkdirSync(binDir, { recursive: true });
32622
+ const entry = channelExecEntryPath();
32623
+ const nodeExec = process.execPath;
32624
+ writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log);
32625
+ writePointerIfChanged(path3.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log);
32626
+ }
32627
+ function writePointerIfChanged(filePath, content, log) {
32628
+ let existing = null;
32629
+ try {
32630
+ existing = fs3.readFileSync(filePath, "utf8");
32631
+ } catch {
32632
+ existing = null;
32633
+ }
32634
+ if (existing !== content) {
32635
+ fs3.writeFileSync(filePath, content, { mode: 493 });
32636
+ log?.info(`channel capability: pointer materialized (${path3.basename(filePath)})`);
32637
+ }
32638
+ fs3.chmodSync(filePath, 493);
32639
+ }
32640
+ function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
32641
+ return [
32642
+ "#!/bin/sh",
32643
+ `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32644
+ "# Credential + exec logic lives in the agent-core package; revocation is",
32645
+ "# enforced by the platform mint endpoint, so this pointer stays constant.",
32646
+ // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
32647
+ // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
32648
+ // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
32649
+ // the mint. The pointer is a platform-authored trust-boundary artifact whose
32650
+ // whole job is a CONTROLLED launch of the broker (absolute node, magic
32651
+ // guard, skip-dir); this closes the same env-hijack class for node startup
32652
+ // that the absolute node path closes for PATH, keeping the launch deterministic.
32653
+ "unset NODE_OPTIONS NODE_PATH",
32654
+ // "$@" preserves argv exactly (this is the agent's main path via git-bash).
32655
+ `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
32656
+ ""
32657
+ ].join("\n");
32658
+ }
32659
+ function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
32660
+ return [
32661
+ "@echo off",
32662
+ `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32663
+ // Clear Node preload-hijack vars before launching node (see the sh pointer).
32664
+ 'set "NODE_OPTIONS="',
32665
+ 'set "NODE_PATH="',
32666
+ `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
32667
+ ""
32668
+ ].join("\r\n");
32669
+ }
32670
+
32364
32671
  // ../agent-core/dist/internal/attachment-input.js
32365
32672
  import { execSync } from "node:child_process";
32366
32673
  import { constants } from "node:fs";
32367
32674
  import * as fsSync from "node:fs";
32368
- import * as fs3 from "node:fs/promises";
32369
- import * as path3 from "node:path";
32675
+ import * as fs4 from "node:fs/promises";
32676
+ import * as path4 from "node:path";
32370
32677
  var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
32371
32678
  var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
32372
32679
  var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
@@ -32396,11 +32703,11 @@ async function prepareLocalImageAttachments(event, context2, opts) {
32396
32703
  };
32397
32704
  }
32398
32705
  const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
32399
- const messageDir = path3.join(rootDir, sanitizePathSegment(event.messageId));
32706
+ const messageDir = path4.join(rootDir, sanitizePathSegment(event.messageId));
32400
32707
  await ensurePathIsNotSymlink(messageDir);
32401
- await fs3.mkdir(messageDir, { recursive: true });
32708
+ await fs4.mkdir(messageDir, { recursive: true });
32402
32709
  await ensurePathIsNotSymlink(messageDir);
32403
- const activeMessageDir = path3.resolve(messageDir);
32710
+ const activeMessageDir = path4.resolve(messageDir);
32404
32711
  activeAttachmentDirs.add(activeMessageDir);
32405
32712
  const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
32406
32713
  const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
@@ -32417,7 +32724,7 @@ async function prepareLocalImageAttachments(event, context2, opts) {
32417
32724
  const notes = [];
32418
32725
  let downloadedBytes = 0;
32419
32726
  for (const att of imageAttachments) {
32420
- const localPath = path3.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
32727
+ const localPath = path4.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
32421
32728
  const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
32422
32729
  const fetchFresh = async () => {
32423
32730
  const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
@@ -32474,7 +32781,7 @@ async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
32474
32781
  return { body: appendLocalAttachmentRefs(body, attachments), attachments };
32475
32782
  }
32476
32783
  function pinLocalAttachmentPaths(images) {
32477
- const dirs = new Set(images.map((image) => path3.resolve(path3.dirname(image.localPath))));
32784
+ const dirs = new Set(images.map((image) => path4.resolve(path4.dirname(image.localPath))));
32478
32785
  for (const dir of dirs) {
32479
32786
  activeAttachmentDirs.add(dir);
32480
32787
  }
@@ -32489,7 +32796,7 @@ function pinLocalAttachmentPaths(images) {
32489
32796
  };
32490
32797
  }
32491
32798
  function attachmentRootDir(workspaceDir) {
32492
- return path3.join(path3.resolve(workspaceDir), ".parall", "attachments");
32799
+ return path4.join(path4.resolve(workspaceDir), ".parall", "attachments");
32493
32800
  }
32494
32801
  function ensureLocalAttachmentGitExclude(workingDirectory) {
32495
32802
  try {
@@ -32498,8 +32805,8 @@ function ensureLocalAttachmentGitExclude(workingDirectory) {
32498
32805
  encoding: "utf8",
32499
32806
  stdio: ["ignore", "pipe", "ignore"]
32500
32807
  }).trim();
32501
- const excludePath = path3.isAbsolute(rel) ? rel : path3.join(workingDirectory, rel);
32502
- fsSync.mkdirSync(path3.dirname(excludePath), { recursive: true });
32808
+ const excludePath = path4.isAbsolute(rel) ? rel : path4.join(workingDirectory, rel);
32809
+ fsSync.mkdirSync(path4.dirname(excludePath), { recursive: true });
32503
32810
  const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
32504
32811
  if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
32505
32812
  return;
@@ -32535,18 +32842,18 @@ function scheduleAttachmentMaintenance(rootDir, opts) {
32535
32842
  return run;
32536
32843
  }
32537
32844
  async function ensureAttachmentRootDir(workspaceDir) {
32538
- const workspaceRoot = path3.resolve(workspaceDir);
32539
- const parallDir = path3.join(workspaceRoot, ".parall");
32845
+ const workspaceRoot = path4.resolve(workspaceDir);
32846
+ const parallDir = path4.join(workspaceRoot, ".parall");
32540
32847
  const rootDir = attachmentRootDir(workspaceRoot);
32541
- await fs3.mkdir(workspaceRoot, { recursive: true });
32848
+ await fs4.mkdir(workspaceRoot, { recursive: true });
32542
32849
  await ensurePathIsNotSymlink(parallDir);
32543
- await fs3.mkdir(parallDir, { recursive: true, mode: 448 });
32850
+ await fs4.mkdir(parallDir, { recursive: true, mode: 448 });
32544
32851
  await ensurePathIsNotSymlink(parallDir);
32545
32852
  await ensurePathIsNotSymlink(rootDir);
32546
- await fs3.mkdir(rootDir, { recursive: true, mode: 448 });
32853
+ await fs4.mkdir(rootDir, { recursive: true, mode: 448 });
32547
32854
  await ensurePathIsNotSymlink(rootDir);
32548
- const realWorkspace = await fs3.realpath(workspaceRoot);
32549
- const realRoot = await fs3.realpath(rootDir);
32855
+ const realWorkspace = await fs4.realpath(workspaceRoot);
32856
+ const realRoot = await fs4.realpath(rootDir);
32550
32857
  if (!isPathInside(realRoot, realWorkspace)) {
32551
32858
  throw new Error(`attachment root escapes workspace: ${rootDir}`);
32552
32859
  }
@@ -32554,7 +32861,7 @@ async function ensureAttachmentRootDir(workspaceDir) {
32554
32861
  }
32555
32862
  async function ensurePathIsNotSymlink(filePath) {
32556
32863
  try {
32557
- const stat = await fs3.lstat(filePath);
32864
+ const stat = await fs4.lstat(filePath);
32558
32865
  if (stat.isSymbolicLink()) {
32559
32866
  throw new Error(`refusing to use symlinked attachment path ${filePath}`);
32560
32867
  }
@@ -32565,8 +32872,8 @@ async function ensurePathIsNotSymlink(filePath) {
32565
32872
  }
32566
32873
  }
32567
32874
  function isPathInside(childPath, parentPath) {
32568
- const rel = path3.relative(parentPath, childPath);
32569
- return rel === "" || !!rel && !rel.startsWith("..") && !path3.isAbsolute(rel);
32875
+ const rel = path4.relative(parentPath, childPath);
32876
+ return rel === "" || !!rel && !rel.startsWith("..") && !path4.isAbsolute(rel);
32570
32877
  }
32571
32878
  async function existingUsableFile(filePath, expectedSize, rootDir) {
32572
32879
  try {
@@ -32577,30 +32884,30 @@ async function existingUsableFile(filePath, expectedSize, rootDir) {
32577
32884
  }
32578
32885
  }
32579
32886
  async function localFileStatInsideRoot(filePath, rootDir) {
32580
- const stat = await fs3.lstat(filePath);
32887
+ const stat = await fs4.lstat(filePath);
32581
32888
  if (stat.isSymbolicLink()) {
32582
32889
  throw new Error(`refusing to use symlinked attachment file ${filePath}`);
32583
32890
  }
32584
32891
  if (!stat.isFile()) {
32585
32892
  throw new Error(`attachment path is not a file ${filePath}`);
32586
32893
  }
32587
- const realRoot = await fs3.realpath(rootDir);
32588
- const realFile = await fs3.realpath(filePath);
32894
+ const realRoot = await fs4.realpath(rootDir);
32895
+ const realFile = await fs4.realpath(filePath);
32589
32896
  if (!isPathInside(realFile, realRoot)) {
32590
32897
  throw new Error(`attachment file escapes workspace: ${filePath}`);
32591
32898
  }
32592
32899
  return stat;
32593
32900
  }
32594
32901
  async function localDirectoryStatInsideRoot(dirPath, rootDir) {
32595
- const stat = await fs3.lstat(dirPath);
32902
+ const stat = await fs4.lstat(dirPath);
32596
32903
  if (stat.isSymbolicLink()) {
32597
32904
  throw new Error(`refusing to use symlinked attachment directory ${dirPath}`);
32598
32905
  }
32599
32906
  if (!stat.isDirectory()) {
32600
32907
  throw new Error(`attachment path is not a directory ${dirPath}`);
32601
32908
  }
32602
- const realRoot = await fs3.realpath(rootDir);
32603
- const realDir = await fs3.realpath(dirPath);
32909
+ const realRoot = await fs4.realpath(rootDir);
32910
+ const realDir = await fs4.realpath(dirPath);
32604
32911
  if (!isPathInside(realDir, realRoot)) {
32605
32912
  throw new Error(`attachment directory escapes workspace: ${dirPath}`);
32606
32913
  }
@@ -32608,7 +32915,7 @@ async function localDirectoryStatInsideRoot(dirPath, rootDir) {
32608
32915
  }
32609
32916
  async function openLocalFileInsideRoot(filePath, rootDir) {
32610
32917
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
32611
- const file = await fs3.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
32918
+ const file = await fs4.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
32612
32919
  let keepOpen = false;
32613
32920
  try {
32614
32921
  const openedStat = await file.stat();
@@ -32624,8 +32931,8 @@ async function openLocalFileInsideRoot(filePath, rootDir) {
32624
32931
  }
32625
32932
  }
32626
32933
  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);
32934
+ await localDirectoryStatInsideRoot(path4.dirname(filePath), rootDir);
32935
+ const file = await fs4.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
32629
32936
  let keepOpen = false;
32630
32937
  try {
32631
32938
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
@@ -32650,7 +32957,7 @@ async function assertLocalFileIdentity(filePath, rootDir, expected) {
32650
32957
  async function removeLocalFileIfInside(filePath, rootDir) {
32651
32958
  try {
32652
32959
  await localFileStatInsideRoot(filePath, rootDir);
32653
- await fs3.rm(filePath, { force: true });
32960
+ await fs4.rm(filePath, { force: true });
32654
32961
  } catch {
32655
32962
  }
32656
32963
  }
@@ -32663,7 +32970,7 @@ function sameFile(a, b) {
32663
32970
  async function cleanupOldAttachmentFiles(rootDir, ttlMs, log, preserveDirs) {
32664
32971
  let entries;
32665
32972
  try {
32666
- entries = await fs3.readdir(rootDir, { withFileTypes: true });
32973
+ entries = await fs4.readdir(rootDir, { withFileTypes: true });
32667
32974
  } catch {
32668
32975
  return;
32669
32976
  }
@@ -32671,15 +32978,15 @@ async function cleanupOldAttachmentFiles(rootDir, ttlMs, log, preserveDirs) {
32671
32978
  await Promise.all(entries.map(async (entry) => {
32672
32979
  if (!entry.isDirectory())
32673
32980
  return;
32674
- const fullPath = path3.join(rootDir, entry.name);
32981
+ const fullPath = path4.join(rootDir, entry.name);
32675
32982
  try {
32676
- if (preserveDirs?.has(path3.resolve(fullPath)))
32983
+ if (preserveDirs?.has(path4.resolve(fullPath)))
32677
32984
  return;
32678
- const stat = await fs3.lstat(fullPath);
32985
+ const stat = await fs4.lstat(fullPath);
32679
32986
  if (!stat.isDirectory())
32680
32987
  return;
32681
32988
  if (stat.mtimeMs < cutoff) {
32682
- await fs3.rm(fullPath, { recursive: true, force: true });
32989
+ await fs4.rm(fullPath, { recursive: true, force: true });
32683
32990
  }
32684
32991
  } catch (err) {
32685
32992
  log?.warn?.(`agent-core: failed to clean attachment temp dir ${fullPath}: ${String(err)}`);
@@ -32691,7 +32998,7 @@ async function pruneAttachmentCache(rootDir, maxBytes, log, preserveDirs) {
32691
32998
  return;
32692
32999
  let entries;
32693
33000
  try {
32694
- entries = await fs3.readdir(rootDir, { withFileTypes: true });
33001
+ entries = await fs4.readdir(rootDir, { withFileTypes: true });
32695
33002
  } catch {
32696
33003
  return;
32697
33004
  }
@@ -32700,9 +33007,9 @@ async function pruneAttachmentCache(rootDir, maxBytes, log, preserveDirs) {
32700
33007
  for (const entry of entries) {
32701
33008
  if (!entry.isDirectory())
32702
33009
  continue;
32703
- const fullPath = path3.join(rootDir, entry.name);
33010
+ const fullPath = path4.join(rootDir, entry.name);
32704
33011
  try {
32705
- const stat = await fs3.lstat(fullPath);
33012
+ const stat = await fs4.lstat(fullPath);
32706
33013
  if (!stat.isDirectory())
32707
33014
  continue;
32708
33015
  const size = await directorySize(fullPath);
@@ -32718,10 +33025,10 @@ async function pruneAttachmentCache(rootDir, maxBytes, log, preserveDirs) {
32718
33025
  for (const dir of dirs) {
32719
33026
  if (total <= maxBytes)
32720
33027
  break;
32721
- if (preserveDirs?.has(path3.resolve(dir.path)))
33028
+ if (preserveDirs?.has(path4.resolve(dir.path)))
32722
33029
  continue;
32723
33030
  try {
32724
- await fs3.rm(dir.path, { recursive: true, force: true });
33031
+ await fs4.rm(dir.path, { recursive: true, force: true });
32725
33032
  total -= dir.size;
32726
33033
  } catch (err) {
32727
33034
  log?.warn?.(`agent-core: failed to prune attachment cache dir ${dir.path}: ${String(err)}`);
@@ -32730,12 +33037,12 @@ async function pruneAttachmentCache(rootDir, maxBytes, log, preserveDirs) {
32730
33037
  }
32731
33038
  async function directorySize(dirPath) {
32732
33039
  let total = 0;
32733
- const entries = await fs3.readdir(dirPath, { withFileTypes: true });
33040
+ const entries = await fs4.readdir(dirPath, { withFileTypes: true });
32734
33041
  for (const entry of entries) {
32735
- const fullPath = path3.join(dirPath, entry.name);
33042
+ const fullPath = path4.join(dirPath, entry.name);
32736
33043
  let stat;
32737
33044
  try {
32738
- stat = await fs3.lstat(fullPath);
33045
+ stat = await fs4.lstat(fullPath);
32739
33046
  } catch {
32740
33047
  continue;
32741
33048
  }
@@ -32750,10 +33057,10 @@ async function directorySize(dirPath) {
32750
33057
  return total;
32751
33058
  }
32752
33059
  function activeDirsForRoot(rootDir) {
32753
- const root = path3.resolve(rootDir);
33060
+ const root = path4.resolve(rootDir);
32754
33061
  const dirs = /* @__PURE__ */ new Set();
32755
33062
  for (const dir of activeAttachmentDirs) {
32756
- if (dir === root || dir.startsWith(`${root}${path3.sep}`)) {
33063
+ if (dir === root || dir.startsWith(`${root}${path4.sep}`)) {
32757
33064
  dirs.add(dir);
32758
33065
  }
32759
33066
  }
@@ -32850,9 +33157,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
32850
33157
  }
32851
33158
  writtenStat = await file.stat();
32852
33159
  await closeFile();
32853
- await localDirectoryStatInsideRoot(path3.dirname(filePath), rootDir);
33160
+ await localDirectoryStatInsideRoot(path4.dirname(filePath), rootDir);
32854
33161
  await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
32855
- await fs3.rename(tmpPath, filePath);
33162
+ await fs4.rename(tmpPath, filePath);
32856
33163
  completed = true;
32857
33164
  return written;
32858
33165
  } finally {
@@ -32868,9 +33175,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
32868
33175
  }
32869
33176
  }
32870
33177
  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;
33178
+ const safeName = sanitizePathSegment(path4.basename(fileName || attachmentId));
33179
+ const ext = path4.extname(safeName) || extensionForMime(mimeType);
33180
+ const stem = path4.basename(safeName, path4.extname(safeName)) || attachmentId;
32874
33181
  return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
32875
33182
  }
32876
33183
  function extensionForMime(mimeType) {
@@ -32936,7 +33243,7 @@ function parseContentLength(value) {
32936
33243
  // dist/gateway.js
32937
33244
  import * as crypto2 from "node:crypto";
32938
33245
  import * as os2 from "node:os";
32939
- import * as path7 from "node:path";
33246
+ import * as path8 from "node:path";
32940
33247
 
32941
33248
  // dist/runtime.js
32942
33249
  var runtime = null;
@@ -32994,15 +33301,27 @@ function buildOrchestratorSessionKey(accountId) {
32994
33301
  }
32995
33302
 
32996
33303
  // dist/config-manager.js
32997
- import * as fs4 from "node:fs";
32998
- import * as path4 from "node:path";
33304
+ import * as fs5 from "node:fs";
33305
+ import * as path5 from "node:path";
33306
+ var currentCapabilities = [];
33307
+ function getChannelCapabilityFragments() {
33308
+ return currentCapabilities.map((c) => c.fragment);
33309
+ }
33310
+ function getChannelCapabilityKeys() {
33311
+ return currentCapabilities.map((c) => c.key);
33312
+ }
33313
+ function applyChannelCapabilitySnapshot(stateDir, config, log) {
33314
+ const caps = extractCapabilities(config);
33315
+ materializeChannelCapabilities(stateDir, caps, log);
33316
+ currentCapabilities = caps;
33317
+ }
32999
33318
  var CACHE_FILENAME = "parall-platform-config.json";
33000
33319
  function cachePath(stateDir) {
33001
- return path4.join(stateDir, CACHE_FILENAME);
33320
+ return path5.join(stateDir, CACHE_FILENAME);
33002
33321
  }
33003
33322
  function loadCachedConfig(stateDir) {
33004
33323
  try {
33005
- const raw = fs4.readFileSync(cachePath(stateDir), "utf-8");
33324
+ const raw = fs5.readFileSync(cachePath(stateDir), "utf-8");
33006
33325
  return JSON.parse(raw);
33007
33326
  } catch {
33008
33327
  return null;
@@ -33016,14 +33335,14 @@ function saveCachedConfig(stateDir, config) {
33016
33335
  };
33017
33336
  const filePath = cachePath(stateDir);
33018
33337
  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);
33338
+ fs5.mkdirSync(path5.dirname(filePath), { recursive: true });
33339
+ fs5.writeFileSync(tmpPath, JSON.stringify(cached, null, 2), "utf-8");
33340
+ fs5.renameSync(tmpPath, filePath);
33022
33341
  }
33023
33342
  function applyToOpenClawConfig(configPath, platformConfig, credentials) {
33024
33343
  let existing = {};
33025
33344
  try {
33026
- const raw = fs4.readFileSync(configPath, "utf-8");
33345
+ const raw = fs5.readFileSync(configPath, "utf-8");
33027
33346
  existing = JSON.parse(raw);
33028
33347
  } catch {
33029
33348
  }
@@ -33095,9 +33414,9 @@ function applyToOpenClawConfig(configPath, platformConfig, credentials) {
33095
33414
  agents.defaults = cleanedExisting;
33096
33415
  existing.agents = agents;
33097
33416
  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);
33417
+ fs5.mkdirSync(path5.dirname(configPath), { recursive: true });
33418
+ fs5.writeFileSync(tmpPath, JSON.stringify(existing, null, 2), "utf-8");
33419
+ fs5.renameSync(tmpPath, configPath);
33101
33420
  }
33102
33421
  async function fetchAndApplyPlatformConfig(opts) {
33103
33422
  const { client, stateDir, configPath, credentials, log } = opts;
@@ -33109,6 +33428,7 @@ async function fetchAndApplyPlatformConfig(opts) {
33109
33428
  if (cached) {
33110
33429
  log?.warn(`platform config fetch failed, using cached version ${cached.version}: ${String(err)}`);
33111
33430
  applyToOpenClawConfig(configPath, cached.config, credentials);
33431
+ applyChannelCapabilitySnapshot(stateDir, cached.config, log);
33112
33432
  return;
33113
33433
  }
33114
33434
  log?.error(`platform config fetch failed and no cache available: ${String(err)}`);
@@ -33118,6 +33438,7 @@ async function fetchAndApplyPlatformConfig(opts) {
33118
33438
  log?.info("platform config unchanged (304)");
33119
33439
  if (cached) {
33120
33440
  applyToOpenClawConfig(configPath, cached.config, credentials);
33441
+ applyChannelCapabilitySnapshot(stateDir, cached.config, log);
33121
33442
  }
33122
33443
  return;
33123
33444
  }
@@ -33126,17 +33447,19 @@ async function fetchAndApplyPlatformConfig(opts) {
33126
33447
  log?.error(`platform config schema_version ${fresh.schema_version} is newer than supported (${SUPPORTED_SCHEMA_VERSION}), keeping current config`);
33127
33448
  if (cached) {
33128
33449
  applyToOpenClawConfig(configPath, cached.config, credentials);
33450
+ applyChannelCapabilitySnapshot(stateDir, cached.config, log);
33129
33451
  }
33130
33452
  return;
33131
33453
  }
33132
33454
  log?.info(`platform config updated to version ${fresh.version}`);
33133
33455
  saveCachedConfig(stateDir, fresh);
33456
+ applyChannelCapabilitySnapshot(stateDir, fresh.config, log);
33134
33457
  applyToOpenClawConfig(configPath, fresh.config, credentials);
33135
33458
  }
33136
33459
 
33137
33460
  // dist/wiki-helper.js
33138
33461
  import { spawn, spawnSync } from "node:child_process";
33139
- import path5 from "node:path";
33462
+ import path6 from "node:path";
33140
33463
  var DEFAULT_SYNC_TIMEOUT_MS = 9e4;
33141
33464
  var DEFAULT_WATCH_INTERVAL_SEC = 30;
33142
33465
  function isCommandMissing(error) {
@@ -33151,7 +33474,7 @@ function resolveParallCli() {
33151
33474
  return _cli;
33152
33475
  }
33153
33476
  function resolveMountRoot(stateDir) {
33154
- return process.env.PRLL_WIKI_MOUNT_ROOT?.trim() || path5.join(stateDir, "workspace");
33477
+ return process.env.PRLL_WIKI_MOUNT_ROOT?.trim() || path6.join(stateDir, "workspace");
33155
33478
  }
33156
33479
  function resolveWatchIntervalSec() {
33157
33480
  const raw = process.env.PRLL_WIKI_REFRESH_INTERVAL_SEC?.trim();
@@ -33266,8 +33589,8 @@ async function startWikiHelper(params) {
33266
33589
 
33267
33590
  // dist/oc-session.js
33268
33591
  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";
33592
+ import { existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "node:fs";
33593
+ import { join as join5, resolve as resolve2 } from "node:path";
33271
33594
  var CURRENT_SESSION_VERSION = 3;
33272
33595
  function generateId(existing) {
33273
33596
  for (let i = 0; i < 100; i++) {
@@ -33278,9 +33601,9 @@ function generateId(existing) {
33278
33601
  return randomUUID();
33279
33602
  }
33280
33603
  function loadEntries(filePath) {
33281
- if (!existsSync2(filePath))
33604
+ if (!existsSync3(filePath))
33282
33605
  return [];
33283
- const lines = readFileSync4(filePath, "utf-8").trim().split("\n");
33606
+ const lines = readFileSync5(filePath, "utf-8").trim().split("\n");
33284
33607
  const entries = [];
33285
33608
  for (const line of lines) {
33286
33609
  if (!line.trim())
@@ -33359,8 +33682,8 @@ var SessionManager = class _SessionManager {
33359
33682
  constructor(cwd, sessionDir, sessionFile) {
33360
33683
  this.cwd = cwd;
33361
33684
  this.sessionDir = sessionDir;
33362
- if (sessionDir && !existsSync2(sessionDir)) {
33363
- mkdirSync4(sessionDir, { recursive: true });
33685
+ if (sessionDir && !existsSync3(sessionDir)) {
33686
+ mkdirSync5(sessionDir, { recursive: true });
33364
33687
  }
33365
33688
  if (sessionFile) {
33366
33689
  this.load(sessionFile);
@@ -33371,7 +33694,7 @@ var SessionManager = class _SessionManager {
33371
33694
  // -- Init / load -----------------------------------------------------------
33372
33695
  load(file) {
33373
33696
  this.sessionFile = resolve2(file);
33374
- if (!existsSync2(this.sessionFile)) {
33697
+ if (!existsSync3(this.sessionFile)) {
33375
33698
  const p = this.sessionFile;
33376
33699
  this.initEmpty();
33377
33700
  this.sessionFile = p;
@@ -33413,7 +33736,7 @@ var SessionManager = class _SessionManager {
33413
33736
  this.leafId = null;
33414
33737
  this.flushed = false;
33415
33738
  const ts = timestamp.replace(/[:.]/g, "-");
33416
- this.sessionFile = join4(this.sessionDir, `${ts}_${this.sessionId}.jsonl`);
33739
+ this.sessionFile = join5(this.sessionDir, `${ts}_${this.sessionId}.jsonl`);
33417
33740
  }
33418
33741
  buildIndex() {
33419
33742
  this.byId.clear();
@@ -33440,7 +33763,7 @@ var SessionManager = class _SessionManager {
33440
33763
  rewrite() {
33441
33764
  if (!this.sessionFile)
33442
33765
  return;
33443
- writeFileSync3(this.sessionFile, this.fileEntries.map((e) => JSON.stringify(e)).join("\n") + "\n");
33766
+ writeFileSync4(this.sessionFile, this.fileEntries.map((e) => JSON.stringify(e)).join("\n") + "\n");
33444
33767
  }
33445
33768
  // -- Public accessors ------------------------------------------------------
33446
33769
  getLeafId() {
@@ -33460,14 +33783,14 @@ var SessionManager = class _SessionManager {
33460
33783
  }
33461
33784
  // -- Branching -------------------------------------------------------------
33462
33785
  getBranch(fromId) {
33463
- const path8 = [];
33786
+ const path9 = [];
33464
33787
  const startId = fromId ?? this.leafId;
33465
33788
  let current = startId ? this.byId.get(startId) : void 0;
33466
33789
  while (current) {
33467
- path8.unshift(current);
33790
+ path9.unshift(current);
33468
33791
  current = current.parentId ? this.byId.get(current.parentId) : void 0;
33469
33792
  }
33470
- return path8;
33793
+ return path9;
33471
33794
  }
33472
33795
  createBranchedSession(leafId) {
33473
33796
  const branch = this.getBranch(leafId);
@@ -33477,7 +33800,7 @@ var SessionManager = class _SessionManager {
33477
33800
  const newId = randomUUID();
33478
33801
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
33479
33802
  const ts = timestamp.replace(/[:.]/g, "-");
33480
- const newFile = join4(this.sessionDir, `${ts}_${newId}.jsonl`);
33803
+ const newFile = join5(this.sessionDir, `${ts}_${newId}.jsonl`);
33481
33804
  const header = {
33482
33805
  type: "session",
33483
33806
  version: CURRENT_SESSION_VERSION,
@@ -33523,50 +33846,50 @@ var SessionManager = class _SessionManager {
33523
33846
  return newFile;
33524
33847
  }
33525
33848
  // -- Factory ---------------------------------------------------------------
33526
- static open(path8) {
33527
- const entries = loadEntries(path8);
33849
+ static open(path9) {
33850
+ const entries = loadEntries(path9);
33528
33851
  const header = entries.find((e) => e.type === "session");
33529
33852
  const cwd = header?.cwd ?? process.cwd();
33530
- const dir = resolve2(path8, "..");
33531
- return new _SessionManager(cwd, dir, path8);
33853
+ const dir = resolve2(path9, "..");
33854
+ return new _SessionManager(cwd, dir, path9);
33532
33855
  }
33533
33856
  };
33534
33857
 
33535
33858
  // dist/fork.js
33536
- import * as fs5 from "node:fs";
33537
- import * as path6 from "node:path";
33859
+ import * as fs6 from "node:fs";
33860
+ import * as path7 from "node:path";
33538
33861
  import * as crypto from "node:crypto";
33539
33862
  function readStoreEntry(sessionsDir, sessionKey) {
33540
- const storeFile = path6.join(sessionsDir, "sessions.json");
33863
+ const storeFile = path7.join(sessionsDir, "sessions.json");
33541
33864
  try {
33542
- const store = JSON.parse(fs5.readFileSync(storeFile, "utf-8"));
33865
+ const store = JSON.parse(fs6.readFileSync(storeFile, "utf-8"));
33543
33866
  return store[sessionKey] ?? store[sessionKey.toLowerCase()] ?? null;
33544
33867
  } catch {
33545
33868
  return null;
33546
33869
  }
33547
33870
  }
33548
33871
  function writeStoreEntry(sessionsDir, sessionKey, entry) {
33549
- const storeFile = path6.join(sessionsDir, "sessions.json");
33872
+ const storeFile = path7.join(sessionsDir, "sessions.json");
33550
33873
  try {
33551
33874
  let store = {};
33552
33875
  try {
33553
- store = JSON.parse(fs5.readFileSync(storeFile, "utf-8"));
33876
+ store = JSON.parse(fs6.readFileSync(storeFile, "utf-8"));
33554
33877
  } catch {
33555
33878
  }
33556
33879
  store[sessionKey.toLowerCase()] = entry;
33557
- fs5.writeFileSync(storeFile, JSON.stringify(store, null, 2), { encoding: "utf-8" });
33880
+ fs6.writeFileSync(storeFile, JSON.stringify(store, null, 2), { encoding: "utf-8" });
33558
33881
  return true;
33559
33882
  } catch {
33560
33883
  return false;
33561
33884
  }
33562
33885
  }
33563
33886
  function deleteStoreEntry(sessionsDir, sessionKey) {
33564
- const storeFile = path6.join(sessionsDir, "sessions.json");
33887
+ const storeFile = path7.join(sessionsDir, "sessions.json");
33565
33888
  try {
33566
- const store = JSON.parse(fs5.readFileSync(storeFile, "utf-8"));
33889
+ const store = JSON.parse(fs6.readFileSync(storeFile, "utf-8"));
33567
33890
  delete store[sessionKey];
33568
33891
  delete store[sessionKey.toLowerCase()];
33569
- fs5.writeFileSync(storeFile, JSON.stringify(store, null, 2), { encoding: "utf-8" });
33892
+ fs6.writeFileSync(storeFile, JSON.stringify(store, null, 2), { encoding: "utf-8" });
33570
33893
  } catch {
33571
33894
  }
33572
33895
  }
@@ -33578,17 +33901,17 @@ function resolveTranscriptFile(sessionsDir, sessionKey) {
33578
33901
  if (!entry?.sessionId)
33579
33902
  return null;
33580
33903
  if (entry.sessionFile) {
33581
- const resolved = path6.isAbsolute(entry.sessionFile) ? entry.sessionFile : path6.join(sessionsDir, entry.sessionFile);
33582
- if (fs5.existsSync(resolved))
33904
+ const resolved = path7.isAbsolute(entry.sessionFile) ? entry.sessionFile : path7.join(sessionsDir, entry.sessionFile);
33905
+ if (fs6.existsSync(resolved))
33583
33906
  return resolved;
33584
33907
  }
33585
- const conventional = path6.join(sessionsDir, `${entry.sessionId}.jsonl`);
33586
- if (fs5.existsSync(conventional))
33908
+ const conventional = path7.join(sessionsDir, `${entry.sessionId}.jsonl`);
33909
+ if (fs6.existsSync(conventional))
33587
33910
  return conventional;
33588
33911
  try {
33589
- const files = fs5.readdirSync(sessionsDir);
33912
+ const files = fs6.readdirSync(sessionsDir);
33590
33913
  const match = files.find((file) => file.includes(entry.sessionId) && file.endsWith(".jsonl"));
33591
- return match ? path6.join(sessionsDir, match) : null;
33914
+ return match ? path7.join(sessionsDir, match) : null;
33592
33915
  } catch {
33593
33916
  return null;
33594
33917
  }
@@ -33599,7 +33922,7 @@ function resolveSessionId(sessionsDir, sessionKey) {
33599
33922
  }
33600
33923
  function forkOrchestratorSession(opts) {
33601
33924
  const { orchestratorSessionKey, accountId, transcriptFile, sessionsDir } = opts;
33602
- if (!fs5.existsSync(transcriptFile))
33925
+ if (!fs6.existsSync(transcriptFile))
33603
33926
  return null;
33604
33927
  try {
33605
33928
  const manager = SessionManager.open(transcriptFile);
@@ -33619,7 +33942,7 @@ function forkOrchestratorSession(opts) {
33619
33942
  sessionId = crypto.randomUUID();
33620
33943
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
33621
33944
  const fileTimestamp = timestamp.replace(/[:.]/g, "-");
33622
- sessionFile = path6.join(manager.getSessionDir(), `${fileTimestamp}_${sessionId}.jsonl`);
33945
+ sessionFile = path7.join(manager.getSessionDir(), `${fileTimestamp}_${sessionId}.jsonl`);
33623
33946
  const header = {
33624
33947
  type: "session",
33625
33948
  version: CURRENT_SESSION_VERSION,
@@ -33628,7 +33951,7 @@ function forkOrchestratorSession(opts) {
33628
33951
  cwd: manager.getCwd(),
33629
33952
  parentSession: transcriptFile
33630
33953
  };
33631
- fs5.writeFileSync(sessionFile, `${JSON.stringify(header)}
33954
+ fs6.writeFileSync(sessionFile, `${JSON.stringify(header)}
33632
33955
  `, {
33633
33956
  encoding: "utf-8",
33634
33957
  mode: 384,
@@ -33638,7 +33961,7 @@ function forkOrchestratorSession(opts) {
33638
33961
  const forkSessionKey = `${orchestratorSessionKey}:fork:${sessionId}`;
33639
33962
  const wrote = writeStoreEntry(sessionsDir, forkSessionKey, {
33640
33963
  sessionId,
33641
- sessionFile: path6.relative(sessionsDir, sessionFile),
33964
+ sessionFile: path7.relative(sessionsDir, sessionFile),
33642
33965
  updatedAt: Date.now(),
33643
33966
  spawnedBy: orchestratorSessionKey,
33644
33967
  parentSessionKey: orchestratorSessionKey,
@@ -33653,8 +33976,8 @@ function forkOrchestratorSession(opts) {
33653
33976
  }
33654
33977
  function cleanupForkSession(opts) {
33655
33978
  try {
33656
- if (fs5.existsSync(opts.sessionFile)) {
33657
- fs5.unlinkSync(opts.sessionFile);
33979
+ if (fs6.existsSync(opts.sessionFile)) {
33980
+ fs6.unlinkSync(opts.sessionFile);
33658
33981
  }
33659
33982
  } catch {
33660
33983
  }
@@ -33662,6 +33985,10 @@ function cleanupForkSession(opts) {
33662
33985
  }
33663
33986
 
33664
33987
  // dist/gateway.js
33988
+ function sessionContextFilePath(stateDir, sessionKey) {
33989
+ const fileName = Buffer.from(sessionKey).toString("base64url");
33990
+ return path8.join(stateDir, "dispatch-context", `${fileName}.json`);
33991
+ }
33665
33992
  function resolveWsUrl(account) {
33666
33993
  if (account.config.ws_url)
33667
33994
  return account.config.ws_url;
@@ -33964,8 +34291,13 @@ var parallGateway = {
33964
34291
  const telemetry = await initAgentTelemetry("parall-openclaw-agent", "openclaw");
33965
34292
  const otelLog = createOtelLogger("agent", "openclaw-agent");
33966
34293
  try {
33967
- const stateDir = process.env.OPENCLAW_STATE_DIR || path7.join(process.env.HOME || "/data", ".openclaw");
33968
- const openclawConfigPath = path7.join(stateDir, "openclaw.json");
34294
+ const stateDir = process.env.OPENCLAW_STATE_DIR || path8.join(process.env.HOME || "/data", ".openclaw");
34295
+ const openclawConfigPath = path8.join(stateDir, "openclaw.json");
34296
+ const shimDir = capabilityBinDir(stateDir);
34297
+ const currentPath = process.env.PATH ?? "";
34298
+ if (!currentPath.split(path8.delimiter).includes(shimDir)) {
34299
+ process.env.PATH = currentPath ? `${shimDir}${path8.delimiter}${currentPath}` : shimDir;
34300
+ }
33969
34301
  const configManagerOpts = {
33970
34302
  client,
33971
34303
  stateDir,
@@ -34001,7 +34333,7 @@ var parallGateway = {
34001
34333
  wsUrl
34002
34334
  });
34003
34335
  const orchestratorKey = buildOrchestratorSessionKey(ctx.accountId);
34004
- const sessionsDir = path7.join(stateDir, "agents", "main", "sessions");
34336
+ const sessionsDir = path8.join(stateDir, "agents", "main", "sessions");
34005
34337
  const workspaceDir = process.cwd();
34006
34338
  ensureLocalAttachmentGitExclude(workspaceDir);
34007
34339
  const dispatchAdapter = createOpenClawDispatchAdapter({
@@ -34026,7 +34358,22 @@ var parallGateway = {
34026
34358
  runtimeKey: orchestratorKey,
34027
34359
  runtimeRef: { hostname: os2.hostname(), pid: process.pid },
34028
34360
  dispatchAdapter,
34361
+ // Opts openclaw into the dispatch ledger (claim/fold/complete +
34362
+ // idempotent reply effects) — the same shared-gateway machinery
34363
+ // claude/codex ride; openclaw stays buffer-only (no mid-turn steer),
34364
+ // which the ledger does not require. Replies already flow through
34365
+ // @parall/cli, which reads PRLL_CONTEXT_DIR (injected in hooks.ts)
34366
+ // to bind dispatch_lane + reply effect keys.
34367
+ // Design: docs/engineering-design/dispatch-convergence-design.md §7 (S2).
34368
+ dispatchContextDir: dispatchLaneContextDir(stateDir),
34369
+ // Per-session context file (PRLL_CONTEXT_FILE contract) — the CLI's
34370
+ // TYPED dispatch binding (parall tasks update → task_update effect)
34371
+ // reads lane/event/task fields from this file, not the lane dir.
34372
+ contextFilePathForSession: (sessionKey) => sessionContextFilePath(stateDir, sessionKey),
34029
34373
  log: otelLog,
34374
+ // Live capability view for hint routing: the channel reply hint
34375
+ // points at the vendor CLI only while the grant is active.
34376
+ getCapabilityKeys: getChannelCapabilityKeys,
34030
34377
  shutdownDeadlineMs: parseShutdownDeadlineMs(process.env.PRLL_SHUTDOWN_DEADLINE_MS),
34031
34378
  forkDeadlineMs: parseForkDeadlineMs(process.env.PRLL_FORK_DEADLINE_MS),
34032
34379
  dispatchDeadlineMs: parseDispatchDeadlineMs(process.env.PRLL_DISPATCH_DEADLINE_MS),
@@ -34046,7 +34393,13 @@ var parallGateway = {
34046
34393
  runtimeRef: { hostname: os2.hostname(), pid: process.pid },
34047
34394
  wikiMountRoot,
34048
34395
  ws,
34049
- orchestratorSessionKey: orchestratorKey
34396
+ orchestratorSessionKey: orchestratorKey,
34397
+ dispatchContextDir: dispatchLaneContextDir(stateDir),
34398
+ contextFilePathForSession: (sessionKey) => sessionContextFilePath(stateDir, sessionKey),
34399
+ // Lease-renewal bridge: openclaw tool calls flow through hooks,
34400
+ // not the RuntimeEvent stream, so hook activity must renew the
34401
+ // ledger lanes or a long exec outlives the lease (STALE_LANE).
34402
+ touchRuntimeActivity: (sessionKey) => gateway.touchRuntimeActivity(sessionKey)
34050
34403
  });
34051
34404
  },
34052
34405
  onSessionBinding: async ({ sessionKey, agentSessionId }) => {
@@ -34220,15 +34573,52 @@ function registerParallHooks(api) {
34220
34573
  buildIdentity(getAgentIdentity()),
34221
34574
  PRLL_CHANNEL_CONTEXT,
34222
34575
  PRLL_BEHAVIOR,
34223
- PRLL_REFERENCE_GUIDE
34576
+ PRLL_REFERENCE_GUIDE,
34577
+ // Channel-capability declarations (platform-config
34578
+ // agents.capabilities[]). Evaluated on EVERY prompt build, so a
34579
+ // capability grant/revocation reaches the next turn without any
34580
+ // restart — the openclaw analogue of the CLI bridges' prompt-file
34581
+ // rewrite + respawn.
34582
+ ...getChannelCapabilityFragments()
34224
34583
  ].join("\n\n")
34225
34584
  };
34226
34585
  });
34227
34586
  const pendingSendCalls = /* @__PURE__ */ new Map();
34587
+ const laneRenewals = /* @__PURE__ */ new Map();
34588
+ const LANE_RENEW_INTERVAL_MS = 18e4;
34589
+ const beginToolRenewal = (sessionKey) => {
34590
+ const accountId = extractAccountIdFromSessionKey(sessionKey);
34591
+ const state = accountId ? getParallAccountState(accountId) : void 0;
34592
+ if (!state?.touchRuntimeActivity)
34593
+ return;
34594
+ state.touchRuntimeActivity(sessionKey);
34595
+ const entry = laneRenewals.get(sessionKey) ?? { count: 0 };
34596
+ entry.count++;
34597
+ if (!entry.timer) {
34598
+ entry.timer = setInterval(() => state.touchRuntimeActivity?.(sessionKey), LANE_RENEW_INTERVAL_MS);
34599
+ entry.timer.unref?.();
34600
+ }
34601
+ laneRenewals.set(sessionKey, entry);
34602
+ };
34603
+ const endToolRenewal = (sessionKey) => {
34604
+ const entry = laneRenewals.get(sessionKey);
34605
+ if (entry) {
34606
+ entry.count--;
34607
+ if (entry.count <= 0) {
34608
+ if (entry.timer)
34609
+ clearInterval(entry.timer);
34610
+ laneRenewals.delete(sessionKey);
34611
+ }
34612
+ }
34613
+ const accountId = extractAccountIdFromSessionKey(sessionKey);
34614
+ const state = accountId ? getParallAccountState(accountId) : void 0;
34615
+ state?.touchRuntimeActivity?.(sessionKey);
34616
+ };
34228
34617
  api.on("before_tool_call", async (event, ctx) => {
34229
34618
  const sessionKey = ctx.sessionKey;
34230
34619
  if (sessionKey) {
34231
34620
  recordToolCall(sessionKey);
34621
+ beginToolRenewal(sessionKey);
34232
34622
  if (event.toolName === "exec" && event.toolCallId) {
34233
34623
  const command = event.params?.command;
34234
34624
  if (isParallSendCommand(command)) {
@@ -34297,6 +34687,12 @@ function registerParallHooks(api) {
34297
34687
  injectedEnv.PRLL_TRIGGER_MESSAGE_ID = triggerMsgId;
34298
34688
  if (state.wikiMountRoot)
34299
34689
  injectedEnv.PRLL_WIKI_MOUNT_ROOT = state.wikiMountRoot;
34690
+ if (state.dispatchContextDir)
34691
+ injectedEnv.PRLL_CONTEXT_DIR = state.dispatchContextDir;
34692
+ if (state.contextFilePathForSession) {
34693
+ injectedEnv.PRLL_CONTEXT_FILE = state.contextFilePathForSession(sessionKey);
34694
+ }
34695
+ state.touchRuntimeActivity?.(sessionKey);
34300
34696
  injectedEnv.OPENCLAW_SESSION_KEY = sessionKey;
34301
34697
  if (event.toolCallId)
34302
34698
  injectedEnv.OPENCLAW_TOOL_CALL_ID = event.toolCallId;
@@ -34308,6 +34704,8 @@ function registerParallHooks(api) {
34308
34704
  };
34309
34705
  });
34310
34706
  api.on("after_tool_call", async (event, ctx) => {
34707
+ if (ctx.sessionKey)
34708
+ endToolRenewal(ctx.sessionKey);
34311
34709
  if (ctx.sessionKey && event.toolCallId && pendingSendCalls.delete(event.toolCallId)) {
34312
34710
  recordMessageSend(ctx.sessionKey, !event.error);
34313
34711
  }