@parall/daemon 1.42.1 → 1.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17718,9 +17718,9 @@ var require_getMachineId_linux = __commonJS({
17718
17718
  var api_1 = (init_esm(), __toCommonJS(esm_exports));
17719
17719
  async function getMachineId() {
17720
17720
  const paths = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
17721
- for (const path10 of paths) {
17721
+ for (const path11 of paths) {
17722
17722
  try {
17723
- const result = await fs_1.promises.readFile(path10, { encoding: "utf8" });
17723
+ const result = await fs_1.promises.readFile(path11, { encoding: "utf8" });
17724
17724
  return result.trim();
17725
17725
  } catch (e) {
17726
17726
  api_1.diag.debug(`error reading machine id: ${e}`);
@@ -21123,7 +21123,7 @@ function appendRootPathToUrlIfNeeded(url) {
21123
21123
  return void 0;
21124
21124
  }
21125
21125
  }
21126
- function appendResourcePathToUrl(url, path10) {
21126
+ function appendResourcePathToUrl(url, path11) {
21127
21127
  try {
21128
21128
  new URL(url);
21129
21129
  } catch (_a) {
@@ -21133,11 +21133,11 @@ function appendResourcePathToUrl(url, path10) {
21133
21133
  if (!url.endsWith("/")) {
21134
21134
  url = url + "/";
21135
21135
  }
21136
- url += path10;
21136
+ url += path11;
21137
21137
  try {
21138
21138
  new URL(url);
21139
21139
  } catch (_b) {
21140
- diag2.warn("Configuration: Provided URL appended with '" + path10 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
21140
+ diag2.warn("Configuration: Provided URL appended with '" + path11 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
21141
21141
  return void 0;
21142
21142
  }
21143
21143
  return url;
@@ -26487,719 +26487,11 @@ function laneContextFilePath(contextDir, targetUri, threadRootId) {
26487
26487
  return path.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
26488
26488
  }
26489
26489
 
26490
- // ts/agent-core/dist/session-state.js
26491
- function normalizeSessionKey(sessionKey) {
26492
- return sessionKey.toLowerCase();
26493
- }
26494
- var sessionChatIdMap = /* @__PURE__ */ new Map();
26495
- var sessionMessageIdMap = /* @__PURE__ */ new Map();
26496
- var dispatchMessageIdMap = /* @__PURE__ */ new Map();
26497
- var dispatchNoReplyMap = /* @__PURE__ */ new Map();
26498
- function setSessionChatId(sessionKey, chatId) {
26499
- sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
26500
- }
26501
- function setSessionMessageId(sessionKey, messageId) {
26502
- sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
26503
- }
26504
- function clearSessionMessageId(sessionKey) {
26505
- sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
26506
- }
26507
- function setDispatchMessageId(sessionKey, messageId) {
26508
- dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
26509
- }
26510
- function clearDispatchMessageId(sessionKey) {
26511
- dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
26512
- }
26513
- function setDispatchNoReply(sessionKey, noReply) {
26514
- dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
26515
- }
26516
- function clearDispatchNoReply(sessionKey) {
26517
- dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
26518
- }
26519
- var dispatchMetricsMap = /* @__PURE__ */ new Map();
26520
- function resetDispatchMetrics(sessionKey) {
26521
- dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
26522
- deliver_text_chunks: 0,
26523
- deliver_text_chars: 0,
26524
- message_send_attempts: 0,
26525
- message_send_successes: 0,
26526
- no_reply_called: false,
26527
- tool_call_count: 0,
26528
- started_at: Date.now()
26529
- });
26530
- }
26531
- function getDispatchMetrics(sessionKey) {
26532
- return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26533
- }
26534
- function clearDispatchMetrics(sessionKey) {
26535
- dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
26536
- }
26537
- function recordDeliverText(sessionKey, charCount) {
26538
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26539
- if (!m)
26540
- return;
26541
- m.deliver_text_chunks++;
26542
- m.deliver_text_chars += charCount;
26543
- }
26544
- function recordMessageSend(sessionKey, success) {
26545
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26546
- if (!m)
26547
- return;
26548
- m.message_send_attempts++;
26549
- if (success)
26550
- m.message_send_successes++;
26551
- }
26552
- function recordNoReply(sessionKey) {
26553
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26554
- if (!m)
26555
- return;
26556
- m.no_reply_called = true;
26557
- }
26558
- function recordToolCall(sessionKey) {
26559
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
26560
- if (!m)
26561
- return;
26562
- m.tool_call_count++;
26563
- }
26564
-
26565
- // ts/agent-core/dist/routing.js
26566
- var MAX_CONCURRENT_FORKS = 20;
26567
- var defaultRoutingStrategy = (event, state) => {
26568
- if (state.mainCurrentTargetId === event.targetId) {
26569
- return { action: "buffer-main" };
26570
- }
26571
- const existingForkKey = state.activeForks.get(event.targetId);
26572
- if (existingForkKey)
26573
- return { action: "buffer-fork", forkKey: existingForkKey };
26574
- if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
26575
- return { action: "buffer-main" };
26576
- }
26577
- return { action: "new-fork" };
26578
- };
26579
- function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
26580
- const existingForkKey = state.activeForks.get(event.targetId);
26581
- if (existingForkKey)
26582
- return { action: "buffer-fork", forkKey: existingForkKey };
26583
- if (!state.mainDispatching)
26584
- return { action: "main" };
26585
- return strategy(event, state);
26586
- }
26587
-
26588
- // ts/agent-core/dist/event-format.js
26589
- function sanitizeMeta(value) {
26590
- return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
26591
- }
26592
- function buildEventBody(event) {
26593
- const lines = [];
26594
- if (event.type === "message") {
26595
- lines.push(`[Event: message.new]`);
26596
- const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
26597
- lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
26598
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26599
- lines.push(`[Message ID: prll://${event.messageId}]`);
26600
- if (event.threadRootId) {
26601
- const threadMeta = [
26602
- `prll://${event.threadRootId}`,
26603
- event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
26604
- event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
26605
- event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
26606
- ].filter(Boolean).join(" | ");
26607
- lines.push(`[Thread: ${threadMeta}]`);
26608
- }
26609
- if (event.unreadCount != null && event.unreadCount > 1) {
26610
- const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
26611
- const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
26612
- let line = `[Unread: ${countStr} messages${sinceStr}]`;
26613
- if (event.unreadCount > 50)
26614
- line += ` \u2014 fetch recent context with --limit, not all`;
26615
- lines.push(line);
26616
- }
26617
- if (event.noReply)
26618
- lines.push(`[Hint: no_reply]`);
26619
- if (event.attachments?.length) {
26620
- for (const att of event.attachments) {
26621
- const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
26622
- lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
26623
- }
26624
- }
26625
- lines.push("", event.body);
26626
- } else if (event.type === "task_comment") {
26627
- lines.push(`[Event: task.comment.created]`);
26628
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
26629
- lines.push(`[Task: ${taskLabel}]`);
26630
- if (event.deliveryReason)
26631
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
26632
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26633
- lines.push(`[Comment ID: prll://${event.messageId}]`);
26634
- lines.push("", event.body);
26635
- } else if (event.type === "wiki_comment") {
26636
- lines.push(`[Event: wiki.comment.created]`);
26637
- const target = event.replyTargetUri ?? `prll://${event.targetId}`;
26638
- if (event.targetType === "changeset") {
26639
- lines.push(`[Wiki Changeset: ${target}]`);
26640
- } else {
26641
- lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
26642
- }
26643
- if (event.deliveryReason)
26644
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
26645
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
26646
- lines.push(`[Comment ID: prll://${event.messageId}]`);
26647
- lines.push("", event.body);
26648
- } else if (event.type === "approval") {
26649
- lines.push(`[Event: approval.decided]`);
26650
- lines.push(`[Approval: prll://${event.messageId}]`);
26651
- lines.push(`[Chat: prll://${event.targetId}]`);
26652
- lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
26653
- lines.push("", event.body);
26654
- } else if (event.type === "schedule") {
26655
- lines.push(`[Event: schedule.fired]`);
26656
- lines.push(`[Schedule: prll://${event.targetId}]`);
26657
- lines.push(`[Run: prll://${event.messageId}]`);
26658
- if (event.scheduledFireAt)
26659
- lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
26660
- if (event.attachedUri)
26661
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
26662
- lines.push("", event.body);
26663
- } else if (event.type === "channel_message") {
26664
- lines.push(`[Event: channel.message]`);
26665
- const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
26666
- const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
26667
- lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
26668
- lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
26669
- if (event.channelExternalMessageId) {
26670
- lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
26671
- }
26672
- lines.push(`[Audience: this conversation lives on ${providerLabel}, OUTSIDE Parall. Readers cannot open prll:// links, Parall cards, or internal attachments \u2014 never include them in replies. Write plain conversational text.]`);
26673
- lines.push("", event.body);
26674
- } else if (event.type === "external_trigger") {
26675
- lines.push(`[Event: external.trigger]`);
26676
- lines.push(`[Trigger: prll://${event.targetId}]`);
26677
- lines.push(`[Run: prll://${event.messageId}]`);
26678
- if (event.externalConnectionId) {
26679
- const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
26680
- lines.push(`[Connection: ${label}]`);
26681
- }
26682
- if (event.externalIngressEventId)
26683
- lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
26684
- if (event.attachedUri)
26685
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
26686
- if (event.externalConnectionSourceType) {
26687
- lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
26688
- }
26689
- if (event.externalIngressEventType) {
26690
- lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
26691
- }
26692
- lines.push("", event.body);
26693
- } else {
26694
- lines.push(`[Event: task.assigned]`);
26695
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
26696
- lines.push(`[Task: ${taskLabel}]`);
26697
- lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
26698
- lines.push("", event.body);
26699
- }
26700
- return lines.join("\n") + buildSendMessageHint(event);
26701
- }
26702
- function buildEventBodyForForkResult(event) {
26703
- return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
26704
- }
26705
- function buildSendMessageHint(event) {
26706
- if (event.noReply)
26707
- return "";
26708
- if (event.type === "wiki_comment" && event.replyTargetUri) {
26709
- const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
26710
- return `
26711
- <system-reminder>To reply on ${where}, run: \`parall comments add --target "${event.replyTargetUri}" --body "..."\` (read the thread first with \`parall comments list --target "${event.replyTargetUri}"\`). To message someone instead, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
26712
- }
26713
- if (event.targetId.startsWith("cht_")) {
26714
- if (event.threadRootId) {
26715
- return `
26716
- <system-reminder>To reply in this thread, run \`parall messages send prll://${event.targetId} --thread-root-id ${sanitizeMeta(event.threadRootId)} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
26717
- }
26718
- return `
26719
- <system-reminder>To reply, run \`parall messages send prll://${event.targetId} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
26720
- }
26721
- if (event.targetId.startsWith("tsk_")) {
26722
- return `
26723
- <system-reminder>To respond, use the CLI: \`parall tasks update\` / \`parall tasks comments add\`. To message someone, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
26724
- }
26725
- if (event.targetId.startsWith("sch_")) {
26726
- return `
26727
- <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
26728
- }
26729
- if (event.type === "channel_message") {
26730
- const clipLabel = event.channelProvider ? `the \`${event.channelProvider}\` clip's` : "your channel provider clip's";
26731
- const apiLabel = event.channelProvider ?? "external platform";
26732
- const target = event.channelExternalConversationId ? `{"chat_id": "${event.channelExternalConversationId}", "text": "..."}` : `{"chat_id": "<conversation id>", "text": "..."}`;
26733
- const threadAlt = event.channelExternalMessageId ? ` To reply in-thread to this specific message, use {"message_id": "${event.channelExternalMessageId}", "text": "..."} instead.` : "";
26734
- return `
26735
- <system-reminder>To reply, invoke ${clipLabel} \`send_message\` command with ${target} \u2014 your plain text output is NOT delivered to the external conversation.${threadAlt} The same clip's \`call\` command reaches the wider ${apiLabel} API when needed.</system-reminder>`;
26736
- }
26737
- if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
26738
- return `
26739
- <system-reminder>This external trigger is incoming-only. Your plain text output is not sent back to the external provider. To communicate in Parall, use \`parall messages send\` / \`parall dm\`; provider-specific outbound actions require a separate capability.</system-reminder>`;
26740
- }
26741
- return "";
26742
- }
26743
- function buildForkScopePrefix(event) {
26744
- const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
26745
- return `[Fork scope: You are a parallel worker forked from the main session to handle ${targetLabel}. The conversation history above belongs to the main session's in-progress dispatch \u2014 do NOT continue it or complete it, or produce external output (comments, messages) for work visible there. The main session owns its own output.
26490
+ // ts/agent-core/dist/lane-ledger.js
26491
+ import * as fs from "node:fs";
26746
26492
 
26747
- Only act on the event below within your target scope. If your event reveals findings about the main session's work, report them in your summary \u2014 do not post them externally.
26748
-
26749
- End with a brief "Fork summary" of actions taken and decisions made.]
26750
-
26751
- `;
26752
- }
26753
- function buildForkResultPrefix(results) {
26754
- if (!results.length)
26755
- return "";
26756
- const blocks = results.map((result) => {
26757
- const lines = [];
26758
- for (const body of result.eventBodies) {
26759
- lines.push(body);
26760
- }
26761
- lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
26762
- lines.push(`[Fork summary: ${result.agentSummary ? sanitizeMeta(result.agentSummary) : "No fork summary available \u2014 the fork completed without producing a text summary. Check the target chat/task for any actions the fork already took before acting."}]`);
26763
- if (result.actions.length)
26764
- lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
26765
- if (result.historyPath)
26766
- lines.push(`[Fork history: ${result.historyPath}]`);
26767
- return lines.join("\n");
26768
- });
26769
- return blocks.join("\n\n") + "\n\n---\n\n";
26770
- }
26771
-
26772
- // ts/agent-core/dist/prompt-fragments.js
26773
- var PRLL_IDENTITY_BASE = `## You on Parall
26774
-
26775
- Parall is a shared workspace where humans and agents work side by side as equals.
26776
- You are a participant here, not a service. You hold tasks, own decisions, and are
26777
- accountable for the work you take on \u2014 the same way a human teammate is.
26778
-
26779
- The people and agents around you are collaborators, not users to serve. Be honest,
26780
- be direct, and care about the outcome of the work \u2014 not just the request in front
26781
- of you.`;
26782
- function sanitizeProfileField(value) {
26783
- return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
26784
- }
26785
- function sanitizeProfileBlock(value) {
26786
- return value.replace(/\r\n?/g, "\n").trim();
26787
- }
26788
- function buildIdentity(agent) {
26789
- if (!agent)
26790
- return PRLL_IDENTITY_BASE;
26791
- const name = sanitizeProfileField(agent.displayName);
26792
- const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
26793
- lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
26794
- if (agent.description) {
26795
- const description = sanitizeProfileBlock(agent.description);
26796
- if (description) {
26797
- lines.push("", "### Your Agent Profile", "", description);
26798
- }
26799
- }
26800
- lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
26801
- return lines.join("\n");
26802
- }
26803
- var PRLL_BEHAVIOR = `## How to work here
26804
-
26805
- ### Move work forward
26806
- Don't wait for instructions. If you see the next step, take it. If something is
26807
- ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
26808
- \u2014 don't go silent. Initiative is expected.
26809
-
26810
- Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
26811
- requests, verifying something landed. When a thing needs future attention and
26812
- nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
26813
-
26814
- ### Work in the open
26815
- Nothing you do exists until the system can see it. Your progress, decisions,
26816
- blockers, and results need to live in tasks, comments, messages, or wiki pages
26817
- \u2014 otherwise the organization is blind to your work, and so is the next agent
26818
- who picks up where you left off. Leave traces as you go, not at the end.
26819
-
26820
- For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
26821
- when status materially changes, close it when done, and link the origin that
26822
- triggered it. Decompose multi-step work into subtasks and keep their statuses
26823
- current \u2014 progress should be auditable without watching the work happen.
26824
- Details: load the \`parall-tasks\` skill.
26825
-
26826
- ### Done means landed
26827
- Producing output does not complete a task. Work counts as done only when it has
26828
- cleared its remaining gates \u2014 review, merge, deployment, the requester's
26829
- verification. Until then keep the status honest (\`in_progress\` or
26830
- \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
26831
- self-reminder if nothing else will prompt follow-up). Never mark done what a
26832
- human still has to accept.
26833
-
26834
- ### Sessions, forks, and what survives
26835
- Sessions end and context compacts. Anything that must survive \u2014 decisions,
26836
- progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
26837
- read the workspace, not this conversation.
26838
-
26839
- Some events are handled by parallel fork sessions \u2014 short-lived copies of the
26840
- same agent identity with separate context. In a fork: leave a written trace of
26841
- what was done or deliberately not done (other sessions cannot see fork
26842
- context), and do not start long-running processes \u2014 they die with the fork.
26843
- When an event is marked fork-handled: do not re-handle it; verify its outcome
26844
- instead of assuming it.
26845
-
26846
- ### Communicate like a teammate
26847
- Match the conversation \u2014 concise in chat, thorough in docs, plain language over
26848
- jargon. Say what matters; stop when you're done. Don't narrate every tool call
26849
- or pad replies to seem thorough.
26850
-
26851
- Match the language of the person you're replying to. If someone writes in
26852
- Chinese, reply in Chinese. If in English, reply in English. Never force a
26853
- language switch unless explicitly asked.
26854
-
26855
- Do not promise delivery times ("in an hour", "by tonight") unless the work is
26856
- driven by an explicit schedule. Scope visibly; report when actually done.
26857
-
26858
- ### Keep topics in threads
26859
- Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
26860
- Present \u2192 that thread is the context; reply there, passing the same root as
26861
- \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
26862
- never treat it as continuing your most recent thread. The sender's newest
26863
- message is the anchor \u2014 never route a reply back into an older thread just
26864
- because the topic used to live there.
26865
-
26866
- Reply where the event lives: a thread message gets a thread reply, a
26867
- top-level message gets a top-level reply. But in group chats, your later
26868
- follow-up on that topic \u2014 progress updates, analysis, links, verification you
26869
- post afterwards \u2014 belongs in a thread rooted at the topic's message
26870
- (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
26871
- the main channel stays scannable. Post follow-up at top level only when
26872
- starting a genuinely new topic, making a channel-wide announcement, or when
26873
- explicitly asked. Never post the same update in both the thread and the main
26874
- channel \u2014 thread replies surface in the thread panel; no need to duplicate
26875
- for visibility.
26876
-
26877
- In DMs, reply top-level by default; use a thread only to continue one that
26878
- already exists.
26879
-
26880
- ### Group chats: mentions and unaddressed work
26881
- An @mention is a direct request \u2014 act on it. A group message delivered to you
26882
- without an @mention means the chat's routing lets you see the conversation:
26883
- decide whether a reply adds value; silence is the default.
26884
-
26885
- A message without an @mention is not an open invitation. Judge from context
26886
- who the work belongs to \u2014 the named domain, the topic's owner, whoever is
26887
- already on it. If it belongs to someone else, leave it. If genuinely unclear,
26888
- ask or claim in one line ("taking this unless someone else has it") before
26889
- starting \u2014 asking first beats duplicated or misdirected work.
26890
-
26891
- ### Verify before you act
26892
- Events can be redelivered \u2014 before acting, check whether it was already
26893
- handled (your own recent replies, task comments); if handled, do nothing.
26894
- Sends can fail silently, and creates can error after succeeding server-side \u2014
26895
- check the chat or entity before retrying. Never blind-retry a mutating call.
26896
-
26897
- ### Gather the full picture first
26898
- When a request is vague, an entity may already exist, or work may already be
26899
- underway \u2014 gather context before acting: search (\`parall search "..."\`),
26900
- check existing tasks/chats/wiki, read the surrounding conversation. Act on the
26901
- full picture, not the fragment that arrived in the event.
26902
-
26903
- ### Report only work that ran
26904
- If a scheduled job, scan, or tool call did not actually run \u2014 restarted
26905
- session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
26906
- or approximate results of work that did not execute.
26907
-
26908
- ### Respect what's shared
26909
- You have broad latitude inside your own work. But actions that are visible to
26910
- others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
26911
- wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
26912
- acting, unless you've been explicitly authorized.
26913
-
26914
- ### Shared workspace
26915
- Other agents share this workspace. Before starting work, check whether someone
26916
- \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
26917
-
26918
- ### Permissions and approvals
26919
- You have real permissions based on your roles (chat member/admin, org member).
26920
- If you lack permission for an action, the API returns PERMISSION_DENIED with the
26921
- \`action\` and \`resource_uri\` that were denied. The server decides whether that
26922
- action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
26923
- fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
26924
- it to ask someone with permission. If it is NOT approvable, the output says so;
26925
- ask a human with permission instead of requesting approval. A
26926
- \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
26927
- (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
26928
- \`dm\` for a user). Don't retry or work around a denial; only request approval
26929
- after an actual denial, never preemptively.
26930
-
26931
- ### When in doubt
26932
- Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
26933
- credibility is what you bring to the workspace \u2014 protect it.`;
26934
- var PRLL_REFERENCE_GUIDE = `## Parall References
26935
-
26936
- Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
26937
- entities when you create or update tasks, comments, messages, and wiki files.
26938
-
26939
- All three forms work \u2014 pick whichever fits:
26940
-
26941
- prll://tsk_abc bare URI (auto-linked)
26942
- [](prll://tsk_abc) empty context (renders resolved title)
26943
- [relevant context](prll://tsk_abc) with author annotation
26944
-
26945
- Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
26946
- resolves and renders the entity title automatically.
26947
-
26948
- ### URI format
26949
-
26950
- \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
26951
-
26952
- **Entities** \u2014 the entity ID is the authority:
26953
-
26954
- prll://usr_xxx user prll://prj_xxx project
26955
- prll://tsk_xxx task prll://wik_xxx wiki
26956
- prll://msg_xxx message prll://tcm_xxx task comment
26957
- prll://cht_xxx chat prll://ase_xxx agent session
26958
- prll://att_xxx attachment prll://sch_xxx schedule
26959
- prll://srn_xxx schedule run
26960
-
26961
- **Wiki** \u2014 path is file path, fragment is a typed anchor:
26962
-
26963
- prll://wik_xxx/docs/guide.md file
26964
- prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
26965
- prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
26966
-
26967
- Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
26968
- Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
26969
-
26970
- **Chat message range**:
26971
-
26972
- prll://cht_xxx#range=msg_01HA,msg_01HZ
26973
-
26974
- **Field access** \u2014 path selects a field (omit to reference the entity itself):
26975
-
26976
- prll://tsk_xxx/description#Implementation heading within task description
26977
-
26978
- ### Unread context
26979
-
26980
- When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
26981
- This shows messages since your last interaction \u2014 your read cursor advances after each
26982
- dispatch, so context you skip now won't appear as unread next time. Use
26983
- \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
26984
- counts (50+), fetch only recent messages rather than everything.
26985
-
26986
- Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
26987
- Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
26988
- catch up on the thread.
26989
-
26990
- ### Reading context on demand
26991
-
26992
- An event only carries the single triggering message. If you're mentioned in a
26993
- group chat and lack context, pull what you need from the chat \u2014 don't guess:
26994
-
26995
- parall messages list cht_xxx --limit 20 --before msg_xxx
26996
- parall messages get msg_xxx
26997
- parall chats get cht_xxx
26998
-
26999
- Rule of thumb: in a group chat mention, the conversation that led up to you
27000
- being called almost always matters \u2014 read it before replying. In a DM, your
27001
- session already has continuity, so skip the fetch unless something is unclear.
27002
-
27003
- Same pattern for any other entity referenced in the event: \`tasks get\`,
27004
- \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
27005
-
27006
- ### Find context with search first
27007
-
27008
- Reach for unified semantic search before paging chat history:
27009
-
27010
- parall search "pricing decision june" [--limit 10]
27011
-
27012
- It spans messages, tasks, and wiki. Page \`messages list\` only for the verbatim
27013
- recent flow of one chat, not for discovery.
27014
-
27015
- ### File attachments
27016
-
27017
- Messages may include attachments. They appear in events as:
27018
-
27019
- [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
27020
-
27021
- To download an attachment, use the CLI:
27022
-
27023
- parall files download att_xxx --output /tmp/screenshot.png
27024
-
27025
- To send a file:
27026
-
27027
- parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
27028
-
27029
- Or upload first and reuse across chats:
27030
-
27031
- parall files upload /tmp/report.pdf
27032
- parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
27033
- parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
27034
-
27035
- The \`--text\` captions above are safe short literals. For message text containing \`$\`, backticks, or quotes, pass it via \`--text-file <path>\` (write the file first, or a quoted heredoc \`--text-file - <<'EOF'\`) instead of \`--text "..."\` \u2014 inside double quotes the shell turns \`$1,000\` into \`,000\` and executes \`$(...)\`.
27036
-
27037
- ### When to reference
27038
-
27039
- - **Origin** \u2014 always link the message or task that triggered your work
27040
- - **Design docs / wiki** \u2014 link specs and guides relevant to the work
27041
- - **Related tasks** \u2014 link parent, sibling, or blocking tasks
27042
- - **People** \u2014 link assignees or stakeholders when mentioning them
27043
- - **Conversations** \u2014 link a chat or message range as context
27044
-
27045
- ### Why this matters
27046
-
27047
- Other agents and humans read your output. References build a navigable context graph \u2014
27048
- in multi-agent workflows, your references are the map that the next agent follows.`;
27049
- function renderLocalAttachmentSection(section) {
27050
- if (section.images.length === 0 && section.notes.length === 0)
27051
- return "";
27052
- const lines = ["[Local attachment files]"];
27053
- for (const image of section.images) {
27054
- lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
27055
- }
27056
- lines.push(...section.notes);
27057
- return lines.join("\n");
27058
- }
27059
- function sanitizePromptMeta(value) {
27060
- return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
27061
- }
27062
- function formatBytes(bytes) {
27063
- if (bytes >= 1048576)
27064
- return `${(bytes / 1048576).toFixed(1)}MB`;
27065
- if (bytes >= 1024)
27066
- return `${Math.round(bytes / 1024)}KB`;
27067
- return `${bytes}B`;
27068
- }
27069
-
27070
- // ts/agent-core/dist/bridge-workspace.js
27071
- var BRIDGE_WORKSPACE_INSTRUCTIONS = `# Agent workspace
27072
-
27073
- You are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.
27074
-
27075
- ## Message Model
27076
-
27077
- Incoming events are rendered as structured \`[Event: ...]\` blocks.
27078
- Each event includes \`[Chat: ... (prll://cht_xxx)]\` \u2014 use that chat ID (or full URI) when replying.
27079
-
27080
- **Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.
27081
- To say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.
27082
-
27083
- ## Parall CLI
27084
-
27085
- All outbound interactions go through the \`parall\` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If \`parall\` is not on PATH, use \`npx --yes @parall/cli@latest\` instead.
27086
-
27087
- - \`parall messages send prll://cht_xxx --text-file -\` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)
27088
- - \`parall dm prll://usr_xxx --text-file - [--no-reply]\` \u2014 direct message another user
27089
- - \`parall tasks update prll://tsk_xxx --status in_progress\` \u2014 task state
27090
- - \`parall no-reply [--reason "..."]\` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)
27091
-
27092
- **Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands \`$\`, backticks, and \`$(...)\` inside \`"..."\` before the CLI sees them: \`--text "That costs $1,000"\` sends \`That costs ,000\`, and \`--text "$(cmd)"\` executes \`cmd\`. Pass message bodies via \`--text-file <path>\` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:
27093
-
27094
- \`\`\`bash
27095
- parall messages send prll://cht_xxx --text-file - <<'EOF'
27096
- That costs $1,000, and $(whoami) stays literal. I'm on it.
27097
- EOF
27098
- \`\`\`
27099
-
27100
- Keep \`--text "..."\` for short literals with no \`$\`, backtick, or apostrophe.
27101
-
27102
- The bridge injects Parall context via environment variables. The static credentials \`PRLL_API_URL\`, \`PRLL_API_KEY\`, and \`PRLL_ORG_ID\` are always set. \`PRLL_CONTEXT_FILE\` points to a per-session JSON file that the gateway updates each dispatch with \`session_id\`, \`chat_id\`, \`trigger_message_id\`, \`no_reply\`, and \`step_id\` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass \`--chat\` or \`--session\` explicitly when the context file is present.
27103
-
27104
- CLI errors are agent-readable \u2014 read them; they usually name the next step.
27105
-
27106
- ## Attachments
27107
-
27108
- Image attachments are pre-downloaded under \`.parall/attachments/<messageId>/\`. Each event's \`[Local attachment files]\` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.
27109
-
27110
- Supported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with \`parall files download att_xxx --output ...\`.
27111
-
27112
- ## Guardrails
27113
-
27114
- - A dispatch may coalesce multiple events. Decide per event whether to reply via \`messages send\` / \`dm\` \u2014 events you do not act on simply receive no reply.
27115
- - If an event carries \`[Hint: no_reply]\`, do not send anything for that event. \`no-reply\` is optional and only useful as an explicit intent marker.
27116
- - Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.
27117
- - Keep CLI replies concise and task-focused.
27118
-
27119
- See \`docs/engineering-design/agent-dm-loop-prevention.md\` \xA7 Layer 0 for why plain text is never auto-projected.
27120
-
27121
- ## Approval Flow
27122
-
27123
- When you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:
27124
-
27125
- 1. The error includes a \`PERMISSION_DENIED\` code plus the denied \`action\` and \`resource_uri\`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a \`Request approval:\` line with an approval command is printed \u2014 fill in its \`--chat\`, \`--title\`, \`--reason\` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.
27126
- 2. Request approval: \`parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"\`
27127
- 3. A card will appear in the specified chat for someone with permission to approve
27128
- 4. Check the result: \`parall approvals get prll://<id>\` or wait: \`parall approvals wait prll://<id> --timeout 300\`
27129
- 5. List available actions: \`parall approvals actions\`
27130
-
27131
- Only request approval when you've actually been denied permission. Don't request approval preemptively.
27132
- `;
27133
- function extractShellCommand(input) {
27134
- if (!input || typeof input !== "object")
27135
- return void 0;
27136
- const command = input.command;
27137
- return typeof command === "string" && command.trim() ? command.trim() : void 0;
27138
- }
27139
- function parseParallCliInvocation(command) {
27140
- const tokens = command.replace(/\s+/g, " ").trim().split(" ");
27141
- let i = 0;
27142
- if (tokens[i] === "parall") {
27143
- i++;
27144
- } else if (tokens[i] === "npx") {
27145
- i++;
27146
- while (i < tokens.length && tokens[i].startsWith("-"))
27147
- i++;
27148
- if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
27149
- return null;
27150
- i++;
27151
- } else if (tokens[i] === "pnpm") {
27152
- i++;
27153
- if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
27154
- i++;
27155
- if (i >= tokens.length || tokens[i] !== "parall")
27156
- return null;
27157
- i++;
27158
- } else {
27159
- return null;
27160
- }
27161
- return tokens.slice(i).filter((t) => !t.startsWith("-"));
27162
- }
27163
- function isParallSendCommand(command) {
27164
- if (!command)
27165
- return false;
27166
- const sub = parseParallCliInvocation(command);
27167
- if (!sub || sub.length === 0)
27168
- return false;
27169
- return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
27170
- }
27171
- function isParallNoReplyCommand(command) {
27172
- if (!command)
27173
- return false;
27174
- const sub = parseParallCliInvocation(command);
27175
- return sub?.[0] === "no-reply";
27176
- }
27177
-
27178
- // ts/agent-core/dist/dispatch-adapter.js
27179
- function buildErrorStepContent(message) {
27180
- return { text: message, suppressed: false, status: "error" };
27181
- }
27182
-
27183
- // ts/agent-core/dist/logger.js
27184
- function createLogger(prefix) {
27185
- return {
27186
- info: (msg) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
27187
- warn: (msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
27188
- error: (msg) => console.error(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
27189
- child: (sub) => createLogger(`${prefix}:${sub}`)
27190
- };
27191
- }
27192
- function childLogger(logger, sub) {
27193
- return logger.child ? logger.child(sub) : logger;
27194
- }
27195
-
27196
- // ts/agent-core/dist/gateway-base.js
27197
- import * as os from "node:os";
27198
- import * as fs2 from "node:fs";
27199
- import * as path2 from "node:path";
27200
-
27201
- // ts/sdk/dist/types.js
27202
- var MENTION_ALL_USER_ID = "all";
26493
+ // ts/sdk/dist/types.js
26494
+ var MENTION_ALL_USER_ID = "all";
27203
26495
 
27204
26496
  // ts/sdk/dist/constants.js
27205
26497
  var API_BASE = "/api/v1";
@@ -27642,6 +26934,7 @@ var ParallClient = class _ParallClient {
27642
26934
  setTokens;
27643
26935
  refreshPromise = null;
27644
26936
  swimlaneName;
26937
+ getFeatureFlagOverrides;
27645
26938
  /** Auth endpoints excluded from automatic 401 refresh to prevent recursion. */
27646
26939
  static AUTH_PATHS = /* @__PURE__ */ new Set([
27647
26940
  "/auth/login",
@@ -27672,7 +26965,7 @@ var ParallClient = class _ParallClient {
27672
26965
  return apiError;
27673
26966
  }
27674
26967
  /** Build headers common to all requests (auth, swimlane). */
27675
- buildHeaders(extra) {
26968
+ buildHeaders(path11, extra) {
27676
26969
  const headers = {
27677
26970
  "Content-Type": "application/json",
27678
26971
  ...extra
@@ -27683,6 +26976,11 @@ var ParallClient = class _ParallClient {
27683
26976
  if (this.swimlaneName) {
27684
26977
  headers["X-Prll-Swimlane"] = this.swimlaneName;
27685
26978
  }
26979
+ if (path11.startsWith(API_BASE)) {
26980
+ const overrides = this.getFeatureFlagOverrides?.();
26981
+ if (overrides)
26982
+ headers["X-Prll-FF-Override"] = overrides;
26983
+ }
27686
26984
  return headers;
27687
26985
  }
27688
26986
  constructor(options = {}) {
@@ -27693,6 +26991,7 @@ var ParallClient = class _ParallClient {
27693
26991
  this.getRefreshToken = options.getRefreshToken;
27694
26992
  this.setTokens = options.setTokens;
27695
26993
  this.swimlaneName = options.swimlaneName;
26994
+ this.getFeatureFlagOverrides = options.getFeatureFlagOverrides;
27696
26995
  }
27697
26996
  /**
27698
26997
  * Pick the origin for a request path: wiki-service base for `/wiki/v1`
@@ -27700,8 +26999,8 @@ var ParallClient = class _ParallClient {
27700
26999
  * is authoritative, so wiki vs api routing can't drift from how a caller
27701
27000
  * happens to invoke the client.
27702
27001
  */
27703
- baseUrlFor(path10) {
27704
- return path10.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
27002
+ baseUrlFor(path11) {
27003
+ return path11.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
27705
27004
  }
27706
27005
  setToken(token) {
27707
27006
  this.token = token;
@@ -27728,10 +27027,10 @@ var ParallClient = class _ParallClient {
27728
27027
  * REFRESH_THRESHOLD_S, refresh it **before** sending the request.
27729
27028
  * No-op when the token is still fresh, missing, or un-parseable.
27730
27029
  */
27731
- async ensureFreshToken(path10) {
27030
+ async ensureFreshToken(path11) {
27732
27031
  if (!this.token || !this.getRefreshToken)
27733
27032
  return;
27734
- const pathSuffix = path10.replace(/^\/api\/v1/, "");
27033
+ const pathSuffix = path11.replace(/^\/api\/v1/, "");
27735
27034
  if (_ParallClient.AUTH_PATHS.has(pathSuffix))
27736
27035
  return;
27737
27036
  const exp = _ParallClient.decodeJwtExp(this.token);
@@ -27763,11 +27062,11 @@ var ParallClient = class _ParallClient {
27763
27062
  this.refreshPromise = null;
27764
27063
  }
27765
27064
  }
27766
- async request(method, path10, body, query, retried = false, opts) {
27065
+ async request(method, path11, body, query, retried = false, opts) {
27767
27066
  if (!retried) {
27768
- await this.ensureFreshToken(path10);
27067
+ await this.ensureFreshToken(path11);
27769
27068
  }
27770
- let url = `${this.baseUrlFor(path10)}${path10}`;
27069
+ let url = `${this.baseUrlFor(path11)}${path11}`;
27771
27070
  if (query) {
27772
27071
  const params = new URLSearchParams();
27773
27072
  for (const [key, value] of Object.entries(query)) {
@@ -27779,7 +27078,7 @@ var ParallClient = class _ParallClient {
27779
27078
  if (qs)
27780
27079
  url += `?${qs}`;
27781
27080
  }
27782
- const headers = this.buildHeaders();
27081
+ const headers = this.buildHeaders(path11);
27783
27082
  const timeoutSignal = AbortSignal.timeout(opts?.timeoutMs ?? 15e3);
27784
27083
  const signal = opts?.signal ? AbortSignal.any([opts.signal, timeoutSignal]) : timeoutSignal;
27785
27084
  let res;
@@ -27797,12 +27096,12 @@ var ParallClient = class _ParallClient {
27797
27096
  throw _ParallClient.normalizeFetchError(err);
27798
27097
  }
27799
27098
  if (res.status === 401) {
27800
- const pathSuffix = path10.replace(/^\/api\/v1/, "");
27099
+ const pathSuffix = path11.replace(/^\/api\/v1/, "");
27801
27100
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
27802
27101
  if (!retried && !isAuthPath && this.getRefreshToken) {
27803
27102
  const refreshed = await this.tryRefresh();
27804
27103
  if (refreshed) {
27805
- return this.request(method, path10, body, query, true, opts);
27104
+ return this.request(method, path11, body, query, true, opts);
27806
27105
  }
27807
27106
  }
27808
27107
  if (this.onTokenExpired && !isAuthPath) {
@@ -27832,15 +27131,15 @@ var ParallClient = class _ParallClient {
27832
27131
  * hit the 100 MiB cap, so a longer 5-minute timeout is used so a
27833
27132
  * 50 MiB blob on a slow connection doesn't get chopped at 15 s.
27834
27133
  */
27835
- async multipartRequest(method, path10, body, retried = false) {
27134
+ async multipartRequest(method, path11, body, retried = false) {
27836
27135
  if (!retried) {
27837
- await this.ensureFreshToken(path10);
27136
+ await this.ensureFreshToken(path11);
27838
27137
  }
27839
- const { "Content-Type": _drop, ...headers } = this.buildHeaders();
27138
+ const { "Content-Type": _drop, ...headers } = this.buildHeaders(path11);
27840
27139
  void _drop;
27841
27140
  let res;
27842
27141
  try {
27843
- res = await fetch(`${this.baseUrlFor(path10)}${path10}`, {
27142
+ res = await fetch(`${this.baseUrlFor(path11)}${path11}`, {
27844
27143
  method,
27845
27144
  headers,
27846
27145
  body,
@@ -27850,12 +27149,12 @@ var ParallClient = class _ParallClient {
27850
27149
  throw _ParallClient.normalizeFetchError(err);
27851
27150
  }
27852
27151
  if (res.status === 401) {
27853
- const pathSuffix = path10.replace(/^\/api\/v1/, "");
27152
+ const pathSuffix = path11.replace(/^\/api\/v1/, "");
27854
27153
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
27855
27154
  if (!retried && !isAuthPath && this.getRefreshToken) {
27856
27155
  const refreshed = await this.tryRefresh();
27857
27156
  if (refreshed) {
27858
- return this.multipartRequest(method, path10, body, true);
27157
+ return this.multipartRequest(method, path11, body, true);
27859
27158
  }
27860
27159
  }
27861
27160
  if (this.onTokenExpired && !isAuthPath) {
@@ -28559,8 +27858,8 @@ var ParallClient = class _ParallClient {
28559
27858
  async requestMachineUpdate(orgId, machineId, mandatory = false) {
28560
27859
  await this.request("POST", ENDPOINTS.MACHINE_REQUEST_UPDATE(orgId, machineId), { mandatory });
28561
27860
  }
28562
- async browseMachineFilesystem(orgId, machineId, path10) {
28563
- return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path10 }, void 0, false, { timeoutMs: 15e3 });
27861
+ async browseMachineFilesystem(orgId, machineId, path11) {
27862
+ return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path11 }, void 0, false, { timeoutMs: 15e3 });
28564
27863
  }
28565
27864
  /** Create a new machine key. Returns the raw key string (shown once) + metadata. */
28566
27865
  async createMachineKey(orgId, machineId, name) {
@@ -28681,7 +27980,7 @@ var ParallClient = class _ParallClient {
28681
27980
  if (currentVersion !== void 0) {
28682
27981
  extra["If-None-Match"] = currentVersion;
28683
27982
  }
28684
- const headers = this.buildHeaders(extra);
27983
+ const headers = this.buildHeaders(ENDPOINTS.PLATFORM_CONFIG, extra);
28685
27984
  let res;
28686
27985
  try {
28687
27986
  res = await fetch(url, {
@@ -29129,8 +28428,8 @@ var ParallClient = class _ParallClient {
29129
28428
  async deleteWikiRestriction(orgId, wikiId, restrictionId) {
29130
28429
  await this.request("DELETE", ENDPOINTS.WIKI_RESTRICTION(orgId, wikiId, restrictionId));
29131
28430
  }
29132
- async getWikiAccessStatus(orgId, wikiId, path10) {
29133
- return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path10 ? { path: path10 } : void 0);
28431
+ async getWikiAccessStatus(orgId, wikiId, path11) {
28432
+ return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path11 ? { path: path11 } : void 0);
29134
28433
  }
29135
28434
  async createWikiAccessRequest(orgId, wikiId, data) {
29136
28435
  await this.request("POST", ENDPOINTS.WIKI_ACCESS_REQUESTS(orgId, wikiId), data);
@@ -29139,14 +28438,14 @@ var ParallClient = class _ParallClient {
29139
28438
  async getWikiCommits(orgId, wikiId, params) {
29140
28439
  return this.request("GET", ENDPOINTS.WIKI_COMMITS(orgId, wikiId), void 0, params);
29141
28440
  }
29142
- async getWikiFileCommits(orgId, wikiId, path10, params) {
28441
+ async getWikiFileCommits(orgId, wikiId, path11, params) {
29143
28442
  return this.request("GET", ENDPOINTS.WIKI_FILE_COMMITS(orgId, wikiId), void 0, {
29144
- path: path10,
28443
+ path: path11,
29145
28444
  ...params
29146
28445
  });
29147
28446
  }
29148
- async getWikiBlame(orgId, wikiId, path10, ref) {
29149
- return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path10, ref });
28447
+ async getWikiBlame(orgId, wikiId, path11, ref) {
28448
+ return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path11, ref });
29150
28449
  }
29151
28450
  // ---- Wiki Operations (audit log) ----
29152
28451
  async getWikiOperations(orgId, wikiId, params) {
@@ -29496,705 +28795,1483 @@ var ParallWs = class {
29496
28795
  };
29497
28796
  this.lastSeq = options.lastSeq ?? 0;
29498
28797
  }
29499
- get state() {
29500
- return this._state;
28798
+ get state() {
28799
+ return this._state;
28800
+ }
28801
+ async connect() {
28802
+ this.intentionalClose = false;
28803
+ this.setupBrowserListeners();
28804
+ this.setState("connecting");
28805
+ let ticket;
28806
+ try {
28807
+ ticket = await this.options.getTicket();
28808
+ } catch (err) {
28809
+ if (isBrowserRuntime() && isRetryableNetworkError(err)) {
28810
+ console.warn("Failed to get WS ticket:", err);
28811
+ } else {
28812
+ console.error("Failed to get WS ticket:", err);
28813
+ }
28814
+ if (this.options.reconnect) {
28815
+ this.scheduleReconnect();
28816
+ } else {
28817
+ this.setState("disconnected");
28818
+ }
28819
+ return;
28820
+ }
28821
+ const wsUrl = ticket.ws_url || this.options.wsUrl;
28822
+ if (!wsUrl) {
28823
+ console.error("No WS URL available");
28824
+ this.setState("disconnected");
28825
+ return;
28826
+ }
28827
+ const url = new URL(wsUrl);
28828
+ url.searchParams.set("ticket", ticket.ticket);
28829
+ if (this.lastSeq > 0) {
28830
+ url.searchParams.set("last_seq", String(this.lastSeq));
28831
+ }
28832
+ this.ws = new WebSocket(url.toString());
28833
+ const ws = this.ws;
28834
+ const connectTimeout = setTimeout(() => {
28835
+ if (this._state === "connected" || this.intentionalClose)
28836
+ return;
28837
+ ws.onclose = null;
28838
+ ws.onopen = null;
28839
+ ws.onerror = null;
28840
+ try {
28841
+ ws.close();
28842
+ } catch {
28843
+ }
28844
+ if (ws !== this.ws)
28845
+ return;
28846
+ if (this.options.reconnect) {
28847
+ this.scheduleReconnect();
28848
+ } else {
28849
+ this.setState("disconnected");
28850
+ }
28851
+ }, 15e3);
28852
+ this.ws.onopen = () => {
28853
+ clearTimeout(connectTimeout);
28854
+ this.reconnectAttempts = 0;
28855
+ this.lastReceivedAt = Date.now();
28856
+ this.setState("connected");
28857
+ };
28858
+ this.ws.onmessage = (event) => {
28859
+ try {
28860
+ const frame = JSON.parse(event.data);
28861
+ this.handleFrame(frame);
28862
+ } catch {
28863
+ }
28864
+ };
28865
+ this.ws.onclose = () => {
28866
+ clearTimeout(connectTimeout);
28867
+ this.stopHeartbeat();
28868
+ this.clearProbe();
28869
+ if (this.intentionalClose) {
28870
+ this.setState("disconnected");
28871
+ return;
28872
+ }
28873
+ if (this.options.reconnect) {
28874
+ this.scheduleReconnect();
28875
+ } else {
28876
+ this.setState("disconnected");
28877
+ }
28878
+ };
28879
+ this.ws.onerror = () => {
28880
+ };
28881
+ }
28882
+ disconnect() {
28883
+ this.intentionalClose = true;
28884
+ this.stopHeartbeat();
28885
+ this.clearReconnect();
28886
+ this.clearProbe();
28887
+ this.teardownBrowserListeners();
28888
+ if (this.ws) {
28889
+ this.ws.close();
28890
+ this.ws = null;
28891
+ }
28892
+ this.setState("disconnected");
28893
+ }
28894
+ // ---- Client -> Server messages ----
28895
+ /** Tell the server which chats the user is currently viewing (no auth implications). */
28896
+ watch(chatIds) {
28897
+ this.send({ type: WS_EVENTS.WATCH, data: { chat_ids: chatIds } });
28898
+ }
28899
+ sendTyping(chatId, action, threadRootId) {
28900
+ this.send({
28901
+ type: WS_EVENTS.TYPING,
28902
+ data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
28903
+ });
28904
+ }
28905
+ /** Send an agent heartbeat with telemetry data. */
28906
+ sendAgentHeartbeat(sessionId, telemetry) {
28907
+ this.send({
28908
+ type: WS_EVENTS.AGENT_HEARTBEAT,
28909
+ data: { session_id: sessionId, telemetry }
28910
+ });
28911
+ }
28912
+ sendEvent(type, data) {
28913
+ this.send({ type, data });
28914
+ }
28915
+ // ---- Event listeners ----
28916
+ on(event, handler) {
28917
+ let set = this.listeners.get(event);
28918
+ if (!set) {
28919
+ set = /* @__PURE__ */ new Set();
28920
+ this.listeners.set(event, set);
28921
+ }
28922
+ set.add(handler);
28923
+ return () => {
28924
+ set.delete(handler);
28925
+ };
28926
+ }
28927
+ off(event, handler) {
28928
+ this.listeners.get(event)?.delete(handler);
28929
+ }
28930
+ onStateChange(handler) {
28931
+ this.stateListeners.add(handler);
28932
+ return () => {
28933
+ this.stateListeners.delete(handler);
28934
+ };
28935
+ }
28936
+ // ---- Internal ----
28937
+ send(frame) {
28938
+ if (this.ws?.readyState === WebSocket.OPEN) {
28939
+ this.ws.send(JSON.stringify(frame));
28940
+ }
28941
+ }
28942
+ handleFrame(frame) {
28943
+ this.lastReceivedAt = Date.now();
28944
+ this.clearProbe();
28945
+ if (frame.seq !== void 0) {
28946
+ this.lastSeq = frame.seq;
28947
+ }
28948
+ if (frame.type === WS_EVENTS.HELLO) {
28949
+ const interval = frame.data.heartbeat_interval;
28950
+ this.startHeartbeat(interval);
28951
+ }
28952
+ const handlers = this.listeners.get(frame.type);
28953
+ if (handlers) {
28954
+ for (const handler of handlers) {
28955
+ handler(frame.data, frame.seq);
28956
+ }
28957
+ }
28958
+ }
28959
+ startHeartbeat(intervalSec) {
28960
+ this.stopHeartbeat();
28961
+ if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
28962
+ console.error("Invalid heartbeat interval from server:", intervalSec);
28963
+ return;
28964
+ }
28965
+ this.heartbeatIntervalMs = intervalSec * 1e3;
28966
+ this.heartbeatTimer = setInterval(() => {
28967
+ if (this.lastReceivedAt > 0 && Date.now() - this.lastReceivedAt > this.heartbeatIntervalMs * 1.5) {
28968
+ this.probeConnection();
28969
+ return;
28970
+ }
28971
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
28972
+ }, intervalSec * 1e3);
28973
+ }
28974
+ stopHeartbeat() {
28975
+ if (this.heartbeatTimer) {
28976
+ clearInterval(this.heartbeatTimer);
28977
+ this.heartbeatTimer = null;
28978
+ }
28979
+ }
28980
+ scheduleReconnect() {
28981
+ this.setState("reconnecting");
28982
+ this.clearReconnect();
28983
+ const base = Math.min(this.options.reconnectInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
28984
+ const delay = base * (0.5 + Math.random() * 0.5);
28985
+ this.reconnectAttempts++;
28986
+ this.reconnectTimer = setTimeout(() => {
28987
+ this.connect();
28988
+ }, delay);
28989
+ }
28990
+ clearReconnect() {
28991
+ if (this.reconnectTimer) {
28992
+ clearTimeout(this.reconnectTimer);
28993
+ this.reconnectTimer = null;
28994
+ }
28995
+ }
28996
+ /** Force-close a dead/stale connection and trigger reconnect. */
28997
+ forceReconnect() {
28998
+ this.stopHeartbeat();
28999
+ this.clearReconnect();
29000
+ this.clearProbe();
29001
+ if (this.ws) {
29002
+ this.ws.onclose = null;
29003
+ this.ws.onopen = null;
29004
+ this.ws.onerror = null;
29005
+ this.ws.onmessage = null;
29006
+ try {
29007
+ this.ws.close();
29008
+ } catch {
29009
+ }
29010
+ this.ws = null;
29011
+ }
29012
+ if (this.options.reconnect && !this.intentionalClose) {
29013
+ this.scheduleReconnect();
29014
+ } else {
29015
+ this.setState("disconnected");
29016
+ }
29017
+ }
29018
+ // ---- Browser event listeners for proactive reconnection ----
29019
+ setupBrowserListeners() {
29020
+ if (this.browserListenersActive)
29021
+ return;
29022
+ this.browserListenersActive = true;
29023
+ if (typeof document !== "undefined") {
29024
+ document.addEventListener("visibilitychange", this.handleVisibilityChange);
29025
+ }
29026
+ if (typeof window !== "undefined") {
29027
+ window.addEventListener("online", this.handleOnline);
29028
+ }
29029
+ }
29030
+ teardownBrowserListeners() {
29031
+ if (!this.browserListenersActive)
29032
+ return;
29033
+ this.browserListenersActive = false;
29034
+ if (typeof document !== "undefined") {
29035
+ document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29036
+ }
29037
+ if (typeof window !== "undefined") {
29038
+ window.removeEventListener("online", this.handleOnline);
29039
+ }
29501
29040
  }
29502
- async connect() {
29503
- this.intentionalClose = false;
29504
- this.setupBrowserListeners();
29505
- this.setState("connecting");
29506
- let ticket;
29507
- try {
29508
- ticket = await this.options.getTicket();
29509
- } catch (err) {
29510
- if (isBrowserRuntime() && isRetryableNetworkError(err)) {
29511
- console.warn("Failed to get WS ticket:", err);
29041
+ /**
29042
+ * Send a ping and arm a short timeout. If no frame arrives within 5s the
29043
+ * connection is assumed dead and force-reconnected. Any received frame
29044
+ * (including the pong) cancels the timer via clearProbe() in handleFrame.
29045
+ */
29046
+ probeConnection() {
29047
+ if (this.probeTimer)
29048
+ return;
29049
+ this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29050
+ this.probeTimer = setTimeout(() => {
29051
+ this.forceReconnect();
29052
+ }, 5e3);
29053
+ }
29054
+ clearProbe() {
29055
+ if (this.probeTimer) {
29056
+ clearTimeout(this.probeTimer);
29057
+ this.probeTimer = null;
29058
+ }
29059
+ }
29060
+ /** Tab returned to foreground — verify connection or accelerate reconnect. */
29061
+ handleVisibilityChange = () => {
29062
+ if (typeof document !== "undefined" && document.hidden)
29063
+ return;
29064
+ if (this._state === "connected") {
29065
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29066
+ this.forceReconnect();
29512
29067
  } else {
29513
- console.error("Failed to get WS ticket:", err);
29068
+ this.probeConnection();
29514
29069
  }
29515
- if (this.options.reconnect) {
29516
- this.scheduleReconnect();
29070
+ } else if (this._state === "reconnecting") {
29071
+ this.clearReconnect();
29072
+ this.reconnectAttempts = 0;
29073
+ this.connect();
29074
+ }
29075
+ };
29076
+ /** Network restored — accelerate reconnection. */
29077
+ handleOnline = () => {
29078
+ if (this.intentionalClose)
29079
+ return;
29080
+ if (this._state === "connected") {
29081
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29082
+ this.forceReconnect();
29517
29083
  } else {
29518
- this.setState("disconnected");
29084
+ this.probeConnection();
29519
29085
  }
29520
- return;
29086
+ } else if (this._state === "reconnecting") {
29087
+ this.clearReconnect();
29088
+ this.reconnectAttempts = 0;
29089
+ this.connect();
29521
29090
  }
29522
- const wsUrl = ticket.ws_url || this.options.wsUrl;
29523
- if (!wsUrl) {
29524
- console.error("No WS URL available");
29525
- this.setState("disconnected");
29526
- return;
29091
+ };
29092
+ setState(state) {
29093
+ this._state = state;
29094
+ for (const listener of this.stateListeners) {
29095
+ listener(state);
29527
29096
  }
29528
- const url = new URL(wsUrl);
29529
- url.searchParams.set("ticket", ticket.ticket);
29530
- if (this.lastSeq > 0) {
29531
- url.searchParams.set("last_seq", String(this.lastSeq));
29097
+ }
29098
+ };
29099
+
29100
+ // ts/agent-core/dist/lane-ledger.js
29101
+ var LedgerUnsupportedError = class extends Error {
29102
+ };
29103
+ function isStaleLane(err) {
29104
+ return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
29105
+ }
29106
+ function isEndpointMissing(err) {
29107
+ return err instanceof ApiError && err.status === 404 && !err.code;
29108
+ }
29109
+ var LaneLedger = class {
29110
+ opts;
29111
+ lanes = /* @__PURE__ */ new Map();
29112
+ constructor(opts) {
29113
+ this.opts = opts;
29114
+ }
29115
+ get contextDir() {
29116
+ return this.opts.contextDir;
29117
+ }
29118
+ /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
29119
+ handles(event) {
29120
+ return event.type === "message" && event.targetId.startsWith("cht_");
29121
+ }
29122
+ laneKeyFor(event) {
29123
+ if (event.type !== "message" && event.dispatchEventId) {
29124
+ return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29532
29125
  }
29533
- this.ws = new WebSocket(url.toString());
29534
- const ws = this.ws;
29535
- const connectTimeout = setTimeout(() => {
29536
- if (this._state === "connected" || this.intentionalClose)
29537
- return;
29538
- ws.onclose = null;
29539
- ws.onopen = null;
29540
- ws.onerror = null;
29126
+ return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29127
+ }
29128
+ getForEvent(event) {
29129
+ return this.lanes.get(this.laneKeyFor(event));
29130
+ }
29131
+ laneContextPath(lane) {
29132
+ return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29133
+ }
29134
+ /**
29135
+ * Claim (or reuse) the lane for a group of same-lane message events and
29136
+ * fold every group member into it. Returns 'foreign' when a healthy
29137
+ * incumbent (another pod) holds the resource — the caller must not
29138
+ * dispatch; the events stay pending server-side and re-drive after the
29139
+ * incumbent completes.
29140
+ */
29141
+ async ensureLane(events) {
29142
+ const trigger = events[events.length - 1];
29143
+ const laneKey = this.laneKeyFor(trigger);
29144
+ let lane = this.lanes.get(laneKey);
29145
+ if (!lane) {
29146
+ const targetUri = `prll://${trigger.targetId}`;
29147
+ let res;
29541
29148
  try {
29542
- ws.close();
29543
- } catch {
29149
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29150
+ target_uri: targetUri,
29151
+ thread_root_id: trigger.threadRootId,
29152
+ limit: 100
29153
+ });
29154
+ } catch (err) {
29155
+ if (isEndpointMissing(err))
29156
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29157
+ throw err;
29544
29158
  }
29545
- if (ws !== this.ws)
29546
- return;
29547
- if (this.options.reconnect) {
29548
- this.scheduleReconnect();
29549
- } else {
29550
- this.setState("disconnected");
29159
+ if (!res.claimed || !res.lane) {
29160
+ this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
29161
+ return null;
29551
29162
  }
29552
- }, 15e3);
29553
- this.ws.onopen = () => {
29554
- clearTimeout(connectTimeout);
29555
- this.reconnectAttempts = 0;
29556
- this.lastReceivedAt = Date.now();
29557
- this.setState("connected");
29558
- };
29559
- this.ws.onmessage = (event) => {
29560
- try {
29561
- const frame = JSON.parse(event.data);
29562
- this.handleFrame(frame);
29563
- } catch {
29163
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29164
+ lane = {
29165
+ laneKey,
29166
+ lane: res.lane,
29167
+ targetUri,
29168
+ threadRootId: trigger.threadRootId,
29169
+ folded: /* @__PURE__ */ new Map(),
29170
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29171
+ };
29172
+ for (const ev of res.events ?? []) {
29173
+ lane.folded.set(ev.source_id, ev.id);
29564
29174
  }
29565
- };
29566
- this.ws.onclose = () => {
29567
- clearTimeout(connectTimeout);
29568
- this.stopHeartbeat();
29569
- this.clearProbe();
29570
- if (this.intentionalClose) {
29571
- this.setState("disconnected");
29572
- return;
29175
+ this.lanes.set(laneKey, lane);
29176
+ }
29177
+ for (const ev of events) {
29178
+ if (lane.folded.has(ev.messageId))
29179
+ continue;
29180
+ try {
29181
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29182
+ lane: lane.lane,
29183
+ target_uri: lane.targetUri,
29184
+ thread_root_id: lane.threadRootId,
29185
+ ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
29186
+ });
29187
+ lane.folded.set(ev.messageId, res.dispatch_event_id);
29188
+ } catch (err) {
29189
+ if (isStaleLane(err)) {
29190
+ this.lanes.delete(laneKey);
29191
+ return null;
29192
+ }
29193
+ this.opts.log?.warn(`steer fold failed for ${ev.messageId} \u2014 failing closed, releasing lane: ${String(err)}`);
29194
+ await this.release(laneKey);
29195
+ return null;
29573
29196
  }
29574
- if (this.options.reconnect) {
29575
- this.scheduleReconnect();
29197
+ }
29198
+ return lane;
29199
+ }
29200
+ /**
29201
+ * Fold a live mid-turn message into its active lane BEFORE injecting it
29202
+ * into the running turn. Injection without a successful fold is forbidden —
29203
+ * an un-folded injected message would be re-driven after complete and the
29204
+ * model would handle it twice.
29205
+ */
29206
+ async steerLive(event) {
29207
+ const laneKey = this.laneKeyFor(event);
29208
+ const lane = this.lanes.get(laneKey);
29209
+ if (!lane)
29210
+ return false;
29211
+ if (lane.folded.has(event.messageId))
29212
+ return true;
29213
+ try {
29214
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29215
+ lane: lane.lane,
29216
+ target_uri: lane.targetUri,
29217
+ thread_root_id: lane.threadRootId,
29218
+ ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
29219
+ });
29220
+ lane.folded.set(event.messageId, res.dispatch_event_id);
29221
+ return true;
29222
+ } catch (err) {
29223
+ if (isStaleLane(err)) {
29224
+ this.lanes.delete(laneKey);
29576
29225
  } else {
29577
- this.setState("disconnected");
29226
+ this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
29578
29227
  }
29579
- };
29580
- this.ws.onerror = () => {
29581
- };
29582
- }
29583
- disconnect() {
29584
- this.intentionalClose = true;
29585
- this.stopHeartbeat();
29586
- this.clearReconnect();
29587
- this.clearProbe();
29588
- this.teardownBrowserListeners();
29589
- if (this.ws) {
29590
- this.ws.close();
29591
- this.ws = null;
29228
+ return false;
29592
29229
  }
29593
- this.setState("disconnected");
29594
- }
29595
- // ---- Client -> Server messages ----
29596
- /** Tell the server which chats the user is currently viewing (no auth implications). */
29597
- watch(chatIds) {
29598
- this.send({ type: WS_EVENTS.WATCH, data: { chat_ids: chatIds } });
29599
29230
  }
29600
- sendTyping(chatId, action, threadRootId) {
29601
- this.send({
29602
- type: WS_EVENTS.TYPING,
29603
- data: { chat_id: chatId, thread_root_id: threadRootId ?? null, action }
29604
- });
29231
+ /**
29232
+ * Complete the lane when no local work remains for it: the server sweeps
29233
+ * still-leased members as no_action, releases the occupancy row, and
29234
+ * re-drives any same-target pending work. A STALE_LANE answer means a
29235
+ * takeover already owns the resource — local state is dropped either way.
29236
+ */
29237
+ async completeIfIdle(laneKey, hasMoreLocal) {
29238
+ const lane = this.lanes.get(laneKey);
29239
+ if (!lane || hasMoreLocal)
29240
+ return;
29241
+ this.lanes.delete(laneKey);
29242
+ this.removeLaneContext(lane);
29243
+ try {
29244
+ const res = await this.opts.client.completeDispatch(this.opts.orgId, {
29245
+ lane: lane.lane,
29246
+ target_uri: lane.targetUri,
29247
+ thread_root_id: lane.threadRootId
29248
+ });
29249
+ if (res.swept_no_action > 0 || res.redriven) {
29250
+ this.opts.log?.info(`lane complete for ${lane.targetUri}: swept ${res.swept_no_action} no_action, redriven=${res.redriven}`);
29251
+ }
29252
+ } catch (err) {
29253
+ if (isStaleLane(err)) {
29254
+ this.opts.log?.info(`lane complete skipped for ${lane.targetUri} \u2014 taken over`);
29255
+ return;
29256
+ }
29257
+ this.opts.log?.warn(`lane complete failed for ${lane.targetUri}: ${String(err)}`);
29258
+ }
29605
29259
  }
29606
- /** Send an agent heartbeat with telemetry data. */
29607
- sendAgentHeartbeat(sessionId, telemetry) {
29608
- this.send({
29609
- type: WS_EVENTS.AGENT_HEARTBEAT,
29610
- data: { session_id: sessionId, telemetry }
29260
+ /**
29261
+ * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
29262
+ * so a chatty turn doesn't spam the server. Without this, a legitimately
29263
+ * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
29264
+ * write misfired with STALE_LANE — the design doc's "long turns renew via
29265
+ * step writes". Fire-and-forget: a failed renewal is surfaced by the next
29266
+ * write's incumbency check anyway.
29267
+ */
29268
+ maybeRenew(lane) {
29269
+ const now = Date.now();
29270
+ const ttl = lane.leaseTtlMs ?? 10 * 6e4;
29271
+ const until = lane.leaseUntilMs ?? now;
29272
+ if (until - now > ttl / 2)
29273
+ return;
29274
+ lane.leaseUntilMs = now + ttl;
29275
+ void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
29276
+ lane: lane.lane,
29277
+ target_uri: lane.targetUri,
29278
+ thread_root_id: lane.threadRootId
29279
+ }).then((res) => {
29280
+ const until2 = Date.parse(res?.lease_until ?? "");
29281
+ if (!Number.isNaN(until2))
29282
+ lane.leaseUntilMs = until2;
29283
+ }).catch((err) => {
29284
+ if (isStaleLane(err)) {
29285
+ this.lanes.delete(lane.laneKey);
29286
+ this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
29287
+ return;
29288
+ }
29289
+ this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
29611
29290
  });
29612
29291
  }
29613
- sendEvent(type, data) {
29614
- this.send({ type, data });
29615
- }
29616
- // ---- Event listeners ----
29617
- on(event, handler) {
29618
- let set = this.listeners.get(event);
29619
- if (!set) {
29620
- set = /* @__PURE__ */ new Set();
29621
- this.listeners.set(event, set);
29292
+ /**
29293
+ * Release a lane's unresolved members back to pending (dispatch error /
29294
+ * shutdown) so the next pod re-claims immediately instead of waiting out
29295
+ * the lease.
29296
+ */
29297
+ async release(laneKey) {
29298
+ const lane = this.lanes.get(laneKey);
29299
+ if (!lane)
29300
+ return;
29301
+ this.lanes.delete(laneKey);
29302
+ this.removeLaneContext(lane);
29303
+ try {
29304
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane);
29305
+ } catch (err) {
29306
+ this.opts.log?.warn(`lane release failed for ${lane.targetUri}: ${String(err)}`);
29622
29307
  }
29623
- set.add(handler);
29624
- return () => {
29625
- set.delete(handler);
29626
- };
29627
- }
29628
- off(event, handler) {
29629
- this.listeners.get(event)?.delete(handler);
29630
- }
29631
- onStateChange(handler) {
29632
- this.stateListeners.add(handler);
29633
- return () => {
29634
- this.stateListeners.delete(handler);
29635
- };
29636
29308
  }
29637
- // ---- Internal ----
29638
- send(frame) {
29639
- if (this.ws?.readyState === WebSocket.OPEN) {
29640
- this.ws.send(JSON.stringify(frame));
29309
+ async releaseAll() {
29310
+ const keys = [...this.lanes.keys()];
29311
+ for (const key of keys) {
29312
+ await this.release(key);
29641
29313
  }
29642
29314
  }
29643
- handleFrame(frame) {
29644
- this.lastReceivedAt = Date.now();
29645
- this.clearProbe();
29646
- if (frame.seq !== void 0) {
29647
- this.lastSeq = frame.seq;
29648
- }
29649
- if (frame.type === WS_EVENTS.HELLO) {
29650
- const interval = frame.data.heartbeat_interval;
29651
- this.startHeartbeat(interval);
29652
- }
29653
- const handlers = this.listeners.get(frame.type);
29654
- if (handlers) {
29655
- for (const handler of handlers) {
29656
- handler(frame.data, frame.seq);
29657
- }
29658
- }
29315
+ /** True when any lane is currently active (used by shutdown logging). */
29316
+ get activeCount() {
29317
+ return this.lanes.size;
29659
29318
  }
29660
- startHeartbeat(intervalSec) {
29661
- this.stopHeartbeat();
29662
- if (!Number.isFinite(intervalSec) || intervalSec <= 0) {
29663
- console.error("Invalid heartbeat interval from server:", intervalSec);
29664
- return;
29319
+ /**
29320
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
29321
+ * by WorkItem id or by source identity (the live task.assigned event has no
29322
+ * WorkItem id). Returns null when a healthy incumbent (another pod) holds
29323
+ * it or the WorkItem is already resolved — the caller must skip processing.
29324
+ */
29325
+ async claimTyped(ref) {
29326
+ let res;
29327
+ try {
29328
+ res = await this.opts.client.claimDispatch(this.opts.orgId, {
29329
+ dispatch_event_id: ref.dispatchEventId,
29330
+ source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
29331
+ source_id: ref.dispatchEventId ? void 0 : ref.sourceId
29332
+ });
29333
+ } catch (err) {
29334
+ if (isEndpointMissing(err))
29335
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
29336
+ throw err;
29665
29337
  }
29666
- this.heartbeatIntervalMs = intervalSec * 1e3;
29667
- this.heartbeatTimer = setInterval(() => {
29668
- if (this.lastReceivedAt > 0 && Date.now() - this.lastReceivedAt > this.heartbeatIntervalMs * 1.5) {
29669
- this.probeConnection();
29670
- return;
29671
- }
29672
- this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29673
- }, intervalSec * 1e3);
29338
+ if (!res.claimed || !res.lane || !res.events?.length)
29339
+ return null;
29340
+ const workItem = res.events[0];
29341
+ const targetUri = `dsp:${workItem.id}`;
29342
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
29343
+ const lane = {
29344
+ laneKey: laneKeyForTarget(targetUri),
29345
+ lane: res.lane,
29346
+ targetUri,
29347
+ folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
29348
+ typedDispatchEventId: workItem.id,
29349
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29350
+ };
29351
+ this.lanes.set(lane.laneKey, lane);
29352
+ return lane;
29674
29353
  }
29675
- stopHeartbeat() {
29676
- if (this.heartbeatTimer) {
29677
- clearInterval(this.heartbeatTimer);
29678
- this.heartbeatTimer = null;
29354
+ /**
29355
+ * Remove the per-lane context file (and its CLI sidecar) when the lane
29356
+ * ends. A leftover file would make a later cross-context send to the same
29357
+ * target bind a dead lane token and misfire with STALE_LANE instead of
29358
+ * taking the plain non-ledger path.
29359
+ */
29360
+ removeLaneContext(lane) {
29361
+ const contextPath = this.laneContextPath(lane);
29362
+ for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
29363
+ try {
29364
+ fs.rmSync(p, { force: true });
29365
+ } catch {
29366
+ }
29679
29367
  }
29680
29368
  }
29681
- scheduleReconnect() {
29682
- this.setState("reconnecting");
29683
- this.clearReconnect();
29684
- const base = Math.min(this.options.reconnectInterval * Math.pow(2, this.reconnectAttempts), this.options.maxReconnectInterval);
29685
- const delay = base * (0.5 + Math.random() * 0.5);
29686
- this.reconnectAttempts++;
29687
- this.reconnectTimer = setTimeout(() => {
29688
- this.connect();
29689
- }, delay);
29690
- }
29691
- clearReconnect() {
29692
- if (this.reconnectTimer) {
29693
- clearTimeout(this.reconnectTimer);
29694
- this.reconnectTimer = null;
29369
+ };
29370
+
29371
+ // ts/agent-core/dist/gateway-lane-flow.js
29372
+ async function dispatchLaneGroup(host, opts) {
29373
+ const ledger = host.laneLedger;
29374
+ const event = opts.events[opts.events.length - 1];
29375
+ let lane;
29376
+ try {
29377
+ lane = await ledger.ensureLane(opts.events);
29378
+ } catch (err) {
29379
+ if (!(err instanceof LedgerUnsupportedError))
29380
+ throw err;
29381
+ host.disableLedger("claim endpoint missing");
29382
+ await host.emitDispatchReceived(event);
29383
+ const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29384
+ if (!dispatched2)
29385
+ return "shutdown";
29386
+ for (const ev of opts.events) {
29387
+ host.opts.client.ackDispatch(host.opts.config.org_id, {
29388
+ source_type: ev.ackSourceType ?? "message",
29389
+ source_id: ev.ackSourceId ?? ev.messageId
29390
+ }).catch(() => {
29391
+ });
29695
29392
  }
29393
+ return "dispatched";
29696
29394
  }
29697
- /** Force-close a dead/stale connection and trigger reconnect. */
29698
- forceReconnect() {
29699
- this.stopHeartbeat();
29700
- this.clearReconnect();
29701
- this.clearProbe();
29702
- if (this.ws) {
29703
- this.ws.onclose = null;
29704
- this.ws.onopen = null;
29705
- this.ws.onerror = null;
29706
- this.ws.onmessage = null;
29707
- try {
29708
- this.ws.close();
29709
- } catch {
29710
- }
29711
- this.ws = null;
29395
+ if (!lane) {
29396
+ for (const ev of opts.events) {
29397
+ host.dispatchedMessages.delete(ev.messageId);
29712
29398
  }
29713
- if (this.options.reconnect && !this.intentionalClose) {
29714
- this.scheduleReconnect();
29715
- } else {
29716
- this.setState("disconnected");
29399
+ return "foreign";
29400
+ }
29401
+ let dispatched = false;
29402
+ try {
29403
+ dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
29404
+ } catch (err) {
29405
+ await ledger.release(lane.laneKey).catch(() => {
29406
+ });
29407
+ throw err;
29408
+ }
29409
+ if (!dispatched) {
29410
+ return "shutdown";
29411
+ }
29412
+ const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
29413
+ await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
29414
+ return "dispatched";
29415
+ }
29416
+ var TYPED_BACKOFF_BASE_MS = 2e3;
29417
+ var TYPED_BACKOFF_CAP_MS = 5 * 6e4;
29418
+ var TYPED_BACKOFF_MAP_CAP = 512;
29419
+ async function consumeTypedDispatch(host, ref, run, ack) {
29420
+ const backoffKey = ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`;
29421
+ const armed = host.typedRedriveBackoff.get(backoffKey);
29422
+ if (armed) {
29423
+ const waitMs = armed.until - Date.now();
29424
+ if (waitMs > 0) {
29425
+ host.opts.log?.info(`typed dispatch ${backoffKey} backing off ${Math.ceil(waitMs / 1e3)}s after ${armed.failures} failed consume(s)`);
29426
+ await new Promise((resolve3) => {
29427
+ const timer = setTimeout(resolve3, waitMs);
29428
+ timer.unref?.();
29429
+ });
29717
29430
  }
29431
+ if (host.shuttingDown)
29432
+ return;
29718
29433
  }
29719
- // ---- Browser event listeners for proactive reconnection ----
29720
- setupBrowserListeners() {
29721
- if (this.browserListenersActive)
29434
+ const settleAck = (ackResult) => ackResult !== false;
29435
+ const settle = (acked2) => {
29436
+ if (acked2) {
29437
+ host.typedRedriveBackoff.delete(backoffKey);
29722
29438
  return;
29723
- this.browserListenersActive = true;
29724
- if (typeof document !== "undefined") {
29725
- document.addEventListener("visibilitychange", this.handleVisibilityChange);
29726
29439
  }
29727
- if (typeof window !== "undefined") {
29728
- window.addEventListener("online", this.handleOnline);
29440
+ const failures = (host.typedRedriveBackoff.get(backoffKey)?.failures ?? 0) + 1;
29441
+ const backoffMs = Math.min(TYPED_BACKOFF_CAP_MS, TYPED_BACKOFF_BASE_MS * 2 ** (failures - 1));
29442
+ if (host.typedRedriveBackoff.delete(backoffKey) === false && host.typedRedriveBackoff.size >= TYPED_BACKOFF_MAP_CAP) {
29443
+ const oldest = host.typedRedriveBackoff.keys().next().value;
29444
+ if (oldest !== void 0)
29445
+ host.typedRedriveBackoff.delete(oldest);
29446
+ }
29447
+ host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
29448
+ };
29449
+ const runLegacy = async () => {
29450
+ let acked2 = false;
29451
+ try {
29452
+ if (await run(ref.dispatchEventId)) {
29453
+ acked2 = settleAck(await ack(ref.dispatchEventId));
29454
+ }
29455
+ } finally {
29456
+ settle(acked2);
29729
29457
  }
29458
+ };
29459
+ if (!host.laneLedger || host.ledgerDisabled) {
29460
+ await runLegacy();
29461
+ return;
29730
29462
  }
29731
- teardownBrowserListeners() {
29732
- if (!this.browserListenersActive)
29463
+ let lane;
29464
+ try {
29465
+ lane = await host.laneLedger.claimTyped(ref);
29466
+ } catch (err) {
29467
+ if (err instanceof LedgerUnsupportedError) {
29468
+ host.disableLedger("claim endpoint missing");
29469
+ await runLegacy();
29733
29470
  return;
29734
- this.browserListenersActive = false;
29735
- if (typeof document !== "undefined") {
29736
- document.removeEventListener("visibilitychange", this.handleVisibilityChange);
29737
- }
29738
- if (typeof window !== "undefined") {
29739
- window.removeEventListener("online", this.handleOnline);
29740
29471
  }
29472
+ throw err;
29741
29473
  }
29742
- /**
29743
- * Send a ping and arm a short timeout. If no frame arrives within 5s the
29744
- * connection is assumed dead and force-reconnected. Any received frame
29745
- * (including the pong) cancels the timer via clearProbe() in handleFrame.
29746
- */
29747
- probeConnection() {
29748
- if (this.probeTimer)
29749
- return;
29750
- this.send({ type: WS_EVENTS.PING, data: { ts: Date.now() } });
29751
- this.probeTimer = setTimeout(() => {
29752
- this.forceReconnect();
29753
- }, 5e3);
29474
+ if (!lane) {
29475
+ host.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} not claimable (held elsewhere or already resolved) \u2014 skipping`);
29476
+ return;
29754
29477
  }
29755
- clearProbe() {
29756
- if (this.probeTimer) {
29757
- clearTimeout(this.probeTimer);
29758
- this.probeTimer = null;
29478
+ let acked = false;
29479
+ try {
29480
+ if (await run(lane.typedDispatchEventId)) {
29481
+ acked = settleAck(await ack(lane.typedDispatchEventId));
29759
29482
  }
29483
+ } finally {
29484
+ settle(acked);
29485
+ await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
29486
+ });
29760
29487
  }
29761
- /** Tab returned to foreground — verify connection or accelerate reconnect. */
29762
- handleVisibilityChange = () => {
29763
- if (typeof document !== "undefined" && document.hidden)
29764
- return;
29765
- if (this._state === "connected") {
29766
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29767
- this.forceReconnect();
29768
- } else {
29769
- this.probeConnection();
29770
- }
29771
- } else if (this._state === "reconnecting") {
29772
- this.clearReconnect();
29773
- this.reconnectAttempts = 0;
29774
- this.connect();
29775
- }
29488
+ }
29489
+ async function consumeMessageWorkItem(host, item) {
29490
+ if (host.shuttingDown)
29491
+ return;
29492
+ if (!host.tryClaimMessage(item.source_id))
29493
+ return;
29494
+ const ackItem = () => {
29495
+ host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
29496
+ });
29776
29497
  };
29777
- /** Network restored — accelerate reconnection. */
29778
- handleOnline = () => {
29779
- if (this.intentionalClose)
29498
+ let msg = null;
29499
+ try {
29500
+ msg = await host.opts.client.getMessage(item.source_id);
29501
+ } catch (err) {
29502
+ const status = err?.status;
29503
+ if (status !== 404) {
29504
+ host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
29505
+ host.dispatchedMessages.delete(item.source_id);
29780
29506
  return;
29781
- if (this._state === "connected") {
29782
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
29783
- this.forceReconnect();
29784
- } else {
29785
- this.probeConnection();
29786
- }
29787
- } else if (this._state === "reconnecting") {
29788
- this.clearReconnect();
29789
- this.reconnectAttempts = 0;
29790
- this.connect();
29791
29507
  }
29792
- };
29793
- setState(state) {
29794
- this._state = state;
29795
- for (const listener of this.stateListeners) {
29796
- listener(state);
29508
+ }
29509
+ if (!msg || msg.sender_id === host.opts.agentUserId) {
29510
+ host.dispatchedMessages.delete(item.source_id);
29511
+ ackItem();
29512
+ return;
29513
+ }
29514
+ const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
29515
+ if (decision.action === "retry") {
29516
+ host.dispatchedMessages.delete(item.source_id);
29517
+ return;
29518
+ }
29519
+ if (decision.action === "skip") {
29520
+ host.dispatchedMessages.delete(item.source_id);
29521
+ ackItem();
29522
+ return;
29523
+ }
29524
+ decision.event.dispatchEventId = item.id;
29525
+ const laneResolved = host.usesLaneLedger(decision.event);
29526
+ try {
29527
+ const dispatched = await host.handleInboundEvent(decision.event);
29528
+ if (dispatched) {
29529
+ if (!laneResolved)
29530
+ ackItem();
29531
+ } else {
29532
+ host.dispatchedMessages.delete(item.source_id);
29797
29533
  }
29534
+ } catch (err) {
29535
+ host.dispatchedMessages.delete(item.source_id);
29536
+ throw err;
29537
+ }
29538
+ }
29539
+
29540
+ // ts/agent-core/dist/session-state.js
29541
+ function normalizeSessionKey(sessionKey) {
29542
+ return sessionKey.toLowerCase();
29543
+ }
29544
+ var sessionChatIdMap = /* @__PURE__ */ new Map();
29545
+ var sessionMessageIdMap = /* @__PURE__ */ new Map();
29546
+ var dispatchMessageIdMap = /* @__PURE__ */ new Map();
29547
+ var dispatchNoReplyMap = /* @__PURE__ */ new Map();
29548
+ function setSessionChatId(sessionKey, chatId) {
29549
+ sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
29550
+ }
29551
+ function setSessionMessageId(sessionKey, messageId) {
29552
+ sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29553
+ }
29554
+ function clearSessionMessageId(sessionKey) {
29555
+ sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
29556
+ }
29557
+ function setDispatchMessageId(sessionKey, messageId) {
29558
+ dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
29559
+ }
29560
+ function clearDispatchMessageId(sessionKey) {
29561
+ dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
29562
+ }
29563
+ function setDispatchNoReply(sessionKey, noReply) {
29564
+ dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
29565
+ }
29566
+ function clearDispatchNoReply(sessionKey) {
29567
+ dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
29568
+ }
29569
+ var dispatchMetricsMap = /* @__PURE__ */ new Map();
29570
+ function resetDispatchMetrics(sessionKey) {
29571
+ dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
29572
+ deliver_text_chunks: 0,
29573
+ deliver_text_chars: 0,
29574
+ message_send_attempts: 0,
29575
+ message_send_successes: 0,
29576
+ no_reply_called: false,
29577
+ tool_call_count: 0,
29578
+ started_at: Date.now()
29579
+ });
29580
+ }
29581
+ function getDispatchMetrics(sessionKey) {
29582
+ return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29583
+ }
29584
+ function clearDispatchMetrics(sessionKey) {
29585
+ dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
29586
+ }
29587
+ function recordDeliverText(sessionKey, charCount) {
29588
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29589
+ if (!m)
29590
+ return;
29591
+ m.deliver_text_chunks++;
29592
+ m.deliver_text_chars += charCount;
29593
+ }
29594
+ function recordMessageSend(sessionKey, success) {
29595
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29596
+ if (!m)
29597
+ return;
29598
+ m.message_send_attempts++;
29599
+ if (success)
29600
+ m.message_send_successes++;
29601
+ }
29602
+ function recordNoReply(sessionKey) {
29603
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29604
+ if (!m)
29605
+ return;
29606
+ m.no_reply_called = true;
29607
+ }
29608
+ function recordToolCall(sessionKey) {
29609
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
29610
+ if (!m)
29611
+ return;
29612
+ m.tool_call_count++;
29613
+ }
29614
+
29615
+ // ts/agent-core/dist/routing.js
29616
+ var MAX_CONCURRENT_FORKS = 20;
29617
+ var defaultRoutingStrategy = (event, state) => {
29618
+ if (state.mainCurrentTargetId === event.targetId) {
29619
+ return { action: "buffer-main" };
29798
29620
  }
29621
+ const existingForkKey = state.activeForks.get(event.targetId);
29622
+ if (existingForkKey)
29623
+ return { action: "buffer-fork", forkKey: existingForkKey };
29624
+ if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
29625
+ return { action: "buffer-main" };
29626
+ }
29627
+ return { action: "new-fork" };
29799
29628
  };
29800
-
29801
- // ts/agent-core/dist/lane-ledger.js
29802
- import * as fs from "node:fs";
29803
- var LedgerUnsupportedError = class extends Error {
29804
- };
29805
- function isStaleLane(err) {
29806
- return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
29629
+ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
29630
+ const existingForkKey = state.activeForks.get(event.targetId);
29631
+ if (existingForkKey)
29632
+ return { action: "buffer-fork", forkKey: existingForkKey };
29633
+ if (!state.mainDispatching)
29634
+ return { action: "main" };
29635
+ return strategy(event, state);
29807
29636
  }
29808
- function isEndpointMissing(err) {
29809
- return err instanceof ApiError && err.status === 404 && !err.code;
29637
+
29638
+ // ts/agent-core/dist/event-format.js
29639
+ function sanitizeMeta(value) {
29640
+ return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
29810
29641
  }
29811
- var LaneLedger = class {
29812
- opts;
29813
- lanes = /* @__PURE__ */ new Map();
29814
- constructor(opts) {
29815
- this.opts = opts;
29816
- }
29817
- get contextDir() {
29818
- return this.opts.contextDir;
29819
- }
29820
- /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
29821
- handles(event) {
29822
- return event.type === "message" && event.targetId.startsWith("cht_");
29823
- }
29824
- laneKeyFor(event) {
29825
- if (event.type !== "message" && event.dispatchEventId) {
29826
- return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
29642
+ function buildEventBody(event) {
29643
+ const lines = [];
29644
+ if (event.type === "message") {
29645
+ lines.push(`[Event: message.new]`);
29646
+ const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29647
+ lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
29648
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29649
+ lines.push(`[Message ID: prll://${event.messageId}]`);
29650
+ if (event.threadRootId) {
29651
+ const threadMeta = [
29652
+ `prll://${event.threadRootId}`,
29653
+ event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
29654
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
29655
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
29656
+ ].filter(Boolean).join(" | ");
29657
+ lines.push(`[Thread: ${threadMeta}]`);
29827
29658
  }
29828
- return laneKeyForTarget(`prll://${event.targetId}`, event.threadRootId);
29829
- }
29830
- getForEvent(event) {
29831
- return this.lanes.get(this.laneKeyFor(event));
29832
- }
29833
- laneContextPath(lane) {
29834
- return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
29835
- }
29836
- /**
29837
- * Claim (or reuse) the lane for a group of same-lane message events and
29838
- * fold every group member into it. Returns 'foreign' when a healthy
29839
- * incumbent (another pod) holds the resource — the caller must not
29840
- * dispatch; the events stay pending server-side and re-drive after the
29841
- * incumbent completes.
29842
- */
29843
- async ensureLane(events) {
29844
- const trigger = events[events.length - 1];
29845
- const laneKey = this.laneKeyFor(trigger);
29846
- let lane = this.lanes.get(laneKey);
29847
- if (!lane) {
29848
- const targetUri = `prll://${trigger.targetId}`;
29849
- let res;
29850
- try {
29851
- res = await this.opts.client.claimDispatch(this.opts.orgId, {
29852
- target_uri: targetUri,
29853
- thread_root_id: trigger.threadRootId,
29854
- limit: 100
29855
- });
29856
- } catch (err) {
29857
- if (isEndpointMissing(err))
29858
- throw new LedgerUnsupportedError("claim endpoint unavailable");
29859
- throw err;
29860
- }
29861
- if (!res.claimed || !res.lane) {
29862
- this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
29863
- return null;
29864
- }
29865
- const leaseUntilMs = Date.parse(res.lease_until ?? "");
29866
- lane = {
29867
- laneKey,
29868
- lane: res.lane,
29869
- targetUri,
29870
- threadRootId: trigger.threadRootId,
29871
- folded: /* @__PURE__ */ new Map(),
29872
- ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
29873
- };
29874
- for (const ev of res.events ?? []) {
29875
- lane.folded.set(ev.source_id, ev.id);
29876
- }
29877
- this.lanes.set(laneKey, lane);
29659
+ if (event.unreadCount != null && event.unreadCount > 1) {
29660
+ const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
29661
+ const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
29662
+ let line = `[Unread: ${countStr} messages${sinceStr}]`;
29663
+ if (event.unreadCount > 50)
29664
+ line += ` \u2014 fetch recent context with --limit, not all`;
29665
+ lines.push(line);
29878
29666
  }
29879
- for (const ev of events) {
29880
- if (lane.folded.has(ev.messageId))
29881
- continue;
29882
- try {
29883
- const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29884
- lane: lane.lane,
29885
- target_uri: lane.targetUri,
29886
- thread_root_id: lane.threadRootId,
29887
- ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
29888
- });
29889
- lane.folded.set(ev.messageId, res.dispatch_event_id);
29890
- } catch (err) {
29891
- if (isStaleLane(err)) {
29892
- this.lanes.delete(laneKey);
29893
- return null;
29894
- }
29895
- this.opts.log?.warn(`steer fold failed for ${ev.messageId} \u2014 failing closed, releasing lane: ${String(err)}`);
29896
- await this.release(laneKey);
29897
- return null;
29667
+ if (event.noReply)
29668
+ lines.push(`[Hint: no_reply]`);
29669
+ if (event.attachments?.length) {
29670
+ for (const att of event.attachments) {
29671
+ const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
29672
+ lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
29898
29673
  }
29899
29674
  }
29900
- return lane;
29901
- }
29902
- /**
29903
- * Fold a live mid-turn message into its active lane BEFORE injecting it
29904
- * into the running turn. Injection without a successful fold is forbidden —
29905
- * an un-folded injected message would be re-driven after complete and the
29906
- * model would handle it twice.
29907
- */
29908
- async steerLive(event) {
29909
- const laneKey = this.laneKeyFor(event);
29910
- const lane = this.lanes.get(laneKey);
29911
- if (!lane)
29912
- return false;
29913
- if (lane.folded.has(event.messageId))
29914
- return true;
29915
- try {
29916
- const res = await this.opts.client.steerDispatch(this.opts.orgId, {
29917
- lane: lane.lane,
29918
- target_uri: lane.targetUri,
29919
- thread_root_id: lane.threadRootId,
29920
- ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
29921
- });
29922
- lane.folded.set(event.messageId, res.dispatch_event_id);
29923
- return true;
29924
- } catch (err) {
29925
- if (isStaleLane(err)) {
29926
- this.lanes.delete(laneKey);
29927
- } else {
29928
- this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
29929
- }
29930
- return false;
29675
+ lines.push("", event.body);
29676
+ } else if (event.type === "task_comment") {
29677
+ lines.push(`[Event: task.comment.created]`);
29678
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29679
+ lines.push(`[Task: ${taskLabel}]`);
29680
+ if (event.deliveryReason)
29681
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29682
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29683
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29684
+ lines.push("", event.body);
29685
+ } else if (event.type === "wiki_comment") {
29686
+ lines.push(`[Event: wiki.comment.created]`);
29687
+ const target = event.replyTargetUri ?? `prll://${event.targetId}`;
29688
+ if (event.targetType === "changeset") {
29689
+ lines.push(`[Wiki Changeset: ${target}]`);
29690
+ } else {
29691
+ lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
29931
29692
  }
29932
- }
29933
- /**
29934
- * Complete the lane when no local work remains for it: the server sweeps
29935
- * still-leased members as no_action, releases the occupancy row, and
29936
- * re-drives any same-target pending work. A STALE_LANE answer means a
29937
- * takeover already owns the resource — local state is dropped either way.
29938
- */
29939
- async completeIfIdle(laneKey, hasMoreLocal) {
29940
- const lane = this.lanes.get(laneKey);
29941
- if (!lane || hasMoreLocal)
29942
- return;
29943
- this.lanes.delete(laneKey);
29944
- this.removeLaneContext(lane);
29945
- try {
29946
- const res = await this.opts.client.completeDispatch(this.opts.orgId, {
29947
- lane: lane.lane,
29948
- target_uri: lane.targetUri,
29949
- thread_root_id: lane.threadRootId
29950
- });
29951
- if (res.swept_no_action > 0 || res.redriven) {
29952
- this.opts.log?.info(`lane complete for ${lane.targetUri}: swept ${res.swept_no_action} no_action, redriven=${res.redriven}`);
29953
- }
29954
- } catch (err) {
29955
- if (isStaleLane(err)) {
29956
- this.opts.log?.info(`lane complete skipped for ${lane.targetUri} \u2014 taken over`);
29957
- return;
29958
- }
29959
- this.opts.log?.warn(`lane complete failed for ${lane.targetUri}: ${String(err)}`);
29693
+ if (event.deliveryReason)
29694
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
29695
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
29696
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
29697
+ lines.push("", event.body);
29698
+ } else if (event.type === "approval") {
29699
+ lines.push(`[Event: approval.decided]`);
29700
+ lines.push(`[Approval: prll://${event.messageId}]`);
29701
+ lines.push(`[Chat: prll://${event.targetId}]`);
29702
+ lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
29703
+ lines.push("", event.body);
29704
+ } else if (event.type === "schedule") {
29705
+ lines.push(`[Event: schedule.fired]`);
29706
+ lines.push(`[Schedule: prll://${event.targetId}]`);
29707
+ lines.push(`[Run: prll://${event.messageId}]`);
29708
+ if (event.scheduledFireAt)
29709
+ lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
29710
+ if (event.attachedUri)
29711
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29712
+ lines.push("", event.body);
29713
+ } else if (event.type === "channel_message") {
29714
+ lines.push(`[Event: channel.message]`);
29715
+ const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
29716
+ const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
29717
+ lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
29718
+ lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
29719
+ if (event.channelExternalMessageId) {
29720
+ lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
29721
+ }
29722
+ lines.push(`[Audience: this conversation lives on ${providerLabel}, OUTSIDE Parall. Readers cannot open prll:// links, Parall cards, or internal attachments \u2014 never include them in replies. Write plain conversational text.]`);
29723
+ lines.push("", event.body);
29724
+ } else if (event.type === "external_trigger") {
29725
+ lines.push(`[Event: external.trigger]`);
29726
+ lines.push(`[Trigger: prll://${event.targetId}]`);
29727
+ lines.push(`[Run: prll://${event.messageId}]`);
29728
+ if (event.externalConnectionId) {
29729
+ const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
29730
+ lines.push(`[Connection: ${label}]`);
29960
29731
  }
29732
+ if (event.externalIngressEventId)
29733
+ lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
29734
+ if (event.attachedUri)
29735
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
29736
+ if (event.externalConnectionSourceType) {
29737
+ lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
29738
+ }
29739
+ if (event.externalIngressEventType) {
29740
+ lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
29741
+ }
29742
+ lines.push("", event.body);
29743
+ } else {
29744
+ lines.push(`[Event: task.assigned]`);
29745
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
29746
+ lines.push(`[Task: ${taskLabel}]`);
29747
+ lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
29748
+ lines.push("", event.body);
29961
29749
  }
29962
- /**
29963
- * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
29964
- * so a chatty turn doesn't spam the server. Without this, a legitimately
29965
- * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
29966
- * write misfired with STALE_LANE — the design doc's "long turns renew via
29967
- * step writes". Fire-and-forget: a failed renewal is surfaced by the next
29968
- * write's incumbency check anyway.
29969
- */
29970
- maybeRenew(lane) {
29971
- const now = Date.now();
29972
- const ttl = lane.leaseTtlMs ?? 10 * 6e4;
29973
- const until = lane.leaseUntilMs ?? now;
29974
- if (until - now > ttl / 2)
29975
- return;
29976
- lane.leaseUntilMs = now + ttl;
29977
- void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
29978
- lane: lane.lane,
29979
- target_uri: lane.targetUri,
29980
- thread_root_id: lane.threadRootId
29981
- }).then((res) => {
29982
- const until2 = Date.parse(res?.lease_until ?? "");
29983
- if (!Number.isNaN(until2))
29984
- lane.leaseUntilMs = until2;
29985
- }).catch((err) => {
29986
- if (isStaleLane(err)) {
29987
- this.lanes.delete(lane.laneKey);
29988
- this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
29989
- return;
29990
- }
29991
- this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
29992
- });
29750
+ return lines.join("\n") + buildSendMessageHint(event);
29751
+ }
29752
+ function buildEventBodyForForkResult(event) {
29753
+ return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
29754
+ }
29755
+ function buildSendMessageHint(event) {
29756
+ if (event.noReply)
29757
+ return "";
29758
+ if (event.type === "wiki_comment" && event.replyTargetUri) {
29759
+ const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
29760
+ return `
29761
+ <system-reminder>To reply on ${where}, run: \`parall comments add --target "${event.replyTargetUri}" --body "..."\` (read the thread first with \`parall comments list --target "${event.replyTargetUri}"\`). To message someone instead, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
29993
29762
  }
29994
- /**
29995
- * Release a lane's unresolved members back to pending (dispatch error /
29996
- * shutdown) so the next pod re-claims immediately instead of waiting out
29997
- * the lease.
29998
- */
29999
- async release(laneKey) {
30000
- const lane = this.lanes.get(laneKey);
30001
- if (!lane)
30002
- return;
30003
- this.lanes.delete(laneKey);
30004
- this.removeLaneContext(lane);
30005
- try {
30006
- await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane);
30007
- } catch (err) {
30008
- this.opts.log?.warn(`lane release failed for ${lane.targetUri}: ${String(err)}`);
29763
+ if (event.targetId.startsWith("cht_")) {
29764
+ if (event.threadRootId) {
29765
+ return `
29766
+ <system-reminder>To reply in this thread, run \`parall messages send prll://${event.targetId} --thread-root-id ${sanitizeMeta(event.threadRootId)} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
30009
29767
  }
29768
+ return `
29769
+ <system-reminder>To reply, run \`parall messages send prll://${event.targetId} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
30010
29770
  }
30011
- async releaseAll() {
30012
- const keys = [...this.lanes.keys()];
30013
- for (const key of keys) {
30014
- await this.release(key);
30015
- }
29771
+ if (event.targetId.startsWith("tsk_")) {
29772
+ return `
29773
+ <system-reminder>To respond, use the CLI: \`parall tasks update\` / \`parall tasks comments add\`. To message someone, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
30016
29774
  }
30017
- /** True when any lane is currently active (used by shutdown logging). */
30018
- get activeCount() {
30019
- return this.lanes.size;
29775
+ if (event.targetId.startsWith("sch_")) {
29776
+ return `
29777
+ <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
30020
29778
  }
30021
- /**
30022
- * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
30023
- * by WorkItem id or by source identity (the live task.assigned event has no
30024
- * WorkItem id). Returns null when a healthy incumbent (another pod) holds
30025
- * it or the WorkItem is already resolved — the caller must skip processing.
30026
- */
30027
- async claimTyped(ref) {
30028
- let res;
30029
- try {
30030
- res = await this.opts.client.claimDispatch(this.opts.orgId, {
30031
- dispatch_event_id: ref.dispatchEventId,
30032
- source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
30033
- source_id: ref.dispatchEventId ? void 0 : ref.sourceId
30034
- });
30035
- } catch (err) {
30036
- if (isEndpointMissing(err))
30037
- throw new LedgerUnsupportedError("claim endpoint unavailable");
30038
- throw err;
29779
+ if (event.type === "channel_message") {
29780
+ if (event.channelCliCapable) {
29781
+ const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
29782
+ const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
29783
+ return `
29784
+ <system-reminder>To reply, use the official Feishu CLI on your PATH: send a message to ${convRef} with \`lark-cli im\` (see \`lark-cli im --help\` for send syntax; auth is provisioned automatically).${threadAlt} lark-cli is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
30039
29785
  }
30040
- if (!res.claimed || !res.lane || !res.events?.length)
30041
- return null;
30042
- const workItem = res.events[0];
30043
- const targetUri = `dsp:${workItem.id}`;
30044
- const leaseUntilMs = Date.parse(res.lease_until ?? "");
30045
- const lane = {
30046
- laneKey: laneKeyForTarget(targetUri),
30047
- lane: res.lane,
30048
- targetUri,
30049
- folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
30050
- typedDispatchEventId: workItem.id,
30051
- ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
30052
- };
30053
- this.lanes.set(lane.laneKey, lane);
30054
- return lane;
29786
+ const platform = event.channelProvider ?? "the external platform";
29787
+ return `
29788
+ <system-reminder>This message arrived from ${platform}, but outbound replies are currently disabled for this org (no channel capability granted). Do NOT attempt to reply on the external platform. If action is needed, surface it inside Parall (\`parall messages send\` / \`parall dm\`). Your plain text output is not delivered anywhere.</system-reminder>`;
30055
29789
  }
30056
- /**
30057
- * Remove the per-lane context file (and its CLI sidecar) when the lane
30058
- * ends. A leftover file would make a later cross-context send to the same
30059
- * target bind a dead lane token and misfire with STALE_LANE instead of
30060
- * taking the plain non-ledger path.
30061
- */
30062
- removeLaneContext(lane) {
30063
- const contextPath = this.laneContextPath(lane);
30064
- for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
30065
- try {
30066
- fs.rmSync(p, { force: true });
30067
- } catch {
30068
- }
29790
+ if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
29791
+ return `
29792
+ <system-reminder>This external trigger is incoming-only. Your plain text output is not sent back to the external provider. To communicate in Parall, use \`parall messages send\` / \`parall dm\`; provider-specific outbound actions require a separate capability.</system-reminder>`;
29793
+ }
29794
+ return "";
29795
+ }
29796
+ function buildForkScopePrefix(event) {
29797
+ const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
29798
+ return `[Fork scope: You are a parallel worker forked from the main session to handle ${targetLabel}. The conversation history above belongs to the main session's in-progress dispatch \u2014 do NOT continue it or complete it, or produce external output (comments, messages) for work visible there. The main session owns its own output.
29799
+
29800
+ Only act on the event below within your target scope. If your event reveals findings about the main session's work, report them in your summary \u2014 do not post them externally.
29801
+
29802
+ End with a brief "Fork summary" of actions taken and decisions made.]
29803
+
29804
+ `;
29805
+ }
29806
+ function buildForkResultPrefix(results) {
29807
+ if (!results.length)
29808
+ return "";
29809
+ const blocks = results.map((result) => {
29810
+ const lines = [];
29811
+ for (const body of result.eventBodies) {
29812
+ lines.push(body);
29813
+ }
29814
+ lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
29815
+ lines.push(`[Fork summary: ${result.agentSummary ? sanitizeMeta(result.agentSummary) : "No fork summary available \u2014 the fork completed without producing a text summary. Check the target chat/task for any actions the fork already took before acting."}]`);
29816
+ if (result.actions.length)
29817
+ lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
29818
+ if (result.historyPath)
29819
+ lines.push(`[Fork history: ${result.historyPath}]`);
29820
+ return lines.join("\n");
29821
+ });
29822
+ return blocks.join("\n\n") + "\n\n---\n\n";
29823
+ }
29824
+
29825
+ // ts/agent-core/dist/prompt-fragments.js
29826
+ var PRLL_IDENTITY_BASE = `## You on Parall
29827
+
29828
+ Parall is a shared workspace where humans and agents work side by side as equals.
29829
+ You are a participant here, not a service. You hold tasks, own decisions, and are
29830
+ accountable for the work you take on \u2014 the same way a human teammate is.
29831
+
29832
+ The people and agents around you are collaborators, not users to serve. Be honest,
29833
+ be direct, and care about the outcome of the work \u2014 not just the request in front
29834
+ of you.`;
29835
+ function sanitizeProfileField(value) {
29836
+ return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
29837
+ }
29838
+ function sanitizeProfileBlock(value) {
29839
+ return value.replace(/\r\n?/g, "\n").trim();
29840
+ }
29841
+ function buildIdentity(agent) {
29842
+ if (!agent)
29843
+ return PRLL_IDENTITY_BASE;
29844
+ const name = sanitizeProfileField(agent.displayName);
29845
+ const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
29846
+ lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
29847
+ if (agent.description) {
29848
+ const description = sanitizeProfileBlock(agent.description);
29849
+ if (description) {
29850
+ lines.push("", "### Your Agent Profile", "", description);
30069
29851
  }
30070
29852
  }
30071
- };
29853
+ lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
29854
+ return lines.join("\n");
29855
+ }
29856
+ var PRLL_BEHAVIOR = `## How to work here
29857
+
29858
+ ### Move work forward
29859
+ Don't wait for instructions. If you see the next step, take it. If something is
29860
+ ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
29861
+ \u2014 don't go silent. Initiative is expected.
29862
+
29863
+ Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
29864
+ requests, verifying something landed. When a thing needs future attention and
29865
+ nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
29866
+
29867
+ ### Work in the open
29868
+ Nothing you do exists until the system can see it. Your progress, decisions,
29869
+ blockers, and results need to live in tasks, comments, messages, or wiki pages
29870
+ \u2014 otherwise the organization is blind to your work, and so is the next agent
29871
+ who picks up where you left off. Leave traces as you go, not at the end.
29872
+
29873
+ For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
29874
+ when status materially changes, close it when done, and link the origin that
29875
+ triggered it. Decompose multi-step work into subtasks and keep their statuses
29876
+ current \u2014 progress should be auditable without watching the work happen.
29877
+ Details: load the \`parall-tasks\` skill.
29878
+
29879
+ ### Done means landed
29880
+ Producing output does not complete a task. Work counts as done only when it has
29881
+ cleared its remaining gates \u2014 review, merge, deployment, the requester's
29882
+ verification. Until then keep the status honest (\`in_progress\` or
29883
+ \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
29884
+ self-reminder if nothing else will prompt follow-up). Never mark done what a
29885
+ human still has to accept.
29886
+
29887
+ ### Sessions, forks, and what survives
29888
+ Sessions end and context compacts. Anything that must survive \u2014 decisions,
29889
+ progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
29890
+ read the workspace, not this conversation.
29891
+
29892
+ Some events are handled by parallel fork sessions \u2014 short-lived copies of the
29893
+ same agent identity with separate context. In a fork: leave a written trace of
29894
+ what was done or deliberately not done (other sessions cannot see fork
29895
+ context), and do not start long-running processes \u2014 they die with the fork.
29896
+ When an event is marked fork-handled: do not re-handle it; verify its outcome
29897
+ instead of assuming it.
29898
+
29899
+ ### Communicate like a teammate
29900
+ Match the conversation \u2014 concise in chat, thorough in docs, plain language over
29901
+ jargon. Say what matters; stop when you're done. Don't narrate every tool call
29902
+ or pad replies to seem thorough.
29903
+
29904
+ Match the language of the person you're replying to. If someone writes in
29905
+ Chinese, reply in Chinese. If in English, reply in English. Never force a
29906
+ language switch unless explicitly asked.
29907
+
29908
+ Do not promise delivery times ("in an hour", "by tonight") unless the work is
29909
+ driven by an explicit schedule. Scope visibly; report when actually done.
29910
+
29911
+ ### Keep topics in threads
29912
+ Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
29913
+ Present \u2192 that thread is the context; reply there, passing the same root as
29914
+ \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
29915
+ never treat it as continuing your most recent thread. The sender's newest
29916
+ message is the anchor \u2014 never route a reply back into an older thread just
29917
+ because the topic used to live there.
29918
+
29919
+ Reply where the event lives: a thread message gets a thread reply, a
29920
+ top-level message gets a top-level reply. But in group chats, your later
29921
+ follow-up on that topic \u2014 progress updates, analysis, links, verification you
29922
+ post afterwards \u2014 belongs in a thread rooted at the topic's message
29923
+ (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
29924
+ the main channel stays scannable. Post follow-up at top level only when
29925
+ starting a genuinely new topic, making a channel-wide announcement, or when
29926
+ explicitly asked. Never post the same update in both the thread and the main
29927
+ channel \u2014 thread replies surface in the thread panel; no need to duplicate
29928
+ for visibility.
29929
+
29930
+ In DMs, reply top-level by default; use a thread only to continue one that
29931
+ already exists.
29932
+
29933
+ ### Group chats: mentions and unaddressed work
29934
+ An @mention is a direct request \u2014 act on it. A group message delivered to you
29935
+ without an @mention means the chat's routing lets you see the conversation:
29936
+ decide whether a reply adds value; silence is the default.
29937
+
29938
+ A message without an @mention is not an open invitation. Judge from context
29939
+ who the work belongs to \u2014 the named domain, the topic's owner, whoever is
29940
+ already on it. If it belongs to someone else, leave it. If genuinely unclear,
29941
+ ask or claim in one line ("taking this unless someone else has it") before
29942
+ starting \u2014 asking first beats duplicated or misdirected work.
29943
+
29944
+ ### Verify before you act
29945
+ Events can be redelivered \u2014 before acting, check whether it was already
29946
+ handled (your own recent replies, task comments); if handled, do nothing.
29947
+ Sends can fail silently, and creates can error after succeeding server-side \u2014
29948
+ check the chat or entity before retrying. Never blind-retry a mutating call.
29949
+
29950
+ ### Gather the full picture first
29951
+ When a request is vague, an entity may already exist, or work may already be
29952
+ underway \u2014 gather context before acting: search (\`parall search "..."\`),
29953
+ check existing tasks/chats/wiki, read the surrounding conversation. Act on the
29954
+ full picture, not the fragment that arrived in the event.
29955
+
29956
+ ### Report only work that ran
29957
+ If a scheduled job, scan, or tool call did not actually run \u2014 restarted
29958
+ session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
29959
+ or approximate results of work that did not execute.
29960
+
29961
+ ### Respect what's shared
29962
+ You have broad latitude inside your own work. But actions that are visible to
29963
+ others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
29964
+ wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
29965
+ acting, unless you've been explicitly authorized.
29966
+
29967
+ ### Shared workspace
29968
+ Other agents share this workspace. Before starting work, check whether someone
29969
+ \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
29970
+
29971
+ ### Permissions and approvals
29972
+ You have real permissions based on your roles (chat member/admin, org member).
29973
+ If you lack permission for an action, the API returns PERMISSION_DENIED with the
29974
+ \`action\` and \`resource_uri\` that were denied. The server decides whether that
29975
+ action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
29976
+ fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
29977
+ it to ask someone with permission. If it is NOT approvable, the output says so;
29978
+ ask a human with permission instead of requesting approval. A
29979
+ \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
29980
+ (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
29981
+ \`dm\` for a user). Don't retry or work around a denial; only request approval
29982
+ after an actual denial, never preemptively.
29983
+
29984
+ ### When in doubt
29985
+ Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
29986
+ credibility is what you bring to the workspace \u2014 protect it.`;
29987
+ var PRLL_REFERENCE_GUIDE = `## Parall References
29988
+
29989
+ Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
29990
+ entities when you create or update tasks, comments, messages, and wiki files.
29991
+
29992
+ All three forms work \u2014 pick whichever fits:
29993
+
29994
+ prll://tsk_abc bare URI (auto-linked)
29995
+ [](prll://tsk_abc) empty context (renders resolved title)
29996
+ [relevant context](prll://tsk_abc) with author annotation
29997
+
29998
+ Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
29999
+ resolves and renders the entity title automatically.
30000
+
30001
+ ### URI format
30002
+
30003
+ \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
30004
+
30005
+ **Entities** \u2014 the entity ID is the authority:
30006
+
30007
+ prll://usr_xxx user prll://prj_xxx project
30008
+ prll://tsk_xxx task prll://wik_xxx wiki
30009
+ prll://msg_xxx message prll://cmt_xxx comment
30010
+ prll://cht_xxx chat prll://tcm_xxx task comment (legacy)
30011
+ prll://att_xxx attachment prll://ase_xxx agent session
30012
+ prll://sch_xxx schedule prll://srn_xxx schedule run
30013
+
30014
+ **Wiki** \u2014 path is file path, fragment is a typed anchor:
30015
+
30016
+ prll://wik_xxx/docs/guide.md file
30017
+ prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
30018
+ prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
30019
+
30020
+ Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
30021
+ Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
30022
+
30023
+ **Chat message range**:
30024
+
30025
+ prll://cht_xxx#range=msg_01HA,msg_01HZ
30026
+
30027
+ **Field access** \u2014 path selects a field (omit to reference the entity itself):
30028
+
30029
+ prll://tsk_xxx/description#Implementation heading within task description
30030
+
30031
+ ### Unread context
30032
+
30033
+ When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
30034
+ This shows messages since your last interaction \u2014 your read cursor advances after each
30035
+ dispatch, so context you skip now won't appear as unread next time. Use
30036
+ \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
30037
+ counts (50+), fetch only recent messages rather than everything.
30038
+
30039
+ Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
30040
+ Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
30041
+ catch up on the thread.
30042
+
30043
+ ### Reading context on demand
30044
+
30045
+ An event only carries the single triggering message. If you're mentioned in a
30046
+ group chat and lack context, pull what you need from the chat \u2014 don't guess:
30047
+
30048
+ parall messages list cht_xxx --limit 20 --before msg_xxx
30049
+ parall messages get msg_xxx
30050
+ parall chats get cht_xxx
30051
+
30052
+ Rule of thumb: in a group chat mention, the conversation that led up to you
30053
+ being called almost always matters \u2014 read it before replying. In a DM, your
30054
+ session already has continuity, so skip the fetch unless something is unclear.
30055
+
30056
+ Same pattern for any other entity referenced in the event: \`tasks get\`,
30057
+ \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
30058
+ When one entity isn't enough \u2014 you need what's *around* it \u2014 walk the
30059
+ reference graph instead of guessing (see "Walk the reference graph" below).
30060
+
30061
+ ### Find context with search first
30062
+
30063
+ Reach for unified semantic search before paging chat history:
30064
+
30065
+ parall search "pricing decision june" --limit 10
30066
+
30067
+ It spans messages, tasks, wiki, and comments. Page \`messages list\` only for the
30068
+ verbatim recent flow of one chat, not for discovery.
30069
+
30070
+ ### Walk the reference graph
30071
+
30072
+ References form a traversable graph, and you can query it \u2014 don't stop at
30073
+ fetching entities one by one:
30074
+
30075
+ # entity metadata (title, status, preview)
30076
+ parall refs resolve prll://tsk_xxx prll://wik_xxx
30077
+ # who references this entity
30078
+ parall refs backlinks prll://tsk_xxx
30079
+ # connected sub-graph around it
30080
+ parall refs graph prll://tsk_xxx --depth 2
30081
+
30082
+ Use \`refs backlinks\` when you need "where is this discussed / used"; use
30083
+ \`refs graph\` when you need the full picture around an entity (related tasks,
30084
+ docs, conversations \u2014 edges carry the author's annotation for why they linked).
30085
+ Then \`refs resolve\` the interesting node URIs in one batch to get titles and
30086
+ status. \`refs graph\` takes entity-level URIs only (\`prll://wik_xxx\`, not
30087
+ \`prll://wik_xxx/docs/a.md\`). All results are filtered to what you can see.
30088
+ Details: parall-platform skill.
30089
+
30090
+ ### File attachments
30091
+
30092
+ Messages may include attachments. They appear in events as:
30093
+
30094
+ [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
30095
+
30096
+ To download an attachment, use the CLI:
30097
+
30098
+ parall files download att_xxx --output /tmp/screenshot.png
30099
+
30100
+ To send a file:
30101
+
30102
+ parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
30103
+
30104
+ Or upload first and reuse across chats:
30105
+
30106
+ parall files upload /tmp/report.pdf
30107
+ parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
30108
+ parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
30109
+
30110
+ The \`--text\` captions above are safe short literals. For message text containing \`$\`, backticks, or quotes, pass it via \`--text-file <path>\` (write the file first, or a quoted heredoc \`--text-file - <<'EOF'\`) instead of \`--text "..."\` \u2014 inside double quotes the shell turns \`$1,000\` into \`,000\` and executes \`$(...)\`.
30111
+
30112
+ ### When to reference
30113
+
30114
+ - **Origin** \u2014 always link the message or task that triggered your work
30115
+ - **Design docs / wiki** \u2014 link specs and guides relevant to the work
30116
+ - **Related tasks** \u2014 link parent, sibling, or blocking tasks
30117
+ - **People** \u2014 link assignees or stakeholders when mentioning them
30118
+ - **Conversations** \u2014 link a chat or message range as context
30119
+
30120
+ ### Why this matters
30121
+
30122
+ Other agents and humans read your output. References build a navigable context graph \u2014
30123
+ in multi-agent workflows, your references are the map that the next agent follows.`;
30124
+ function renderLocalAttachmentSection(section) {
30125
+ if (section.images.length === 0 && section.notes.length === 0)
30126
+ return "";
30127
+ const lines = ["[Local attachment files]"];
30128
+ for (const image of section.images) {
30129
+ lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
30130
+ }
30131
+ lines.push(...section.notes);
30132
+ return lines.join("\n");
30133
+ }
30134
+ function sanitizePromptMeta(value) {
30135
+ return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
30136
+ }
30137
+ function formatBytes(bytes) {
30138
+ if (bytes >= 1048576)
30139
+ return `${(bytes / 1048576).toFixed(1)}MB`;
30140
+ if (bytes >= 1024)
30141
+ return `${Math.round(bytes / 1024)}KB`;
30142
+ return `${bytes}B`;
30143
+ }
30144
+
30145
+ // ts/agent-core/dist/bridge-workspace.js
30146
+ var BRIDGE_WORKSPACE_INSTRUCTIONS = `# Agent workspace
30147
+
30148
+ You are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.
30149
+
30150
+ ## Message Model
30151
+
30152
+ Incoming events are rendered as structured \`[Event: ...]\` blocks.
30153
+ Each event includes \`[Chat: ... (prll://cht_xxx)]\` \u2014 use that chat ID (or full URI) when replying.
30154
+
30155
+ **Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.
30156
+ To say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.
30157
+
30158
+ ## Parall CLI
30159
+
30160
+ All outbound interactions go through the \`parall\` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If \`parall\` is not on PATH, use \`npx --yes @parall/cli@latest\` instead.
30161
+
30162
+ - \`parall messages send prll://cht_xxx --text-file -\` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)
30163
+ - \`parall dm prll://usr_xxx --text-file - [--no-reply]\` \u2014 direct message another user
30164
+ - \`parall tasks update prll://tsk_xxx --status in_progress\` \u2014 task state
30165
+ - \`parall no-reply [--reason "..."]\` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)
30166
+
30167
+ **Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands \`$\`, backticks, and \`$(...)\` inside \`"..."\` before the CLI sees them: \`--text "That costs $1,000"\` sends \`That costs ,000\`, and \`--text "$(cmd)"\` executes \`cmd\`. Pass message bodies via \`--text-file <path>\` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:
30168
+
30169
+ \`\`\`bash
30170
+ parall messages send prll://cht_xxx --text-file - <<'EOF'
30171
+ That costs $1,000, and $(whoami) stays literal. I'm on it.
30172
+ EOF
30173
+ \`\`\`
30174
+
30175
+ Keep \`--text "..."\` for short literals with no \`$\`, backtick, or apostrophe.
30176
+
30177
+ The bridge injects Parall context via environment variables. The static credentials \`PRLL_API_URL\`, \`PRLL_API_KEY\`, and \`PRLL_ORG_ID\` are always set. \`PRLL_CONTEXT_FILE\` points to a per-session JSON file that the gateway updates each dispatch with \`session_id\`, \`chat_id\`, \`trigger_message_id\`, \`no_reply\`, and \`step_id\` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass \`--chat\` or \`--session\` explicitly when the context file is present.
30178
+
30179
+ CLI errors are agent-readable \u2014 read them; they usually name the next step.
30180
+
30181
+ ## Attachments
30182
+
30183
+ Image attachments are pre-downloaded under \`.parall/attachments/<messageId>/\`. Each event's \`[Local attachment files]\` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.
30072
30184
 
30073
- // ts/agent-core/dist/gateway-lane-flow.js
30074
- async function dispatchLaneGroup(host, opts) {
30075
- const ledger = host.laneLedger;
30076
- const event = opts.events[opts.events.length - 1];
30077
- let lane;
30078
- try {
30079
- lane = await ledger.ensureLane(opts.events);
30080
- } catch (err) {
30081
- if (!(err instanceof LedgerUnsupportedError))
30082
- throw err;
30083
- host.disableLedger("claim endpoint missing");
30084
- await host.emitDispatchReceived(event);
30085
- const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
30086
- if (!dispatched2)
30087
- return "shutdown";
30088
- for (const ev of opts.events) {
30089
- host.opts.client.ackDispatch(host.opts.config.org_id, {
30090
- source_type: ev.ackSourceType ?? "message",
30091
- source_id: ev.ackSourceId ?? ev.messageId
30092
- }).catch(() => {
30093
- });
30094
- }
30095
- return "dispatched";
30096
- }
30097
- if (!lane) {
30098
- for (const ev of opts.events) {
30099
- host.dispatchedMessages.delete(ev.messageId);
30100
- }
30101
- return "foreign";
30102
- }
30103
- let dispatched = false;
30104
- try {
30105
- dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
30106
- } catch (err) {
30107
- await ledger.release(lane.laneKey).catch(() => {
30108
- });
30109
- throw err;
30110
- }
30111
- if (!dispatched) {
30112
- return "shutdown";
30113
- }
30114
- const pendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
30115
- await ledger.completeIfIdle(lane.laneKey, pendingInjections || opts.hasMoreLocal());
30116
- return "dispatched";
30185
+ Supported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with \`parall files download att_xxx --output ...\`.
30186
+
30187
+ ## Guardrails
30188
+
30189
+ - A dispatch may coalesce multiple events. Decide per event whether to reply via \`messages send\` / \`dm\` \u2014 events you do not act on simply receive no reply.
30190
+ - If an event carries \`[Hint: no_reply]\`, do not send anything for that event. \`no-reply\` is optional and only useful as an explicit intent marker.
30191
+ - Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.
30192
+ - Keep CLI replies concise and task-focused.
30193
+
30194
+ See \`docs/engineering-design/agent-dm-loop-prevention.md\` \xA7 Layer 0 for why plain text is never auto-projected.
30195
+
30196
+ ## Approval Flow
30197
+
30198
+ When you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:
30199
+
30200
+ 1. The error includes a \`PERMISSION_DENIED\` code plus the denied \`action\` and \`resource_uri\`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a \`Request approval:\` line with an approval command is printed \u2014 fill in its \`--chat\`, \`--title\`, \`--reason\` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.
30201
+ 2. Request approval: \`parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"\`
30202
+ 3. A card will appear in the specified chat for someone with permission to approve
30203
+ 4. Check the result: \`parall approvals get prll://<id>\` or wait: \`parall approvals wait prll://<id> --timeout 300\`
30204
+ 5. List available actions: \`parall approvals actions\`
30205
+
30206
+ Only request approval when you've actually been denied permission. Don't request approval preemptively.
30207
+ `;
30208
+ function extractShellCommand(input) {
30209
+ if (!input || typeof input !== "object")
30210
+ return void 0;
30211
+ const command = input.command;
30212
+ return typeof command === "string" && command.trim() ? command.trim() : void 0;
30117
30213
  }
30118
- async function consumeTypedDispatch(host, ref, run, ack) {
30119
- if (!host.laneLedger || host.ledgerDisabled) {
30120
- if (await run(ref.dispatchEventId))
30121
- await ack(ref.dispatchEventId);
30122
- return;
30123
- }
30124
- let lane;
30125
- try {
30126
- lane = await host.laneLedger.claimTyped(ref);
30127
- } catch (err) {
30128
- if (err instanceof LedgerUnsupportedError) {
30129
- host.disableLedger("claim endpoint missing");
30130
- if (await run(ref.dispatchEventId))
30131
- await ack(ref.dispatchEventId);
30132
- return;
30133
- }
30134
- throw err;
30135
- }
30136
- if (!lane) {
30137
- host.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} not claimable (held elsewhere or already resolved) \u2014 skipping`);
30138
- return;
30139
- }
30140
- try {
30141
- if (await run(lane.typedDispatchEventId))
30142
- await ack(lane.typedDispatchEventId);
30143
- } finally {
30144
- await host.laneLedger.completeIfIdle(lane.laneKey, false).catch(() => {
30145
- });
30214
+ function parseParallCliInvocation(command) {
30215
+ const tokens = command.replace(/\s+/g, " ").trim().split(" ");
30216
+ let i = 0;
30217
+ if (tokens[i] === "parall") {
30218
+ i++;
30219
+ } else if (tokens[i] === "npx") {
30220
+ i++;
30221
+ while (i < tokens.length && tokens[i].startsWith("-"))
30222
+ i++;
30223
+ if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
30224
+ return null;
30225
+ i++;
30226
+ } else if (tokens[i] === "pnpm") {
30227
+ i++;
30228
+ if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
30229
+ i++;
30230
+ if (i >= tokens.length || tokens[i] !== "parall")
30231
+ return null;
30232
+ i++;
30233
+ } else {
30234
+ return null;
30146
30235
  }
30236
+ return tokens.slice(i).filter((t) => !t.startsWith("-"));
30147
30237
  }
30148
- async function consumeMessageWorkItem(host, item) {
30149
- if (host.shuttingDown)
30150
- return;
30151
- if (!host.tryClaimMessage(item.source_id))
30152
- return;
30153
- const ackItem = () => {
30154
- host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
30155
- });
30238
+ function isParallSendCommand(command) {
30239
+ if (!command)
30240
+ return false;
30241
+ const sub = parseParallCliInvocation(command);
30242
+ if (!sub || sub.length === 0)
30243
+ return false;
30244
+ return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
30245
+ }
30246
+ function isParallNoReplyCommand(command) {
30247
+ if (!command)
30248
+ return false;
30249
+ const sub = parseParallCliInvocation(command);
30250
+ return sub?.[0] === "no-reply";
30251
+ }
30252
+
30253
+ // ts/agent-core/dist/dispatch-adapter.js
30254
+ function buildErrorStepContent(message) {
30255
+ return { text: message, suppressed: false, status: "error" };
30256
+ }
30257
+
30258
+ // ts/agent-core/dist/logger.js
30259
+ function createLogger(prefix) {
30260
+ return {
30261
+ info: (msg) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30262
+ warn: (msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30263
+ error: (msg) => console.error(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
30264
+ child: (sub) => createLogger(`${prefix}:${sub}`)
30156
30265
  };
30157
- let msg = null;
30158
- try {
30159
- msg = await host.opts.client.getMessage(item.source_id);
30160
- } catch (err) {
30161
- const status = err?.status;
30162
- if (status !== 404) {
30163
- host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
30164
- host.dispatchedMessages.delete(item.source_id);
30165
- return;
30166
- }
30167
- }
30168
- if (!msg || msg.sender_id === host.opts.agentUserId) {
30169
- host.dispatchedMessages.delete(item.source_id);
30170
- ackItem();
30171
- return;
30172
- }
30173
- const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
30174
- if (decision.action === "retry") {
30175
- host.dispatchedMessages.delete(item.source_id);
30176
- return;
30177
- }
30178
- if (decision.action === "skip") {
30179
- host.dispatchedMessages.delete(item.source_id);
30180
- ackItem();
30181
- return;
30182
- }
30183
- decision.event.dispatchEventId = item.id;
30184
- const laneResolved = host.usesLaneLedger(decision.event);
30185
- try {
30186
- const dispatched = await host.handleInboundEvent(decision.event);
30187
- if (dispatched) {
30188
- if (!laneResolved)
30189
- ackItem();
30190
- } else {
30191
- host.dispatchedMessages.delete(item.source_id);
30192
- }
30193
- } catch (err) {
30194
- host.dispatchedMessages.delete(item.source_id);
30195
- throw err;
30196
- }
30197
30266
  }
30267
+ function childLogger(logger, sub) {
30268
+ return logger.child ? logger.child(sub) : logger;
30269
+ }
30270
+
30271
+ // ts/agent-core/dist/gateway-base.js
30272
+ import * as os from "node:os";
30273
+ import * as fs2 from "node:fs";
30274
+ import * as path2 from "node:path";
30198
30275
 
30199
30276
  // ts/agent-core/dist/telemetry.js
30200
30277
  init_esm();
@@ -30476,6 +30553,9 @@ var ParallAgentGateway = class {
30476
30553
  // (stable mapping; avoids one connection fetch per inbound message).
30477
30554
  channelConnectionProviders = /* @__PURE__ */ new Map();
30478
30555
  dispatchedMessages = /* @__PURE__ */ new Set();
30556
+ // Per-WorkItem failure backoff for typed dispatch consumption — see
30557
+ // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
30558
+ typedRedriveBackoff = /* @__PURE__ */ new Map();
30479
30559
  forkStates = /* @__PURE__ */ new Map();
30480
30560
  dispatchState = {
30481
30561
  mainDispatching: false,
@@ -30600,7 +30680,11 @@ var ParallAgentGateway = class {
30600
30680
  return this.opts.client.ackDispatch(this.opts.config.org_id, {
30601
30681
  source_type: "task_activity",
30602
30682
  source_id: data.id
30603
- }).then(() => void 0, () => void 0);
30683
+ }).then(() => true, (err) => {
30684
+ this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
30685
+ this.opts.log?.warn(`dispatch ack failed for task ${data.id}, releasing for re-drive: ${String(err)}`);
30686
+ return false;
30687
+ });
30604
30688
  });
30605
30689
  } catch (err) {
30606
30690
  this.opts.log?.error(`task dispatch failed for ${data.id}: ${String(err)}`);
@@ -30750,11 +30834,15 @@ var ParallAgentGateway = class {
30750
30834
  }
30751
30835
  // Typed completion must wait until the administrative ack has either
30752
30836
  // committed or failed. Errors stay best-effort: a failed ack leaves the row
30753
- // received, so Complete releases and re-drives it safely.
30837
+ // received, so Complete releases and re-drives it safely. The boolean
30838
+ // outcome feeds the typed-consume backoff — an ack that failed must count
30839
+ // as a failed consume, or an ack outage would clear the backoff entry and
30840
+ // let the release re-drive spin at wire speed.
30754
30841
  ackDispatchEvent(dispatchEventId, onFailure) {
30755
- return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => void 0, (err) => {
30842
+ return this.opts.client.ackDispatchByID(this.opts.config.org_id, dispatchEventId).then(() => true, (err) => {
30756
30843
  onFailure?.();
30757
30844
  this.opts.log?.warn(`dispatch ack failed for ${dispatchEventId}, releasing for re-drive: ${String(err)}`);
30845
+ return false;
30758
30846
  });
30759
30847
  }
30760
30848
  clearTypedDispatchDedupe(item) {
@@ -32077,6 +32165,8 @@ var ParallAgentGateway = class {
32077
32165
  provider = void 0;
32078
32166
  }
32079
32167
  }
32168
+ const keys = this.opts.getCapabilityKeys?.() ?? [];
32169
+ const cliCapable = provider ? keys.includes(`${provider}-cli`) : keys.some((k) => k.endsWith("-cli"));
32080
32170
  const event = {
32081
32171
  type: "channel_message",
32082
32172
  targetId: conv.id,
@@ -32091,6 +32181,7 @@ var ParallAgentGateway = class {
32091
32181
  channelConversationType: conv.conversation_type || void 0,
32092
32182
  channelExternalConversationId: conv.external_conversation_id,
32093
32183
  channelExternalMessageId: msg.external_message_id,
32184
+ channelCliCapable: cliCapable,
32094
32185
  ackSourceType: "channel_message",
32095
32186
  ackSourceId: msg.id
32096
32187
  };
@@ -32427,6 +32518,28 @@ ${fullSummary}` : fullSummary;
32427
32518
  // ts/agent-core/dist/platform-config.js
32428
32519
  import * as fs3 from "node:fs";
32429
32520
  import * as path3 from "node:path";
32521
+ function extractCapabilities(config) {
32522
+ const agents = config.agents ?? {};
32523
+ const raw = agents.capabilities;
32524
+ if (!Array.isArray(raw))
32525
+ return [];
32526
+ const out = [];
32527
+ for (const entry of raw) {
32528
+ if (typeof entry !== "object" || entry === null)
32529
+ continue;
32530
+ const e = entry;
32531
+ if (typeof e.key !== "string" || !e.key)
32532
+ continue;
32533
+ if (typeof e.fragment !== "string" || !e.fragment)
32534
+ continue;
32535
+ out.push({
32536
+ key: e.key,
32537
+ source: typeof e.source === "string" ? e.source : "",
32538
+ fragment: e.fragment
32539
+ });
32540
+ }
32541
+ return out;
32542
+ }
32430
32543
  function isPlatformManagedProfile(profile) {
32431
32544
  return profile?.machine_id != null || profile?.model_management === "platform";
32432
32545
  }
@@ -32550,13 +32663,96 @@ function createPlatformConfigManager(opts) {
32550
32663
  },
32551
32664
  rawConfig() {
32552
32665
  return currentRawConfig;
32666
+ },
32667
+ capabilities() {
32668
+ return currentRawConfig ? extractCapabilities(currentRawConfig) : [];
32553
32669
  }
32554
32670
  };
32555
32671
  }
32556
32672
 
32557
- // ts/agent-core/dist/skills/index.js
32673
+ // ts/agent-core/dist/channel-capability.js
32558
32674
  import * as fs4 from "node:fs";
32559
32675
  import * as path4 from "node:path";
32676
+ import { fileURLToPath } from "node:url";
32677
+ var CAPABILITY_FEISHU_CLI = "feishu-cli";
32678
+ var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
32679
+ function capabilityBinDir(stateDir) {
32680
+ return path4.join(stateDir, "bin");
32681
+ }
32682
+ function channelExecEntryPath() {
32683
+ const selfDir = path4.dirname(fileURLToPath(import.meta.url));
32684
+ const sibling = path4.join(selfDir, "parall-channel-exec.js");
32685
+ if (fs4.existsSync(sibling))
32686
+ return sibling;
32687
+ return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
32688
+ }
32689
+ function materializeChannelCapabilities(stateDir, capabilities, log2) {
32690
+ try {
32691
+ reconcileFeishuCli(stateDir, capabilities, log2);
32692
+ } catch (err) {
32693
+ log2?.warn(`channel capability materialization failed: ${String(err)}`);
32694
+ }
32695
+ }
32696
+ function reconcileFeishuCli(stateDir, capabilities, log2) {
32697
+ const binDir = capabilityBinDir(stateDir);
32698
+ const posixPath = path4.join(binDir, "lark-cli");
32699
+ const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
32700
+ const hadPointer = fs4.existsSync(posixPath);
32701
+ if (!granted && !hadPointer)
32702
+ return;
32703
+ fs4.mkdirSync(binDir, { recursive: true });
32704
+ const entry = channelExecEntryPath();
32705
+ const nodeExec = process.execPath;
32706
+ writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log2);
32707
+ writePointerIfChanged(path4.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log2);
32708
+ }
32709
+ function writePointerIfChanged(filePath, content, log2) {
32710
+ let existing = null;
32711
+ try {
32712
+ existing = fs4.readFileSync(filePath, "utf8");
32713
+ } catch {
32714
+ existing = null;
32715
+ }
32716
+ if (existing !== content) {
32717
+ fs4.writeFileSync(filePath, content, { mode: 493 });
32718
+ log2?.info(`channel capability: pointer materialized (${path4.basename(filePath)})`);
32719
+ }
32720
+ fs4.chmodSync(filePath, 493);
32721
+ }
32722
+ function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
32723
+ return [
32724
+ "#!/bin/sh",
32725
+ `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32726
+ "# Credential + exec logic lives in the agent-core package; revocation is",
32727
+ "# enforced by the platform mint endpoint, so this pointer stays constant.",
32728
+ // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
32729
+ // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
32730
+ // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
32731
+ // the mint. The pointer is a platform-authored trust-boundary artifact whose
32732
+ // whole job is a CONTROLLED launch of the broker (absolute node, magic
32733
+ // guard, skip-dir); this closes the same env-hijack class for node startup
32734
+ // that the absolute node path closes for PATH, keeping the launch deterministic.
32735
+ "unset NODE_OPTIONS NODE_PATH",
32736
+ // "$@" preserves argv exactly (this is the agent's main path via git-bash).
32737
+ `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
32738
+ ""
32739
+ ].join("\n");
32740
+ }
32741
+ function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
32742
+ return [
32743
+ "@echo off",
32744
+ `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
32745
+ // Clear Node preload-hijack vars before launching node (see the sh pointer).
32746
+ 'set "NODE_OPTIONS="',
32747
+ 'set "NODE_PATH="',
32748
+ `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
32749
+ ""
32750
+ ].join("\r\n");
32751
+ }
32752
+
32753
+ // ts/agent-core/dist/skills/index.js
32754
+ import * as fs5 from "node:fs";
32755
+ import * as path5 from "node:path";
32560
32756
 
32561
32757
  // ts/agent-core/dist/skills/parall-platform.js
32562
32758
  var PARALL_PLATFORM_SKILL = `# Parall Platform
@@ -32637,11 +32833,11 @@ settled questions or repeat known mistakes. This searches live org data
32637
32833
  can see.
32638
32834
 
32639
32835
  \`\`\`bash
32640
- # Semantic + keyword search across messages, tasks, and wiki
32836
+ # Semantic + keyword search across messages, tasks, wiki, and comments
32641
32837
  parall search "auth v5 upgrade"
32642
32838
 
32643
- # Restrict entity types (m=message, t=task, w=wiki). --channel narrows the
32644
- # MESSAGE hits to one chat (tasks/wiki are unaffected by it).
32839
+ # Restrict entity types (m=message, t=task, w=wiki, c=comment). --channel
32840
+ # narrows the MESSAGE hits to one chat (tasks/wiki/comments are unaffected).
32645
32841
  parall search "auth v5 upgrade" --types m,w --channel prll://cht_eng
32646
32842
 
32647
32843
  # Time-box to recent activity (RFC3339 or YYYY-MM-DD). Narrows messages + tasks;
@@ -32762,6 +32958,8 @@ Every entity is addressable with a \`prll://\` URI. Common prefixes you'll see i
32762
32958
  | \`prll://usr_\` | User (human or agent) | parall-platform |
32763
32959
  | \`prll://cht_\` | Chat | parall-platform |
32764
32960
  | \`prll://msg_\` | Message | parall-platform |
32961
+ | \`prll://cmt_\` | Comment (on tasks, wiki pages, changesets) | by target: task comment \u2192 parall-tasks, wiki/changeset comment \u2192 parall-wiki |
32962
+ | \`prll://ase_\` | Agent session | parall-platform |
32765
32963
  | \`prll://tsk_\` | Task | parall-tasks |
32766
32964
  | \`prll://prj_\` | Project | parall-tasks |
32767
32965
  | \`prll://sch_\` | Schedule (time trigger) | parall-schedules |
@@ -32797,7 +32995,24 @@ parall refs graph prll://tsk_xxx --depth 2
32797
32995
 
32798
32996
  \`refs graph\` traverses both directions (inbound + outbound) and returns \`nodes\`
32799
32997
  and \`edges\` with each node's hop \`depth\`. \`truncated: true\` means a size cap clipped
32800
- the result \u2014 narrow it with a smaller \`--depth\`.
32998
+ the result \u2014 narrow it with a smaller \`--depth\`. Edges carry \`context\` \u2014 the
32999
+ author's annotation from \`[context](prll://...)\` \u2014 telling you *why* two
33000
+ entities are linked, not just that they are.
33001
+
33002
+ The graph returns bare node URIs (no titles). The usual two-step: \`refs graph\`
33003
+ for topology, then batch-\`refs resolve\` the node URIs you care about for
33004
+ titles/status. If graph rejects your URI with a path/anchor error, strip it to
33005
+ the entity root (\`prll://wik_xxx/docs/a.md\` \u2192 \`prll://wik_xxx\`) and re-query \u2014
33006
+ but note this WIDENS the query to the whole entity, not that one file: the
33007
+ graph seeds from the wiki id, so a specific file's outbound links may sit
33008
+ deeper in the result (or past the size caps). For refs pointing AT one file
33009
+ (inbound), \`refs backlinks\` on the full file URI is precise. There is no
33010
+ precise query for one file's OUTBOUND edges today \u2014 the widened root graph is
33011
+ best-effort for those, or read the file itself for its \`prll://\` links.
33012
+ Wiki-file nodes inside a graph *result* do legitimately carry paths.
33013
+
33014
+ \`refs backlinks\` items include a \`snippet\` of the referencing content \u2014 often
33015
+ enough to judge relevance without fetching the source entity.
32801
33016
 
32802
33017
  CLI success output is JSON. Errors print a JSON line (\`{"error","status","code",...}\`) and, on a \`PERMISSION_DENIED\`, may add a plain-text \`Request approval:\` line \u2014 read both.
32803
33018
  `;
@@ -33311,7 +33526,7 @@ Results are JSON on stdout; failures print an error.
33311
33526
  var SKILLS = [
33312
33527
  {
33313
33528
  name: "parall-platform",
33314
- description: "Parall platform queries and lightweight agent provisioning: list org members, agents, chats, read message history, check identity, or create another agent. Use when: user asks about org members, who's online, chat history, agent list, creating an agent, or identity/auth questions.",
33529
+ description: "Parall platform queries and lightweight agent provisioning: list org members, agents, chats, read message history, check identity, create another agent, or walk the prll:// reference graph (resolve URIs, backlinks, multi-hop graph). Use when: user asks about org members, who's online, chat history, agent list, creating an agent, identity/auth questions, or you need to find what an entity is connected to / who references it.",
33315
33530
  content: PARALL_PLATFORM_SKILL
33316
33531
  },
33317
33532
  {
@@ -33341,13 +33556,13 @@ var SKILLS = [
33341
33556
  }
33342
33557
  ];
33343
33558
  function writeSkillFiles(targetDir) {
33344
- fs4.mkdirSync(targetDir, { recursive: true });
33559
+ fs5.mkdirSync(targetDir, { recursive: true });
33345
33560
  for (const skill of SKILLS) {
33346
- fs4.writeFileSync(path4.join(targetDir, `${skill.name}.md`), skill.content, "utf8");
33561
+ fs5.writeFileSync(path5.join(targetDir, `${skill.name}.md`), skill.content, "utf8");
33347
33562
  }
33348
33563
  }
33349
33564
  function buildSkillReferences(workspaceDir) {
33350
- const dir = path4.join(workspaceDir, ".parall", "skills");
33565
+ const dir = path5.join(workspaceDir, ".parall", "skills");
33351
33566
  const lines = SKILLS.map((s) => `- ${s.description.split(":")[0]}: \`${dir}/${s.name}.md\``);
33352
33567
  return `## Platform Skills (read on demand)
33353
33568
 
@@ -33357,7 +33572,7 @@ ${lines.join("\n")}
33357
33572
 
33358
33573
  // ts/claude-agent/dist/config.js
33359
33574
  import * as os2 from "node:os";
33360
- import * as path5 from "node:path";
33575
+ import * as path6 from "node:path";
33361
33576
  function requireEnv(env, name) {
33362
33577
  const value = env[name]?.trim();
33363
33578
  if (!value) {
@@ -33371,15 +33586,15 @@ function parseList(value) {
33371
33586
  return value.split(/[,\n]/).map((item) => item.trim()).filter(Boolean);
33372
33587
  }
33373
33588
  function resolvePath(value) {
33374
- return path5.isAbsolute(value) ? value : path5.resolve(process.cwd(), value);
33589
+ return path6.isAbsolute(value) ? value : path6.resolve(process.cwd(), value);
33375
33590
  }
33376
33591
  function resolveClaudeAgentConfig(env = process.env) {
33377
33592
  const apiUrl = requireEnv(env, "PRLL_API_URL");
33378
33593
  const apiKey = requireEnv(env, "PRLL_API_KEY");
33379
33594
  const orgId = requireEnv(env, "PRLL_ORG_ID");
33380
33595
  const claudeHome = resolvePath(env.PRLL_CLAUDE_HOME?.trim() || env.HOME || os2.homedir());
33381
- const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() || path5.join(claudeHome, ".parall-agent"));
33382
- const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() || path5.join(stateDir, "workspace"));
33596
+ const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() || path6.join(claudeHome, ".parall-agent"));
33597
+ const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() || path6.join(stateDir, "workspace"));
33383
33598
  const additionalDirs = parseList(env.PRLL_CLAUDE_ADD_DIRS).map(resolvePath);
33384
33599
  return {
33385
33600
  apiUrl,
@@ -33414,23 +33629,23 @@ function buildClaudeRuntimeKey(agentUserId) {
33414
33629
  }
33415
33630
  function sessionStateFilePathForRuntime(stateDir, runtimeKey) {
33416
33631
  const fileName = Buffer.from(runtimeKey).toString("base64url");
33417
- return path5.join(stateDir, "sessions", `${fileName}.json`);
33632
+ return path6.join(stateDir, "sessions", `${fileName}.json`);
33418
33633
  }
33419
33634
  function contextFilePathForSession(stateDir, sessionKey) {
33420
33635
  const fileName = Buffer.from(sessionKey).toString("base64url");
33421
- return path5.join(stateDir, "dispatch-context", `${fileName}.json`);
33636
+ return path6.join(stateDir, "dispatch-context", `${fileName}.json`);
33422
33637
  }
33423
33638
  function dispatchContextDirPath(stateDir) {
33424
33639
  return dispatchLaneContextDir(stateDir);
33425
33640
  }
33426
33641
  function stepIdFilePathForSession(stateDir, sessionKey) {
33427
33642
  const fileName = Buffer.from(sessionKey).toString("base64url");
33428
- return path5.join(stateDir, "step-ids", `${fileName}.txt`);
33643
+ return path6.join(stateDir, "step-ids", `${fileName}.txt`);
33429
33644
  }
33430
33645
 
33431
33646
  // ts/claude-agent/dist/dispatch.js
33432
- import * as fs6 from "node:fs";
33433
- import * as path7 from "node:path";
33647
+ import * as fs7 from "node:fs";
33648
+ import * as path8 from "node:path";
33434
33649
  import { randomUUID } from "node:crypto";
33435
33650
  import { execSync as execSync2, spawn } from "node:child_process";
33436
33651
 
@@ -33438,8 +33653,8 @@ import { execSync as execSync2, spawn } from "node:child_process";
33438
33653
  import { execSync } from "node:child_process";
33439
33654
  import { constants } from "node:fs";
33440
33655
  import * as fsSync from "node:fs";
33441
- import * as fs5 from "node:fs/promises";
33442
- import * as path6 from "node:path";
33656
+ import * as fs6 from "node:fs/promises";
33657
+ import * as path7 from "node:path";
33443
33658
  var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
33444
33659
  var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
33445
33660
  var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
@@ -33469,11 +33684,11 @@ async function prepareLocalImageAttachments(event, context2, opts) {
33469
33684
  };
33470
33685
  }
33471
33686
  const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
33472
- const messageDir = path6.join(rootDir, sanitizePathSegment(event.messageId));
33687
+ const messageDir = path7.join(rootDir, sanitizePathSegment(event.messageId));
33473
33688
  await ensurePathIsNotSymlink(messageDir);
33474
- await fs5.mkdir(messageDir, { recursive: true });
33689
+ await fs6.mkdir(messageDir, { recursive: true });
33475
33690
  await ensurePathIsNotSymlink(messageDir);
33476
- const activeMessageDir = path6.resolve(messageDir);
33691
+ const activeMessageDir = path7.resolve(messageDir);
33477
33692
  activeAttachmentDirs.add(activeMessageDir);
33478
33693
  const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
33479
33694
  const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
@@ -33490,7 +33705,7 @@ async function prepareLocalImageAttachments(event, context2, opts) {
33490
33705
  const notes = [];
33491
33706
  let downloadedBytes = 0;
33492
33707
  for (const att of imageAttachments) {
33493
- const localPath = path6.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
33708
+ const localPath = path7.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
33494
33709
  const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
33495
33710
  const fetchFresh = async () => {
33496
33711
  const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
@@ -33547,7 +33762,7 @@ async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
33547
33762
  return { body: appendLocalAttachmentRefs(body, attachments), attachments };
33548
33763
  }
33549
33764
  function pinLocalAttachmentPaths(images) {
33550
- const dirs = new Set(images.map((image) => path6.resolve(path6.dirname(image.localPath))));
33765
+ const dirs = new Set(images.map((image) => path7.resolve(path7.dirname(image.localPath))));
33551
33766
  for (const dir of dirs) {
33552
33767
  activeAttachmentDirs.add(dir);
33553
33768
  }
@@ -33562,7 +33777,7 @@ function pinLocalAttachmentPaths(images) {
33562
33777
  };
33563
33778
  }
33564
33779
  function attachmentRootDir(workspaceDir) {
33565
- return path6.join(path6.resolve(workspaceDir), ".parall", "attachments");
33780
+ return path7.join(path7.resolve(workspaceDir), ".parall", "attachments");
33566
33781
  }
33567
33782
  function ensureLocalAttachmentGitExclude(workingDirectory) {
33568
33783
  try {
@@ -33571,8 +33786,8 @@ function ensureLocalAttachmentGitExclude(workingDirectory) {
33571
33786
  encoding: "utf8",
33572
33787
  stdio: ["ignore", "pipe", "ignore"]
33573
33788
  }).trim();
33574
- const excludePath = path6.isAbsolute(rel) ? rel : path6.join(workingDirectory, rel);
33575
- fsSync.mkdirSync(path6.dirname(excludePath), { recursive: true });
33789
+ const excludePath = path7.isAbsolute(rel) ? rel : path7.join(workingDirectory, rel);
33790
+ fsSync.mkdirSync(path7.dirname(excludePath), { recursive: true });
33576
33791
  const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
33577
33792
  if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
33578
33793
  return;
@@ -33608,18 +33823,18 @@ function scheduleAttachmentMaintenance(rootDir, opts) {
33608
33823
  return run;
33609
33824
  }
33610
33825
  async function ensureAttachmentRootDir(workspaceDir) {
33611
- const workspaceRoot = path6.resolve(workspaceDir);
33612
- const parallDir = path6.join(workspaceRoot, ".parall");
33826
+ const workspaceRoot = path7.resolve(workspaceDir);
33827
+ const parallDir = path7.join(workspaceRoot, ".parall");
33613
33828
  const rootDir = attachmentRootDir(workspaceRoot);
33614
- await fs5.mkdir(workspaceRoot, { recursive: true });
33829
+ await fs6.mkdir(workspaceRoot, { recursive: true });
33615
33830
  await ensurePathIsNotSymlink(parallDir);
33616
- await fs5.mkdir(parallDir, { recursive: true, mode: 448 });
33831
+ await fs6.mkdir(parallDir, { recursive: true, mode: 448 });
33617
33832
  await ensurePathIsNotSymlink(parallDir);
33618
33833
  await ensurePathIsNotSymlink(rootDir);
33619
- await fs5.mkdir(rootDir, { recursive: true, mode: 448 });
33834
+ await fs6.mkdir(rootDir, { recursive: true, mode: 448 });
33620
33835
  await ensurePathIsNotSymlink(rootDir);
33621
- const realWorkspace = await fs5.realpath(workspaceRoot);
33622
- const realRoot = await fs5.realpath(rootDir);
33836
+ const realWorkspace = await fs6.realpath(workspaceRoot);
33837
+ const realRoot = await fs6.realpath(rootDir);
33623
33838
  if (!isPathInside(realRoot, realWorkspace)) {
33624
33839
  throw new Error(`attachment root escapes workspace: ${rootDir}`);
33625
33840
  }
@@ -33627,7 +33842,7 @@ async function ensureAttachmentRootDir(workspaceDir) {
33627
33842
  }
33628
33843
  async function ensurePathIsNotSymlink(filePath) {
33629
33844
  try {
33630
- const stat = await fs5.lstat(filePath);
33845
+ const stat = await fs6.lstat(filePath);
33631
33846
  if (stat.isSymbolicLink()) {
33632
33847
  throw new Error(`refusing to use symlinked attachment path ${filePath}`);
33633
33848
  }
@@ -33638,8 +33853,8 @@ async function ensurePathIsNotSymlink(filePath) {
33638
33853
  }
33639
33854
  }
33640
33855
  function isPathInside(childPath, parentPath) {
33641
- const rel = path6.relative(parentPath, childPath);
33642
- return rel === "" || !!rel && !rel.startsWith("..") && !path6.isAbsolute(rel);
33856
+ const rel = path7.relative(parentPath, childPath);
33857
+ return rel === "" || !!rel && !rel.startsWith("..") && !path7.isAbsolute(rel);
33643
33858
  }
33644
33859
  async function existingUsableFile(filePath, expectedSize, rootDir) {
33645
33860
  try {
@@ -33650,30 +33865,30 @@ async function existingUsableFile(filePath, expectedSize, rootDir) {
33650
33865
  }
33651
33866
  }
33652
33867
  async function localFileStatInsideRoot(filePath, rootDir) {
33653
- const stat = await fs5.lstat(filePath);
33868
+ const stat = await fs6.lstat(filePath);
33654
33869
  if (stat.isSymbolicLink()) {
33655
33870
  throw new Error(`refusing to use symlinked attachment file ${filePath}`);
33656
33871
  }
33657
33872
  if (!stat.isFile()) {
33658
33873
  throw new Error(`attachment path is not a file ${filePath}`);
33659
33874
  }
33660
- const realRoot = await fs5.realpath(rootDir);
33661
- const realFile = await fs5.realpath(filePath);
33875
+ const realRoot = await fs6.realpath(rootDir);
33876
+ const realFile = await fs6.realpath(filePath);
33662
33877
  if (!isPathInside(realFile, realRoot)) {
33663
33878
  throw new Error(`attachment file escapes workspace: ${filePath}`);
33664
33879
  }
33665
33880
  return stat;
33666
33881
  }
33667
33882
  async function localDirectoryStatInsideRoot(dirPath, rootDir) {
33668
- const stat = await fs5.lstat(dirPath);
33883
+ const stat = await fs6.lstat(dirPath);
33669
33884
  if (stat.isSymbolicLink()) {
33670
33885
  throw new Error(`refusing to use symlinked attachment directory ${dirPath}`);
33671
33886
  }
33672
33887
  if (!stat.isDirectory()) {
33673
33888
  throw new Error(`attachment path is not a directory ${dirPath}`);
33674
33889
  }
33675
- const realRoot = await fs5.realpath(rootDir);
33676
- const realDir = await fs5.realpath(dirPath);
33890
+ const realRoot = await fs6.realpath(rootDir);
33891
+ const realDir = await fs6.realpath(dirPath);
33677
33892
  if (!isPathInside(realDir, realRoot)) {
33678
33893
  throw new Error(`attachment directory escapes workspace: ${dirPath}`);
33679
33894
  }
@@ -33681,7 +33896,7 @@ async function localDirectoryStatInsideRoot(dirPath, rootDir) {
33681
33896
  }
33682
33897
  async function openLocalFileInsideRoot(filePath, rootDir) {
33683
33898
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
33684
- const file = await fs5.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
33899
+ const file = await fs6.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
33685
33900
  let keepOpen = false;
33686
33901
  try {
33687
33902
  const openedStat = await file.stat();
@@ -33697,8 +33912,8 @@ async function openLocalFileInsideRoot(filePath, rootDir) {
33697
33912
  }
33698
33913
  }
33699
33914
  async function openLocalTempFileInsideRoot(filePath, rootDir) {
33700
- await localDirectoryStatInsideRoot(path6.dirname(filePath), rootDir);
33701
- const file = await fs5.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
33915
+ await localDirectoryStatInsideRoot(path7.dirname(filePath), rootDir);
33916
+ const file = await fs6.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
33702
33917
  let keepOpen = false;
33703
33918
  try {
33704
33919
  const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
@@ -33723,7 +33938,7 @@ async function assertLocalFileIdentity(filePath, rootDir, expected) {
33723
33938
  async function removeLocalFileIfInside(filePath, rootDir) {
33724
33939
  try {
33725
33940
  await localFileStatInsideRoot(filePath, rootDir);
33726
- await fs5.rm(filePath, { force: true });
33941
+ await fs6.rm(filePath, { force: true });
33727
33942
  } catch {
33728
33943
  }
33729
33944
  }
@@ -33736,7 +33951,7 @@ function sameFile(a, b) {
33736
33951
  async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
33737
33952
  let entries;
33738
33953
  try {
33739
- entries = await fs5.readdir(rootDir, { withFileTypes: true });
33954
+ entries = await fs6.readdir(rootDir, { withFileTypes: true });
33740
33955
  } catch {
33741
33956
  return;
33742
33957
  }
@@ -33744,15 +33959,15 @@ async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
33744
33959
  await Promise.all(entries.map(async (entry) => {
33745
33960
  if (!entry.isDirectory())
33746
33961
  return;
33747
- const fullPath = path6.join(rootDir, entry.name);
33962
+ const fullPath = path7.join(rootDir, entry.name);
33748
33963
  try {
33749
- if (preserveDirs?.has(path6.resolve(fullPath)))
33964
+ if (preserveDirs?.has(path7.resolve(fullPath)))
33750
33965
  return;
33751
- const stat = await fs5.lstat(fullPath);
33966
+ const stat = await fs6.lstat(fullPath);
33752
33967
  if (!stat.isDirectory())
33753
33968
  return;
33754
33969
  if (stat.mtimeMs < cutoff) {
33755
- await fs5.rm(fullPath, { recursive: true, force: true });
33970
+ await fs6.rm(fullPath, { recursive: true, force: true });
33756
33971
  }
33757
33972
  } catch (err) {
33758
33973
  log2?.warn?.(`agent-core: failed to clean attachment temp dir ${fullPath}: ${String(err)}`);
@@ -33764,7 +33979,7 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33764
33979
  return;
33765
33980
  let entries;
33766
33981
  try {
33767
- entries = await fs5.readdir(rootDir, { withFileTypes: true });
33982
+ entries = await fs6.readdir(rootDir, { withFileTypes: true });
33768
33983
  } catch {
33769
33984
  return;
33770
33985
  }
@@ -33773,9 +33988,9 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33773
33988
  for (const entry of entries) {
33774
33989
  if (!entry.isDirectory())
33775
33990
  continue;
33776
- const fullPath = path6.join(rootDir, entry.name);
33991
+ const fullPath = path7.join(rootDir, entry.name);
33777
33992
  try {
33778
- const stat = await fs5.lstat(fullPath);
33993
+ const stat = await fs6.lstat(fullPath);
33779
33994
  if (!stat.isDirectory())
33780
33995
  continue;
33781
33996
  const size = await directorySize(fullPath);
@@ -33791,10 +34006,10 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33791
34006
  for (const dir of dirs) {
33792
34007
  if (total <= maxBytes)
33793
34008
  break;
33794
- if (preserveDirs?.has(path6.resolve(dir.path)))
34009
+ if (preserveDirs?.has(path7.resolve(dir.path)))
33795
34010
  continue;
33796
34011
  try {
33797
- await fs5.rm(dir.path, { recursive: true, force: true });
34012
+ await fs6.rm(dir.path, { recursive: true, force: true });
33798
34013
  total -= dir.size;
33799
34014
  } catch (err) {
33800
34015
  log2?.warn?.(`agent-core: failed to prune attachment cache dir ${dir.path}: ${String(err)}`);
@@ -33803,12 +34018,12 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
33803
34018
  }
33804
34019
  async function directorySize(dirPath) {
33805
34020
  let total = 0;
33806
- const entries = await fs5.readdir(dirPath, { withFileTypes: true });
34021
+ const entries = await fs6.readdir(dirPath, { withFileTypes: true });
33807
34022
  for (const entry of entries) {
33808
- const fullPath = path6.join(dirPath, entry.name);
34023
+ const fullPath = path7.join(dirPath, entry.name);
33809
34024
  let stat;
33810
34025
  try {
33811
- stat = await fs5.lstat(fullPath);
34026
+ stat = await fs6.lstat(fullPath);
33812
34027
  } catch {
33813
34028
  continue;
33814
34029
  }
@@ -33823,10 +34038,10 @@ async function directorySize(dirPath) {
33823
34038
  return total;
33824
34039
  }
33825
34040
  function activeDirsForRoot(rootDir) {
33826
- const root = path6.resolve(rootDir);
34041
+ const root = path7.resolve(rootDir);
33827
34042
  const dirs = /* @__PURE__ */ new Set();
33828
34043
  for (const dir of activeAttachmentDirs) {
33829
- if (dir === root || dir.startsWith(`${root}${path6.sep}`)) {
34044
+ if (dir === root || dir.startsWith(`${root}${path7.sep}`)) {
33830
34045
  dirs.add(dir);
33831
34046
  }
33832
34047
  }
@@ -33923,9 +34138,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
33923
34138
  }
33924
34139
  writtenStat = await file.stat();
33925
34140
  await closeFile();
33926
- await localDirectoryStatInsideRoot(path6.dirname(filePath), rootDir);
34141
+ await localDirectoryStatInsideRoot(path7.dirname(filePath), rootDir);
33927
34142
  await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
33928
- await fs5.rename(tmpPath, filePath);
34143
+ await fs6.rename(tmpPath, filePath);
33929
34144
  completed = true;
33930
34145
  return written;
33931
34146
  } finally {
@@ -33941,9 +34156,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
33941
34156
  }
33942
34157
  }
33943
34158
  function localFileName(attachmentId, fileName, mimeType) {
33944
- const safeName = sanitizePathSegment(path6.basename(fileName || attachmentId));
33945
- const ext = path6.extname(safeName) || extensionForMime(mimeType);
33946
- const stem = path6.basename(safeName, path6.extname(safeName)) || attachmentId;
34159
+ const safeName = sanitizePathSegment(path7.basename(fileName || attachmentId));
34160
+ const ext = path7.extname(safeName) || extensionForMime(mimeType);
34161
+ const stem = path7.basename(safeName, path7.extname(safeName)) || attachmentId;
33947
34162
  return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
33948
34163
  }
33949
34164
  function extensionForMime(mimeType) {
@@ -34235,6 +34450,11 @@ function buildSpawnEnv(parentEnv, claudeHome, context2, opts) {
34235
34450
  if (opts.effortLevel) {
34236
34451
  result.CLAUDE_CODE_EFFORT_LEVEL = opts.effortLevel;
34237
34452
  }
34453
+ if (opts.capabilityBinDir) {
34454
+ const pathKey = process.platform === "win32" ? Object.keys(result).find((k) => k.toUpperCase() === "PATH") ?? "PATH" : "PATH";
34455
+ const existing = result[pathKey];
34456
+ result[pathKey] = existing ? `${opts.capabilityBinDir}${path8.delimiter}${existing}` : opts.capabilityBinDir;
34457
+ }
34238
34458
  return result;
34239
34459
  }
34240
34460
  var ClaudeCodeAdapter = class {
@@ -34262,9 +34482,18 @@ var ClaudeCodeAdapter = class {
34262
34482
  if (effortChanged)
34263
34483
  this._effortLevel = config.effort ?? void 0;
34264
34484
  if (modelChanged || effortChanged) {
34265
- for (const [, state] of this.processes) {
34266
- state.needsRestart = true;
34267
- }
34485
+ this.requestProcessRestart();
34486
+ }
34487
+ }
34488
+ // Mark every live subprocess for a lazy respawn (applied at its next
34489
+ // dispatch; the session survives via --resume) — the same mechanism
34490
+ // updateConfig uses for model/effort changes. For spawn-time inputs that
34491
+ // live OUTSIDE this adapter's config, e.g. the .parall/system-prompt.md
34492
+ // file: a long-lived process read it via --append-system-prompt-file at
34493
+ // spawn, so a capability declaration change only reaches it by respawning.
34494
+ requestProcessRestart() {
34495
+ for (const [, state] of this.processes) {
34496
+ state.needsRestart = true;
34268
34497
  }
34269
34498
  }
34270
34499
  enqueueDuringDispatch(sessionKey, body) {
@@ -34333,8 +34562,8 @@ var ClaudeCodeAdapter = class {
34333
34562
  if (!sessionId)
34334
34563
  return void 0;
34335
34564
  const projectSlug = this.opts.workspaceDir.replace(/[/.]/g, "-");
34336
- const filePath = path7.join(this.opts.claudeHome, ".claude", "projects", projectSlug, `${sessionId}.jsonl`);
34337
- return fs6.existsSync(filePath) ? filePath : void 0;
34565
+ const filePath = path8.join(this.opts.claudeHome, ".claude", "projects", projectSlug, `${sessionId}.jsonl`);
34566
+ return fs7.existsSync(filePath) ? filePath : void 0;
34338
34567
  }
34339
34568
  forkSession({ sessionKey }) {
34340
34569
  return this.opts.sessionManager.createForkSession(sessionKey);
@@ -34541,7 +34770,8 @@ var ClaudeCodeAdapter = class {
34541
34770
  const env = buildSpawnEnv(process.env, this.opts.claudeHome, this.buildPlaceholderContext(sessionKey), {
34542
34771
  allowApiKey: this.opts.allowApiKey,
34543
34772
  effortLevel: this._effortLevel,
34544
- wikiMountRoot: this.opts.workspaceDir
34773
+ wikiMountRoot: this.opts.workspaceDir,
34774
+ capabilityBinDir: this.opts.capabilityBinDir
34545
34775
  });
34546
34776
  log2?.info(`spawn long-lived ${this.opts.claudeBin} (session ${sessionKey}, model=${this._model || "default"}, effort=${this._effortLevel || "default"}, mode=${this.opts.permissionMode})`);
34547
34777
  const proc = spawn(IS_WIN32 ? quoteWin32Arg(this.opts.claudeBin) : this.opts.claudeBin, IS_WIN32 ? args.map(quoteWin32Arg) : args, {
@@ -34620,7 +34850,7 @@ var ClaudeCodeAdapter = class {
34620
34850
  if (this.opts.disallowedTools.length > 0) {
34621
34851
  args.push("--disallowedTools", this.opts.disallowedTools.join(","));
34622
34852
  }
34623
- args.push("--append-system-prompt-file", path7.join(this.opts.workspaceDir, ".parall", "system-prompt.md"));
34853
+ args.push("--append-system-prompt-file", path8.join(this.opts.workspaceDir, ".parall", "system-prompt.md"));
34624
34854
  if (this.opts.appendSystemPrompt) {
34625
34855
  args.push("--append-system-prompt", this.opts.appendSystemPrompt);
34626
34856
  }
@@ -34652,8 +34882,8 @@ var ClaudeCodeAdapter = class {
34652
34882
  };
34653
34883
 
34654
34884
  // ts/claude-agent/dist/session-manager.js
34655
- import * as fs7 from "node:fs";
34656
- import * as path8 from "node:path";
34885
+ import * as fs8 from "node:fs";
34886
+ import * as path9 from "node:path";
34657
34887
  import { randomUUID as randomUUID2 } from "node:crypto";
34658
34888
  var ClaudeSessionManager = class _ClaudeSessionManager {
34659
34889
  mainSessionKey;
@@ -34802,13 +35032,13 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
34802
35032
  clearMainSession() {
34803
35033
  this.sessionIds.delete(this.mainSessionKey);
34804
35034
  try {
34805
- fs7.unlinkSync(this.stateFilePath);
35035
+ fs8.unlinkSync(this.stateFilePath);
34806
35036
  } catch {
34807
35037
  }
34808
35038
  }
34809
35039
  restore() {
34810
35040
  try {
34811
- const raw = fs7.readFileSync(this.stateFilePath, "utf8");
35041
+ const raw = fs8.readFileSync(this.stateFilePath, "utf8");
34812
35042
  const parsed = JSON.parse(raw);
34813
35043
  if (parsed.runtimeKey === this.mainSessionKey && typeof parsed.sessionId === "string" && parsed.sessionId.trim()) {
34814
35044
  this.sessionIds.set(this.mainSessionKey, parsed.sessionId.trim());
@@ -34818,8 +35048,8 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
34818
35048
  }
34819
35049
  persist(sessionId) {
34820
35050
  try {
34821
- fs7.mkdirSync(path8.dirname(this.stateFilePath), { recursive: true });
34822
- fs7.writeFileSync(this.stateFilePath, JSON.stringify({
35051
+ fs8.mkdirSync(path9.dirname(this.stateFilePath), { recursive: true });
35052
+ fs8.writeFileSync(this.stateFilePath, JSON.stringify({
34823
35053
  runtimeKey: this.mainSessionKey,
34824
35054
  sessionId
34825
35055
  }, null, 2));
@@ -34830,22 +35060,31 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
34830
35060
  };
34831
35061
 
34832
35062
  // ts/claude-agent/dist/workspace.js
34833
- import * as fs8 from "node:fs";
34834
- import * as path9 from "node:path";
34835
- function ensureClaudeWorkspace(workspaceDir, log2, agentIdentity) {
34836
- const systemPrompt = [
35063
+ import * as fs9 from "node:fs";
35064
+ import * as path10 from "node:path";
35065
+ function buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
35066
+ const parts = [
34837
35067
  buildIdentity(agentIdentity),
34838
35068
  BRIDGE_WORKSPACE_INSTRUCTIONS,
34839
35069
  PRLL_BEHAVIOR,
34840
- PRLL_REFERENCE_GUIDE,
34841
- buildSkillReferences(workspaceDir)
34842
- ].join("\n\n");
34843
- fs8.mkdirSync(workspaceDir, { recursive: true });
34844
- fs8.mkdirSync(path9.join(workspaceDir, ".claude"), { recursive: true });
34845
- const parallDir = path9.join(workspaceDir, ".parall");
34846
- fs8.mkdirSync(parallDir, { recursive: true });
34847
- fs8.writeFileSync(path9.join(parallDir, "system-prompt.md"), systemPrompt, "utf8");
34848
- writeSkillFiles(path9.join(parallDir, "skills"));
35070
+ PRLL_REFERENCE_GUIDE
35071
+ ];
35072
+ if (capabilityFragments && capabilityFragments.length > 0) {
35073
+ parts.push(capabilityFragments.join("\n\n"));
35074
+ }
35075
+ parts.push(buildSkillReferences(workspaceDir));
35076
+ return parts.join("\n\n");
35077
+ }
35078
+ function writeClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
35079
+ const parallDir = path10.join(workspaceDir, ".parall");
35080
+ fs9.mkdirSync(parallDir, { recursive: true });
35081
+ fs9.writeFileSync(path10.join(parallDir, "system-prompt.md"), buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments), "utf8");
35082
+ }
35083
+ function ensureClaudeWorkspace(workspaceDir, log2, agentIdentity, capabilityFragments) {
35084
+ fs9.mkdirSync(workspaceDir, { recursive: true });
35085
+ fs9.mkdirSync(path10.join(workspaceDir, ".claude"), { recursive: true });
35086
+ writeClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments);
35087
+ writeSkillFiles(path10.join(workspaceDir, ".parall", "skills"));
34849
35088
  ensureLocalAttachmentGitExclude(workspaceDir);
34850
35089
  }
34851
35090
 
@@ -34900,11 +35139,11 @@ async function main() {
34900
35139
  const agentUserId = me.id;
34901
35140
  const agentLog = childLogger(activeLog, agentUserId);
34902
35141
  activeLog = agentLog;
34903
- ensureClaudeWorkspace(config.workspaceDir, agentLog, {
35142
+ const agentIdentity = {
34904
35143
  userId: agentUserId,
34905
35144
  displayName: me.display_name,
34906
35145
  description: me.agent_profile?.description ?? void 0
34907
- });
35146
+ };
34908
35147
  const runtimeKey = config.runtimeKey || buildClaudeRuntimeKey(agentUserId);
34909
35148
  const sessionStateFilePath = sessionStateFilePathForRuntime(config.stateDir, runtimeKey);
34910
35149
  const sessionManager = new ClaudeSessionManager(runtimeKey, sessionStateFilePath, agentLog);
@@ -34920,6 +35159,14 @@ async function main() {
34920
35159
  log: agentLog
34921
35160
  });
34922
35161
  const platformDefaults = await configMgr.fetch();
35162
+ const applyChannelCapabilities = () => {
35163
+ const caps = configMgr.capabilities();
35164
+ materializeChannelCapabilities(config.stateDir, caps, agentLog);
35165
+ return caps.map((c) => c.fragment);
35166
+ };
35167
+ const bootCapabilityFragments = applyChannelCapabilities();
35168
+ let lastCapabilityFragments = bootCapabilityFragments.join("\n\n");
35169
+ ensureClaudeWorkspace(config.workspaceDir, agentLog, agentIdentity, bootCapabilityFragments);
34923
35170
  const platformModelOverride = deriveModelIsPin(platformDefaults, me.agent_profile);
34924
35171
  const resolvedModel = resolveRuntimeModel(platformModelOverride, platformDefaults.model, config.model);
34925
35172
  const resolvedEffort = platformDefaults.thinkingEffort ?? (process.env.CLAUDE_CODE_EFFORT_LEVEL?.trim() || void 0);
@@ -34947,7 +35194,10 @@ async function main() {
34947
35194
  orgId: config.orgId,
34948
35195
  contextFilePathForSession: (sessionKey) => contextFilePathForSession(config.stateDir, sessionKey),
34949
35196
  stepIdFilePathForSession: (sessionKey) => stepIdFilePathForSession(config.stateDir, sessionKey),
34950
- contextDirPath: dispatchContextDirPath(config.stateDir)
35197
+ contextDirPath: dispatchContextDirPath(config.stateDir),
35198
+ // Constant PATH prepend; the directory's content (the lark-cli shim)
35199
+ // tracks capability grants, so add/remove reaches live subprocesses.
35200
+ capabilityBinDir: capabilityBinDir(config.stateDir)
34951
35201
  });
34952
35202
  if (resolvedEffort) {
34953
35203
  adapter.updateConfig({ effort: resolvedEffort });
@@ -34968,6 +35218,19 @@ async function main() {
34968
35218
  model: resolveRuntimeModel(isPin, updated.model, config.model) ?? null,
34969
35219
  effort: updated.thinkingEffort ?? localEffort
34970
35220
  });
35221
+ const fragments = applyChannelCapabilities();
35222
+ const joinedFragments = fragments.join("\n\n");
35223
+ let promptWritten = true;
35224
+ try {
35225
+ writeClaudeSystemPrompt(config.workspaceDir, agentIdentity, fragments);
35226
+ } catch (err) {
35227
+ promptWritten = false;
35228
+ agentLog.warn(`system prompt refresh write failed (retrying next refresh): ${String(err)}`);
35229
+ }
35230
+ if (promptWritten && joinedFragments !== lastCapabilityFragments) {
35231
+ lastCapabilityFragments = joinedFragments;
35232
+ adapter.requestProcessRestart();
35233
+ }
34971
35234
  };
34972
35235
  const gateway = new ParallAgentGateway({
34973
35236
  accountId: agentUserId,
@@ -34990,6 +35253,11 @@ async function main() {
34990
35253
  },
34991
35254
  dispatchAdapter: adapter,
34992
35255
  log: agentLog,
35256
+ // Live capability view for hint routing: the channel reply hint points
35257
+ // at the vendor CLI only while the grant is active (config manager
35258
+ // re-fetches on agent_config.update, so revocation reaches the very
35259
+ // next dispatch's hint).
35260
+ getCapabilityKeys: () => configMgr.capabilities().map((c) => c.key),
34993
35261
  shutdownDeadlineMs: parseShutdownDeadlineMs(process.env.PRLL_SHUTDOWN_DEADLINE_MS),
34994
35262
  forkDeadlineMs: parseForkDeadlineMs(process.env.PRLL_FORK_DEADLINE_MS),
34995
35263
  dispatchDeadlineMs: parseDispatchDeadlineMs(process.env.PRLL_DISPATCH_DEADLINE_MS),