@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.
- package/bundle/manifest.json +15 -11
- package/bundle/parall-browser-pod.js +26 -16
- package/bundle/parall-channel-exec.js +224 -0
- package/bundle/parall-claude-agent.js +1736 -1468
- package/bundle/parall-codex-agent.js +1775 -1502
- package/bundle/parall-daemon.js +384 -215
- package/dist/clip-runtime/hub-client.d.ts +1 -1
- package/dist/clip-runtime/hub-client.js +1 -1
- package/dist/clip-runtime/process-manager.d.ts +2 -2
- package/dist/clip-runtime/process-manager.js +2 -2
- package/dist/config.d.ts +9 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +5 -0
- package/dist/home-isolation.d.ts +68 -0
- package/dist/home-isolation.d.ts.map +1 -0
- package/dist/home-isolation.js +130 -0
- package/dist/runtimes.d.ts +7 -0
- package/dist/runtimes.d.ts.map +1 -1
- package/dist/runtimes.js +20 -0
- package/dist/supervisor.d.ts +8 -1
- package/dist/supervisor.d.ts.map +1 -1
- package/dist/supervisor.js +97 -45
- package/package.json +6 -6
|
@@ -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
|
|
17721
|
+
for (const path11 of paths) {
|
|
17722
17722
|
try {
|
|
17723
|
-
const result = await fs_1.promises.readFile(
|
|
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,
|
|
21126
|
+
function appendResourcePathToUrl(url, path11) {
|
|
21127
21127
|
try {
|
|
21128
21128
|
new URL(url);
|
|
21129
21129
|
} catch (_a) {
|
|
@@ -21133,11 +21133,11 @@ function appendResourcePathToUrl(url, path9) {
|
|
|
21133
21133
|
if (!url.endsWith("/")) {
|
|
21134
21134
|
url = url + "/";
|
|
21135
21135
|
}
|
|
21136
|
-
url +=
|
|
21136
|
+
url += path11;
|
|
21137
21137
|
try {
|
|
21138
21138
|
new URL(url);
|
|
21139
21139
|
} catch (_b) {
|
|
21140
|
-
diag2.warn("Configuration: Provided URL appended with '" +
|
|
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/
|
|
26491
|
-
|
|
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
|
-
|
|
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(
|
|
27704
|
-
return
|
|
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(
|
|
27030
|
+
async ensureFreshToken(path11) {
|
|
27732
27031
|
if (!this.token || !this.getRefreshToken)
|
|
27733
27032
|
return;
|
|
27734
|
-
const pathSuffix =
|
|
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,
|
|
27065
|
+
async request(method, path11, body, query, retried = false, opts) {
|
|
27767
27066
|
if (!retried) {
|
|
27768
|
-
await this.ensureFreshToken(
|
|
27067
|
+
await this.ensureFreshToken(path11);
|
|
27769
27068
|
}
|
|
27770
|
-
let url = `${this.baseUrlFor(
|
|
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 =
|
|
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,
|
|
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,
|
|
27134
|
+
async multipartRequest(method, path11, body, retried = false) {
|
|
27836
27135
|
if (!retried) {
|
|
27837
|
-
await this.ensureFreshToken(
|
|
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(
|
|
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 =
|
|
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,
|
|
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,
|
|
28563
|
-
return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path:
|
|
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,
|
|
29133
|
-
return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), 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,
|
|
28441
|
+
async getWikiFileCommits(orgId, wikiId, path11, params) {
|
|
29143
28442
|
return this.request("GET", ENDPOINTS.WIKI_FILE_COMMITS(orgId, wikiId), void 0, {
|
|
29144
|
-
path:
|
|
28443
|
+
path: path11,
|
|
29145
28444
|
...params
|
|
29146
28445
|
});
|
|
29147
28446
|
}
|
|
29148
|
-
async getWikiBlame(orgId, wikiId,
|
|
29149
|
-
return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path:
|
|
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,706 +28795,1484 @@ 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
|
-
|
|
29503
|
-
|
|
29504
|
-
|
|
29505
|
-
|
|
29506
|
-
|
|
29507
|
-
|
|
29508
|
-
|
|
29509
|
-
|
|
29510
|
-
|
|
29511
|
-
|
|
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
|
-
|
|
29068
|
+
this.probeConnection();
|
|
29514
29069
|
}
|
|
29515
|
-
|
|
29516
|
-
|
|
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.
|
|
29084
|
+
this.probeConnection();
|
|
29519
29085
|
}
|
|
29520
|
-
|
|
29086
|
+
} else if (this._state === "reconnecting") {
|
|
29087
|
+
this.clearReconnect();
|
|
29088
|
+
this.reconnectAttempts = 0;
|
|
29089
|
+
this.connect();
|
|
29521
29090
|
}
|
|
29522
|
-
|
|
29523
|
-
|
|
29524
|
-
|
|
29525
|
-
|
|
29526
|
-
|
|
29091
|
+
};
|
|
29092
|
+
setState(state) {
|
|
29093
|
+
this._state = state;
|
|
29094
|
+
for (const listener of this.stateListeners) {
|
|
29095
|
+
listener(state);
|
|
29527
29096
|
}
|
|
29528
|
-
|
|
29529
|
-
|
|
29530
|
-
|
|
29531
|
-
|
|
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
|
-
|
|
29534
|
-
|
|
29535
|
-
|
|
29536
|
-
|
|
29537
|
-
|
|
29538
|
-
|
|
29539
|
-
|
|
29540
|
-
|
|
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
|
-
|
|
29543
|
-
|
|
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 (
|
|
29546
|
-
|
|
29547
|
-
|
|
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
|
-
|
|
29553
|
-
|
|
29554
|
-
|
|
29555
|
-
|
|
29556
|
-
|
|
29557
|
-
|
|
29558
|
-
|
|
29559
|
-
|
|
29560
|
-
|
|
29561
|
-
|
|
29562
|
-
|
|
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
|
-
|
|
29567
|
-
|
|
29568
|
-
|
|
29569
|
-
|
|
29570
|
-
|
|
29571
|
-
this.
|
|
29572
|
-
|
|
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
|
-
|
|
29575
|
-
|
|
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.
|
|
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
|
-
|
|
29601
|
-
|
|
29602
|
-
|
|
29603
|
-
|
|
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
|
-
/**
|
|
29607
|
-
|
|
29608
|
-
|
|
29609
|
-
|
|
29610
|
-
|
|
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
|
-
|
|
29614
|
-
|
|
29615
|
-
|
|
29616
|
-
|
|
29617
|
-
|
|
29618
|
-
|
|
29619
|
-
|
|
29620
|
-
|
|
29621
|
-
|
|
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
29308
|
}
|
|
29628
|
-
|
|
29629
|
-
this.
|
|
29309
|
+
async releaseAll() {
|
|
29310
|
+
const keys = [...this.lanes.keys()];
|
|
29311
|
+
for (const key of keys) {
|
|
29312
|
+
await this.release(key);
|
|
29313
|
+
}
|
|
29630
29314
|
}
|
|
29631
|
-
|
|
29632
|
-
|
|
29633
|
-
return
|
|
29634
|
-
this.stateListeners.delete(handler);
|
|
29635
|
-
};
|
|
29315
|
+
/** True when any lane is currently active (used by shutdown logging). */
|
|
29316
|
+
get activeCount() {
|
|
29317
|
+
return this.lanes.size;
|
|
29636
29318
|
}
|
|
29637
|
-
|
|
29638
|
-
|
|
29639
|
-
|
|
29640
|
-
|
|
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;
|
|
29641
29337
|
}
|
|
29338
|
+
if (!res.claimed || !res.lane || !res.events?.length)
|
|
29339
|
+
return null;
|
|
29340
|
+
const workItem = res.events[0];
|
|
29341
|
+
const targetUri = `dsp:${workItem.id}`;
|
|
29342
|
+
const leaseUntilMs = Date.parse(res.lease_until ?? "");
|
|
29343
|
+
const lane = {
|
|
29344
|
+
laneKey: laneKeyForTarget(targetUri),
|
|
29345
|
+
lane: res.lane,
|
|
29346
|
+
targetUri,
|
|
29347
|
+
folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
|
|
29348
|
+
typedDispatchEventId: workItem.id,
|
|
29349
|
+
...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
|
|
29350
|
+
};
|
|
29351
|
+
this.lanes.set(lane.laneKey, lane);
|
|
29352
|
+
return lane;
|
|
29642
29353
|
}
|
|
29643
|
-
|
|
29644
|
-
|
|
29645
|
-
|
|
29646
|
-
|
|
29647
|
-
|
|
29648
|
-
|
|
29649
|
-
|
|
29650
|
-
|
|
29651
|
-
|
|
29652
|
-
|
|
29653
|
-
|
|
29654
|
-
|
|
29655
|
-
for (const handler of handlers) {
|
|
29656
|
-
handler(frame.data, frame.seq);
|
|
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 {
|
|
29657
29366
|
}
|
|
29658
29367
|
}
|
|
29659
29368
|
}
|
|
29660
|
-
|
|
29661
|
-
|
|
29662
|
-
|
|
29663
|
-
|
|
29664
|
-
|
|
29665
|
-
|
|
29666
|
-
|
|
29667
|
-
|
|
29668
|
-
|
|
29669
|
-
|
|
29670
|
-
|
|
29671
|
-
|
|
29672
|
-
|
|
29673
|
-
|
|
29674
|
-
|
|
29675
|
-
|
|
29676
|
-
|
|
29677
|
-
|
|
29678
|
-
|
|
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
|
+
});
|
|
29679
29392
|
}
|
|
29393
|
+
return "dispatched";
|
|
29680
29394
|
}
|
|
29681
|
-
|
|
29682
|
-
|
|
29683
|
-
|
|
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;
|
|
29395
|
+
if (!lane) {
|
|
29396
|
+
for (const ev of opts.events) {
|
|
29397
|
+
host.dispatchedMessages.delete(ev.messageId);
|
|
29695
29398
|
}
|
|
29399
|
+
return "foreign";
|
|
29696
29400
|
}
|
|
29697
|
-
|
|
29698
|
-
|
|
29699
|
-
|
|
29700
|
-
|
|
29701
|
-
|
|
29702
|
-
|
|
29703
|
-
|
|
29704
|
-
|
|
29705
|
-
|
|
29706
|
-
|
|
29707
|
-
|
|
29708
|
-
|
|
29709
|
-
|
|
29710
|
-
|
|
29711
|
-
|
|
29712
|
-
|
|
29713
|
-
|
|
29714
|
-
|
|
29715
|
-
|
|
29716
|
-
|
|
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((resolve4) => {
|
|
29427
|
+
const timer = setTimeout(resolve4, waitMs);
|
|
29428
|
+
timer.unref?.();
|
|
29429
|
+
});
|
|
29717
29430
|
}
|
|
29431
|
+
if (host.shuttingDown)
|
|
29432
|
+
return;
|
|
29718
29433
|
}
|
|
29719
|
-
|
|
29720
|
-
|
|
29721
|
-
if (
|
|
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
|
-
|
|
29728
|
-
|
|
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);
|
|
29729
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);
|
|
29457
|
+
}
|
|
29458
|
+
};
|
|
29459
|
+
if (!host.laneLedger || host.ledgerDisabled) {
|
|
29460
|
+
await runLegacy();
|
|
29461
|
+
return;
|
|
29730
29462
|
}
|
|
29731
|
-
|
|
29732
|
-
|
|
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
|
-
|
|
29744
|
-
|
|
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
|
-
|
|
29756
|
-
|
|
29757
|
-
|
|
29758
|
-
|
|
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
|
-
|
|
29762
|
-
|
|
29763
|
-
|
|
29764
|
-
|
|
29765
|
-
|
|
29766
|
-
|
|
29767
|
-
|
|
29768
|
-
|
|
29769
|
-
|
|
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
|
-
|
|
29778
|
-
|
|
29779
|
-
|
|
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
|
-
|
|
29794
|
-
|
|
29795
|
-
|
|
29796
|
-
|
|
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" };
|
|
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" };
|
|
29798
29626
|
}
|
|
29627
|
+
return { action: "new-fork" };
|
|
29799
29628
|
};
|
|
29800
|
-
|
|
29801
|
-
|
|
29802
|
-
|
|
29803
|
-
|
|
29804
|
-
|
|
29805
|
-
|
|
29806
|
-
return
|
|
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
|
-
|
|
29809
|
-
|
|
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
|
-
|
|
29812
|
-
|
|
29813
|
-
|
|
29814
|
-
|
|
29815
|
-
|
|
29816
|
-
|
|
29817
|
-
|
|
29818
|
-
|
|
29819
|
-
|
|
29820
|
-
|
|
29821
|
-
|
|
29822
|
-
|
|
29823
|
-
|
|
29824
|
-
|
|
29825
|
-
|
|
29826
|
-
|
|
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
|
-
|
|
29829
|
-
|
|
29830
|
-
|
|
29831
|
-
|
|
29832
|
-
|
|
29833
|
-
|
|
29834
|
-
|
|
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
|
-
|
|
29880
|
-
|
|
29881
|
-
|
|
29882
|
-
|
|
29883
|
-
const
|
|
29884
|
-
|
|
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
|
-
|
|
29901
|
-
}
|
|
29902
|
-
|
|
29903
|
-
|
|
29904
|
-
|
|
29905
|
-
|
|
29906
|
-
|
|
29907
|
-
|
|
29908
|
-
|
|
29909
|
-
|
|
29910
|
-
|
|
29911
|
-
|
|
29912
|
-
|
|
29913
|
-
if (
|
|
29914
|
-
|
|
29915
|
-
|
|
29916
|
-
|
|
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
|
-
|
|
29935
|
-
|
|
29936
|
-
|
|
29937
|
-
|
|
29938
|
-
|
|
29939
|
-
|
|
29940
|
-
|
|
29941
|
-
|
|
29942
|
-
|
|
29943
|
-
|
|
29944
|
-
|
|
29945
|
-
|
|
29946
|
-
|
|
29947
|
-
|
|
29948
|
-
|
|
29949
|
-
|
|
29950
|
-
});
|
|
29951
|
-
|
|
29952
|
-
|
|
29953
|
-
|
|
29954
|
-
|
|
29955
|
-
|
|
29956
|
-
|
|
29957
|
-
|
|
29958
|
-
|
|
29959
|
-
|
|
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}]`);
|
|
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)}]`);
|
|
29960
29741
|
}
|
|
29742
|
+
lines.push("", event.body);
|
|
29743
|
+
} else {
|
|
29744
|
+
lines.push(`[Event: task.assigned]`);
|
|
29745
|
+
const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
|
|
29746
|
+
lines.push(`[Task: ${taskLabel}]`);
|
|
29747
|
+
lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
|
|
29748
|
+
lines.push("", event.body);
|
|
29961
29749
|
}
|
|
29962
|
-
|
|
29963
|
-
|
|
29964
|
-
|
|
29965
|
-
|
|
29966
|
-
|
|
29967
|
-
|
|
29968
|
-
|
|
29969
|
-
|
|
29970
|
-
|
|
29971
|
-
const
|
|
29972
|
-
|
|
29973
|
-
|
|
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
|
-
|
|
29996
|
-
|
|
29997
|
-
|
|
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
|
-
|
|
30012
|
-
|
|
30013
|
-
|
|
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
|
-
|
|
30018
|
-
|
|
30019
|
-
|
|
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
|
-
|
|
30023
|
-
|
|
30024
|
-
|
|
30025
|
-
|
|
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
|
-
|
|
30041
|
-
|
|
30042
|
-
|
|
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
|
-
|
|
30058
|
-
|
|
30059
|
-
|
|
30060
|
-
|
|
30061
|
-
|
|
30062
|
-
|
|
30063
|
-
|
|
30064
|
-
|
|
30065
|
-
|
|
30066
|
-
|
|
30067
|
-
|
|
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.
|
|
30184
|
+
|
|
30185
|
+
Supported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with \`parall files download att_xxx --output ...\`.
|
|
30072
30186
|
|
|
30073
|
-
|
|
30074
|
-
|
|
30075
|
-
|
|
30076
|
-
|
|
30077
|
-
|
|
30078
|
-
|
|
30079
|
-
|
|
30080
|
-
|
|
30081
|
-
|
|
30082
|
-
|
|
30083
|
-
|
|
30084
|
-
|
|
30085
|
-
|
|
30086
|
-
|
|
30087
|
-
|
|
30088
|
-
|
|
30089
|
-
|
|
30090
|
-
|
|
30091
|
-
|
|
30092
|
-
|
|
30093
|
-
|
|
30094
|
-
|
|
30095
|
-
|
|
30096
|
-
|
|
30097
|
-
|
|
30098
|
-
|
|
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";
|
|
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
|
-
|
|
30119
|
-
|
|
30120
|
-
|
|
30121
|
-
|
|
30122
|
-
|
|
30123
|
-
}
|
|
30124
|
-
|
|
30125
|
-
|
|
30126
|
-
|
|
30127
|
-
|
|
30128
|
-
|
|
30129
|
-
|
|
30130
|
-
|
|
30131
|
-
|
|
30132
|
-
|
|
30133
|
-
|
|
30134
|
-
|
|
30135
|
-
|
|
30136
|
-
|
|
30137
|
-
|
|
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
|
-
|
|
30149
|
-
if (
|
|
30150
|
-
return;
|
|
30151
|
-
|
|
30152
|
-
|
|
30153
|
-
|
|
30154
|
-
|
|
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
|
-
|
|
30158
|
-
|
|
30159
|
-
|
|
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
|
-
}
|
|
30266
|
+
}
|
|
30267
|
+
function childLogger(logger, sub) {
|
|
30268
|
+
return logger.child ? logger.child(sub) : logger;
|
|
30197
30269
|
}
|
|
30198
30270
|
|
|
30271
|
+
// ts/agent-core/dist/gateway-base.js
|
|
30272
|
+
import * as os from "node:os";
|
|
30273
|
+
import * as fs2 from "node:fs";
|
|
30274
|
+
import * as path2 from "node:path";
|
|
30275
|
+
|
|
30199
30276
|
// ts/agent-core/dist/telemetry.js
|
|
30200
30277
|
init_esm();
|
|
30201
30278
|
var import_api_logs = __toESM(require_src(), 1);
|
|
@@ -30476,6 +30553,9 @@ var ParallAgentGateway = class {
|
|
|
30476
30553
|
// (stable mapping; avoids one connection fetch per inbound message).
|
|
30477
30554
|
channelConnectionProviders = /* @__PURE__ */ new Map();
|
|
30478
30555
|
dispatchedMessages = /* @__PURE__ */ new Set();
|
|
30556
|
+
// Per-WorkItem failure backoff for typed dispatch consumption — see
|
|
30557
|
+
// LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
|
|
30558
|
+
typedRedriveBackoff = /* @__PURE__ */ new Map();
|
|
30479
30559
|
forkStates = /* @__PURE__ */ new Map();
|
|
30480
30560
|
dispatchState = {
|
|
30481
30561
|
mainDispatching: false,
|
|
@@ -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(() =>
|
|
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(() =>
|
|
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/
|
|
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
|
|
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
|
|
32644
|
-
# MESSAGE hits to one chat (tasks/wiki are unaffected
|
|
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,
|
|
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
|
-
|
|
33559
|
+
fs5.mkdirSync(targetDir, { recursive: true });
|
|
33345
33560
|
for (const skill of SKILLS) {
|
|
33346
|
-
|
|
33561
|
+
fs5.writeFileSync(path5.join(targetDir, `${skill.name}.md`), skill.content, "utf8");
|
|
33347
33562
|
}
|
|
33348
33563
|
}
|
|
33349
33564
|
function buildSkillReferences(workspaceDir) {
|
|
33350
|
-
const dir =
|
|
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/codex-agent/dist/config.js
|
|
33359
33574
|
import * as os2 from "node:os";
|
|
33360
|
-
import * as
|
|
33575
|
+
import * as path6 from "node:path";
|
|
33361
33576
|
function requireEnv(env, name) {
|
|
33362
33577
|
const value = env[name]?.trim();
|
|
33363
33578
|
if (!value) {
|
|
@@ -33366,15 +33581,15 @@ function requireEnv(env, name) {
|
|
|
33366
33581
|
return value;
|
|
33367
33582
|
}
|
|
33368
33583
|
function resolvePath(value) {
|
|
33369
|
-
return
|
|
33584
|
+
return path6.isAbsolute(value) ? value : path6.resolve(process.cwd(), value);
|
|
33370
33585
|
}
|
|
33371
33586
|
function resolveCodexAgentConfig(env = process.env) {
|
|
33372
33587
|
const apiUrl = requireEnv(env, "PRLL_API_URL");
|
|
33373
33588
|
const apiKey = requireEnv(env, "PRLL_API_KEY");
|
|
33374
33589
|
const orgId = requireEnv(env, "PRLL_ORG_ID");
|
|
33375
|
-
const codexHome = resolvePath(env.PRLL_CODEX_HOME?.trim() || env.CODEX_HOME?.trim() ||
|
|
33376
|
-
const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() ||
|
|
33377
|
-
const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() ||
|
|
33590
|
+
const codexHome = resolvePath(env.PRLL_CODEX_HOME?.trim() || env.CODEX_HOME?.trim() || path6.join(env.HOME || os2.homedir(), ".codex"));
|
|
33591
|
+
const stateDir = resolvePath(env.PRLL_STATE_DIR?.trim() || path6.join(env.HOME || os2.homedir(), ".parall-agent"));
|
|
33592
|
+
const workspaceDir = resolvePath(env.PRLL_WORKSPACE_DIR?.trim() || path6.join(stateDir, "workspace"));
|
|
33378
33593
|
return {
|
|
33379
33594
|
apiUrl,
|
|
33380
33595
|
apiKey,
|
|
@@ -33430,31 +33645,32 @@ function buildCodexRuntimeKey(agentUserId) {
|
|
|
33430
33645
|
}
|
|
33431
33646
|
function sessionStateFilePathForRuntime(stateDir, runtimeKey) {
|
|
33432
33647
|
const fileName = Buffer.from(runtimeKey).toString("base64url");
|
|
33433
|
-
return
|
|
33648
|
+
return path6.join(stateDir, "threads", `${fileName}.json`);
|
|
33434
33649
|
}
|
|
33435
33650
|
function contextFilePathForSession(stateDir, sessionKey) {
|
|
33436
33651
|
const fileName = Buffer.from(sessionKey).toString("base64url");
|
|
33437
|
-
return
|
|
33652
|
+
return path6.join(stateDir, "dispatch-context", `${fileName}.json`);
|
|
33438
33653
|
}
|
|
33439
33654
|
function dispatchContextDirPath(stateDir) {
|
|
33440
33655
|
return dispatchLaneContextDir(stateDir);
|
|
33441
33656
|
}
|
|
33442
33657
|
function stepIdFilePathForSession(stateDir, sessionKey) {
|
|
33443
33658
|
const fileName = Buffer.from(sessionKey).toString("base64url");
|
|
33444
|
-
return
|
|
33659
|
+
return path6.join(stateDir, "step-ids", `${fileName}.txt`);
|
|
33445
33660
|
}
|
|
33446
33661
|
|
|
33447
33662
|
// ts/codex-agent/dist/dispatch.js
|
|
33448
33663
|
import { execSync as execSync2, spawn } from "node:child_process";
|
|
33449
33664
|
import { randomUUID } from "node:crypto";
|
|
33450
|
-
import * as
|
|
33665
|
+
import * as fs7 from "node:fs";
|
|
33666
|
+
import * as path8 from "node:path";
|
|
33451
33667
|
|
|
33452
33668
|
// ts/agent-core/dist/internal/attachment-input.js
|
|
33453
33669
|
import { execSync } from "node:child_process";
|
|
33454
33670
|
import { constants } from "node:fs";
|
|
33455
33671
|
import * as fsSync from "node:fs";
|
|
33456
|
-
import * as
|
|
33457
|
-
import * as
|
|
33672
|
+
import * as fs6 from "node:fs/promises";
|
|
33673
|
+
import * as path7 from "node:path";
|
|
33458
33674
|
var DEFAULT_MAX_TOTAL_IMAGE_BYTES = 20 * 1024 * 1024;
|
|
33459
33675
|
var DEFAULT_ATTACHMENT_CACHE_MAX_BYTES = 512 * 1024 * 1024;
|
|
33460
33676
|
var DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 3e4;
|
|
@@ -33484,11 +33700,11 @@ async function prepareLocalImageAttachments(event, context2, opts) {
|
|
|
33484
33700
|
};
|
|
33485
33701
|
}
|
|
33486
33702
|
const rootDir = await ensureAttachmentRootDir(opts.workspaceDir);
|
|
33487
|
-
const messageDir =
|
|
33703
|
+
const messageDir = path7.join(rootDir, sanitizePathSegment(event.messageId));
|
|
33488
33704
|
await ensurePathIsNotSymlink(messageDir);
|
|
33489
|
-
await
|
|
33705
|
+
await fs6.mkdir(messageDir, { recursive: true });
|
|
33490
33706
|
await ensurePathIsNotSymlink(messageDir);
|
|
33491
|
-
const activeMessageDir =
|
|
33707
|
+
const activeMessageDir = path7.resolve(messageDir);
|
|
33492
33708
|
activeAttachmentDirs.add(activeMessageDir);
|
|
33493
33709
|
const maintenanceCooldownMs = opts.maintenanceCooldownMs ?? DEFAULT_MAINTENANCE_COOLDOWN_MS;
|
|
33494
33710
|
const maintenancePromise = scheduleAttachmentMaintenance(rootDir, {
|
|
@@ -33505,7 +33721,7 @@ async function prepareLocalImageAttachments(event, context2, opts) {
|
|
|
33505
33721
|
const notes = [];
|
|
33506
33722
|
let downloadedBytes = 0;
|
|
33507
33723
|
for (const att of imageAttachments) {
|
|
33508
|
-
const localPath =
|
|
33724
|
+
const localPath = path7.join(messageDir, localFileName(att.id, att.fileName, att.mimeType));
|
|
33509
33725
|
const downloadTimeoutMs = opts.downloadTimeoutMs ?? DEFAULT_ATTACHMENT_DOWNLOAD_TIMEOUT_MS;
|
|
33510
33726
|
const fetchFresh = async () => {
|
|
33511
33727
|
const fileInfo = await withTimeout(context2.client.getFileUrl(att.id), downloadTimeoutMs, `file URL lookup timed out after ${downloadTimeoutMs}ms`);
|
|
@@ -33562,7 +33778,7 @@ async function appendPreparedLocalAttachmentRefs(body, event, context2, opts) {
|
|
|
33562
33778
|
return { body: appendLocalAttachmentRefs(body, attachments), attachments };
|
|
33563
33779
|
}
|
|
33564
33780
|
function pinLocalAttachmentPaths(images) {
|
|
33565
|
-
const dirs = new Set(images.map((image) =>
|
|
33781
|
+
const dirs = new Set(images.map((image) => path7.resolve(path7.dirname(image.localPath))));
|
|
33566
33782
|
for (const dir of dirs) {
|
|
33567
33783
|
activeAttachmentDirs.add(dir);
|
|
33568
33784
|
}
|
|
@@ -33577,7 +33793,7 @@ function pinLocalAttachmentPaths(images) {
|
|
|
33577
33793
|
};
|
|
33578
33794
|
}
|
|
33579
33795
|
function attachmentRootDir(workspaceDir) {
|
|
33580
|
-
return
|
|
33796
|
+
return path7.join(path7.resolve(workspaceDir), ".parall", "attachments");
|
|
33581
33797
|
}
|
|
33582
33798
|
function ensureLocalAttachmentGitExclude(workingDirectory) {
|
|
33583
33799
|
try {
|
|
@@ -33586,8 +33802,8 @@ function ensureLocalAttachmentGitExclude(workingDirectory) {
|
|
|
33586
33802
|
encoding: "utf8",
|
|
33587
33803
|
stdio: ["ignore", "pipe", "ignore"]
|
|
33588
33804
|
}).trim();
|
|
33589
|
-
const excludePath =
|
|
33590
|
-
fsSync.mkdirSync(
|
|
33805
|
+
const excludePath = path7.isAbsolute(rel) ? rel : path7.join(workingDirectory, rel);
|
|
33806
|
+
fsSync.mkdirSync(path7.dirname(excludePath), { recursive: true });
|
|
33591
33807
|
const existing = fsSync.existsSync(excludePath) ? fsSync.readFileSync(excludePath, "utf8") : "";
|
|
33592
33808
|
if (existing.split(/\r?\n/).some((line) => line.trim() === ".parall/"))
|
|
33593
33809
|
return;
|
|
@@ -33623,18 +33839,18 @@ function scheduleAttachmentMaintenance(rootDir, opts) {
|
|
|
33623
33839
|
return run;
|
|
33624
33840
|
}
|
|
33625
33841
|
async function ensureAttachmentRootDir(workspaceDir) {
|
|
33626
|
-
const workspaceRoot =
|
|
33627
|
-
const parallDir =
|
|
33842
|
+
const workspaceRoot = path7.resolve(workspaceDir);
|
|
33843
|
+
const parallDir = path7.join(workspaceRoot, ".parall");
|
|
33628
33844
|
const rootDir = attachmentRootDir(workspaceRoot);
|
|
33629
|
-
await
|
|
33845
|
+
await fs6.mkdir(workspaceRoot, { recursive: true });
|
|
33630
33846
|
await ensurePathIsNotSymlink(parallDir);
|
|
33631
|
-
await
|
|
33847
|
+
await fs6.mkdir(parallDir, { recursive: true, mode: 448 });
|
|
33632
33848
|
await ensurePathIsNotSymlink(parallDir);
|
|
33633
33849
|
await ensurePathIsNotSymlink(rootDir);
|
|
33634
|
-
await
|
|
33850
|
+
await fs6.mkdir(rootDir, { recursive: true, mode: 448 });
|
|
33635
33851
|
await ensurePathIsNotSymlink(rootDir);
|
|
33636
|
-
const realWorkspace = await
|
|
33637
|
-
const realRoot = await
|
|
33852
|
+
const realWorkspace = await fs6.realpath(workspaceRoot);
|
|
33853
|
+
const realRoot = await fs6.realpath(rootDir);
|
|
33638
33854
|
if (!isPathInside(realRoot, realWorkspace)) {
|
|
33639
33855
|
throw new Error(`attachment root escapes workspace: ${rootDir}`);
|
|
33640
33856
|
}
|
|
@@ -33642,7 +33858,7 @@ async function ensureAttachmentRootDir(workspaceDir) {
|
|
|
33642
33858
|
}
|
|
33643
33859
|
async function ensurePathIsNotSymlink(filePath) {
|
|
33644
33860
|
try {
|
|
33645
|
-
const stat = await
|
|
33861
|
+
const stat = await fs6.lstat(filePath);
|
|
33646
33862
|
if (stat.isSymbolicLink()) {
|
|
33647
33863
|
throw new Error(`refusing to use symlinked attachment path ${filePath}`);
|
|
33648
33864
|
}
|
|
@@ -33653,8 +33869,8 @@ async function ensurePathIsNotSymlink(filePath) {
|
|
|
33653
33869
|
}
|
|
33654
33870
|
}
|
|
33655
33871
|
function isPathInside(childPath, parentPath) {
|
|
33656
|
-
const rel =
|
|
33657
|
-
return rel === "" || !!rel && !rel.startsWith("..") && !
|
|
33872
|
+
const rel = path7.relative(parentPath, childPath);
|
|
33873
|
+
return rel === "" || !!rel && !rel.startsWith("..") && !path7.isAbsolute(rel);
|
|
33658
33874
|
}
|
|
33659
33875
|
async function existingUsableFile(filePath, expectedSize, rootDir) {
|
|
33660
33876
|
try {
|
|
@@ -33665,30 +33881,30 @@ async function existingUsableFile(filePath, expectedSize, rootDir) {
|
|
|
33665
33881
|
}
|
|
33666
33882
|
}
|
|
33667
33883
|
async function localFileStatInsideRoot(filePath, rootDir) {
|
|
33668
|
-
const stat = await
|
|
33884
|
+
const stat = await fs6.lstat(filePath);
|
|
33669
33885
|
if (stat.isSymbolicLink()) {
|
|
33670
33886
|
throw new Error(`refusing to use symlinked attachment file ${filePath}`);
|
|
33671
33887
|
}
|
|
33672
33888
|
if (!stat.isFile()) {
|
|
33673
33889
|
throw new Error(`attachment path is not a file ${filePath}`);
|
|
33674
33890
|
}
|
|
33675
|
-
const realRoot = await
|
|
33676
|
-
const realFile = await
|
|
33891
|
+
const realRoot = await fs6.realpath(rootDir);
|
|
33892
|
+
const realFile = await fs6.realpath(filePath);
|
|
33677
33893
|
if (!isPathInside(realFile, realRoot)) {
|
|
33678
33894
|
throw new Error(`attachment file escapes workspace: ${filePath}`);
|
|
33679
33895
|
}
|
|
33680
33896
|
return stat;
|
|
33681
33897
|
}
|
|
33682
33898
|
async function localDirectoryStatInsideRoot(dirPath, rootDir) {
|
|
33683
|
-
const stat = await
|
|
33899
|
+
const stat = await fs6.lstat(dirPath);
|
|
33684
33900
|
if (stat.isSymbolicLink()) {
|
|
33685
33901
|
throw new Error(`refusing to use symlinked attachment directory ${dirPath}`);
|
|
33686
33902
|
}
|
|
33687
33903
|
if (!stat.isDirectory()) {
|
|
33688
33904
|
throw new Error(`attachment path is not a directory ${dirPath}`);
|
|
33689
33905
|
}
|
|
33690
|
-
const realRoot = await
|
|
33691
|
-
const realDir = await
|
|
33906
|
+
const realRoot = await fs6.realpath(rootDir);
|
|
33907
|
+
const realDir = await fs6.realpath(dirPath);
|
|
33692
33908
|
if (!isPathInside(realDir, realRoot)) {
|
|
33693
33909
|
throw new Error(`attachment directory escapes workspace: ${dirPath}`);
|
|
33694
33910
|
}
|
|
@@ -33696,7 +33912,7 @@ async function localDirectoryStatInsideRoot(dirPath, rootDir) {
|
|
|
33696
33912
|
}
|
|
33697
33913
|
async function openLocalFileInsideRoot(filePath, rootDir) {
|
|
33698
33914
|
const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
|
|
33699
|
-
const file = await
|
|
33915
|
+
const file = await fs6.open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
33700
33916
|
let keepOpen = false;
|
|
33701
33917
|
try {
|
|
33702
33918
|
const openedStat = await file.stat();
|
|
@@ -33712,8 +33928,8 @@ async function openLocalFileInsideRoot(filePath, rootDir) {
|
|
|
33712
33928
|
}
|
|
33713
33929
|
}
|
|
33714
33930
|
async function openLocalTempFileInsideRoot(filePath, rootDir) {
|
|
33715
|
-
await localDirectoryStatInsideRoot(
|
|
33716
|
-
const file = await
|
|
33931
|
+
await localDirectoryStatInsideRoot(path7.dirname(filePath), rootDir);
|
|
33932
|
+
const file = await fs6.open(filePath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
|
|
33717
33933
|
let keepOpen = false;
|
|
33718
33934
|
try {
|
|
33719
33935
|
const checkedStat = await localFileStatInsideRoot(filePath, rootDir);
|
|
@@ -33738,7 +33954,7 @@ async function assertLocalFileIdentity(filePath, rootDir, expected) {
|
|
|
33738
33954
|
async function removeLocalFileIfInside(filePath, rootDir) {
|
|
33739
33955
|
try {
|
|
33740
33956
|
await localFileStatInsideRoot(filePath, rootDir);
|
|
33741
|
-
await
|
|
33957
|
+
await fs6.rm(filePath, { force: true });
|
|
33742
33958
|
} catch {
|
|
33743
33959
|
}
|
|
33744
33960
|
}
|
|
@@ -33751,7 +33967,7 @@ function sameFile(a, b) {
|
|
|
33751
33967
|
async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
|
|
33752
33968
|
let entries;
|
|
33753
33969
|
try {
|
|
33754
|
-
entries = await
|
|
33970
|
+
entries = await fs6.readdir(rootDir, { withFileTypes: true });
|
|
33755
33971
|
} catch {
|
|
33756
33972
|
return;
|
|
33757
33973
|
}
|
|
@@ -33759,15 +33975,15 @@ async function cleanupOldAttachmentFiles(rootDir, ttlMs, log2, preserveDirs) {
|
|
|
33759
33975
|
await Promise.all(entries.map(async (entry) => {
|
|
33760
33976
|
if (!entry.isDirectory())
|
|
33761
33977
|
return;
|
|
33762
|
-
const fullPath =
|
|
33978
|
+
const fullPath = path7.join(rootDir, entry.name);
|
|
33763
33979
|
try {
|
|
33764
|
-
if (preserveDirs?.has(
|
|
33980
|
+
if (preserveDirs?.has(path7.resolve(fullPath)))
|
|
33765
33981
|
return;
|
|
33766
|
-
const stat = await
|
|
33982
|
+
const stat = await fs6.lstat(fullPath);
|
|
33767
33983
|
if (!stat.isDirectory())
|
|
33768
33984
|
return;
|
|
33769
33985
|
if (stat.mtimeMs < cutoff) {
|
|
33770
|
-
await
|
|
33986
|
+
await fs6.rm(fullPath, { recursive: true, force: true });
|
|
33771
33987
|
}
|
|
33772
33988
|
} catch (err) {
|
|
33773
33989
|
log2?.warn?.(`agent-core: failed to clean attachment temp dir ${fullPath}: ${String(err)}`);
|
|
@@ -33779,7 +33995,7 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
|
|
|
33779
33995
|
return;
|
|
33780
33996
|
let entries;
|
|
33781
33997
|
try {
|
|
33782
|
-
entries = await
|
|
33998
|
+
entries = await fs6.readdir(rootDir, { withFileTypes: true });
|
|
33783
33999
|
} catch {
|
|
33784
34000
|
return;
|
|
33785
34001
|
}
|
|
@@ -33788,9 +34004,9 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
|
|
|
33788
34004
|
for (const entry of entries) {
|
|
33789
34005
|
if (!entry.isDirectory())
|
|
33790
34006
|
continue;
|
|
33791
|
-
const fullPath =
|
|
34007
|
+
const fullPath = path7.join(rootDir, entry.name);
|
|
33792
34008
|
try {
|
|
33793
|
-
const stat = await
|
|
34009
|
+
const stat = await fs6.lstat(fullPath);
|
|
33794
34010
|
if (!stat.isDirectory())
|
|
33795
34011
|
continue;
|
|
33796
34012
|
const size = await directorySize(fullPath);
|
|
@@ -33806,10 +34022,10 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
|
|
|
33806
34022
|
for (const dir of dirs) {
|
|
33807
34023
|
if (total <= maxBytes)
|
|
33808
34024
|
break;
|
|
33809
|
-
if (preserveDirs?.has(
|
|
34025
|
+
if (preserveDirs?.has(path7.resolve(dir.path)))
|
|
33810
34026
|
continue;
|
|
33811
34027
|
try {
|
|
33812
|
-
await
|
|
34028
|
+
await fs6.rm(dir.path, { recursive: true, force: true });
|
|
33813
34029
|
total -= dir.size;
|
|
33814
34030
|
} catch (err) {
|
|
33815
34031
|
log2?.warn?.(`agent-core: failed to prune attachment cache dir ${dir.path}: ${String(err)}`);
|
|
@@ -33818,12 +34034,12 @@ async function pruneAttachmentCache(rootDir, maxBytes, log2, preserveDirs) {
|
|
|
33818
34034
|
}
|
|
33819
34035
|
async function directorySize(dirPath) {
|
|
33820
34036
|
let total = 0;
|
|
33821
|
-
const entries = await
|
|
34037
|
+
const entries = await fs6.readdir(dirPath, { withFileTypes: true });
|
|
33822
34038
|
for (const entry of entries) {
|
|
33823
|
-
const fullPath =
|
|
34039
|
+
const fullPath = path7.join(dirPath, entry.name);
|
|
33824
34040
|
let stat;
|
|
33825
34041
|
try {
|
|
33826
|
-
stat = await
|
|
34042
|
+
stat = await fs6.lstat(fullPath);
|
|
33827
34043
|
} catch {
|
|
33828
34044
|
continue;
|
|
33829
34045
|
}
|
|
@@ -33838,10 +34054,10 @@ async function directorySize(dirPath) {
|
|
|
33838
34054
|
return total;
|
|
33839
34055
|
}
|
|
33840
34056
|
function activeDirsForRoot(rootDir) {
|
|
33841
|
-
const root =
|
|
34057
|
+
const root = path7.resolve(rootDir);
|
|
33842
34058
|
const dirs = /* @__PURE__ */ new Set();
|
|
33843
34059
|
for (const dir of activeAttachmentDirs) {
|
|
33844
|
-
if (dir === root || dir.startsWith(`${root}${
|
|
34060
|
+
if (dir === root || dir.startsWith(`${root}${path7.sep}`)) {
|
|
33845
34061
|
dirs.add(dir);
|
|
33846
34062
|
}
|
|
33847
34063
|
}
|
|
@@ -33938,9 +34154,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
|
|
|
33938
34154
|
}
|
|
33939
34155
|
writtenStat = await file.stat();
|
|
33940
34156
|
await closeFile();
|
|
33941
|
-
await localDirectoryStatInsideRoot(
|
|
34157
|
+
await localDirectoryStatInsideRoot(path7.dirname(filePath), rootDir);
|
|
33942
34158
|
await assertLocalFileIdentity(tmpPath, rootDir, writtenStat);
|
|
33943
|
-
await
|
|
34159
|
+
await fs6.rename(tmpPath, filePath);
|
|
33944
34160
|
completed = true;
|
|
33945
34161
|
return written;
|
|
33946
34162
|
} finally {
|
|
@@ -33956,9 +34172,9 @@ async function writeResponseToFileWithLimit(res, filePath, maxBytes, rootDir) {
|
|
|
33956
34172
|
}
|
|
33957
34173
|
}
|
|
33958
34174
|
function localFileName(attachmentId, fileName, mimeType) {
|
|
33959
|
-
const safeName = sanitizePathSegment(
|
|
33960
|
-
const ext =
|
|
33961
|
-
const stem =
|
|
34175
|
+
const safeName = sanitizePathSegment(path7.basename(fileName || attachmentId));
|
|
34176
|
+
const ext = path7.extname(safeName) || extensionForMime(mimeType);
|
|
34177
|
+
const stem = path7.basename(safeName, path7.extname(safeName)) || attachmentId;
|
|
33962
34178
|
return `${sanitizePathSegment(attachmentId)}-${stem}${ext}`;
|
|
33963
34179
|
}
|
|
33964
34180
|
function extensionForMime(mimeType) {
|
|
@@ -34481,6 +34697,7 @@ var CodexAppServerAdapter = class {
|
|
|
34481
34697
|
}
|
|
34482
34698
|
(this.opts.log ?? context2.log)?.warn?.(`pending steer invalidated (subprocess died); falling through to normal dispatch`);
|
|
34483
34699
|
}
|
|
34700
|
+
await this.applyPendingRestart(context2.log);
|
|
34484
34701
|
await this.ensureStarted(context2.log);
|
|
34485
34702
|
const client = this.client;
|
|
34486
34703
|
if (!client) {
|
|
@@ -34694,6 +34911,24 @@ var CodexAppServerAdapter = class {
|
|
|
34694
34911
|
this.opts.log?.warn?.(`thread/fork failed: ${errToString(err)}`);
|
|
34695
34912
|
return null;
|
|
34696
34913
|
}
|
|
34914
|
+
/**
|
|
34915
|
+
* Lazily restart the app-server before the NEXT turn: the workspace
|
|
34916
|
+
* config.toml (developer_instructions, carrying capability fragments) is
|
|
34917
|
+
* loaded at process start, so a changed fragment set needs a respawn to
|
|
34918
|
+
* reach the prompt. Deferred to the next dispatch with no active turns —
|
|
34919
|
+
* never kills an in-flight turn; thread state survives via thread/resume.
|
|
34920
|
+
*/
|
|
34921
|
+
requestProcessRestart() {
|
|
34922
|
+
this.restartRequested = true;
|
|
34923
|
+
}
|
|
34924
|
+
restartRequested = false;
|
|
34925
|
+
async applyPendingRestart(log2) {
|
|
34926
|
+
if (!this.restartRequested || this.activeTurns.size > 0)
|
|
34927
|
+
return;
|
|
34928
|
+
this.restartRequested = false;
|
|
34929
|
+
(log2 ?? this.opts.log)?.info?.("restarting codex app-server to pick up updated developer_instructions");
|
|
34930
|
+
await this.stop();
|
|
34931
|
+
}
|
|
34697
34932
|
async stop() {
|
|
34698
34933
|
this.stopping = true;
|
|
34699
34934
|
const proc = this.proc;
|
|
@@ -34703,6 +34938,7 @@ var CodexAppServerAdapter = class {
|
|
|
34703
34938
|
this.initialized = false;
|
|
34704
34939
|
this.activeTurnIds.clear();
|
|
34705
34940
|
this.pendingInjections.clear();
|
|
34941
|
+
this.resumedThreadIds.clear();
|
|
34706
34942
|
if (client)
|
|
34707
34943
|
client.dispose(new Error("adapter stopped"));
|
|
34708
34944
|
if (proc && proc.exitCode === null && proc.signalCode === null) {
|
|
@@ -34745,6 +34981,11 @@ var CodexAppServerAdapter = class {
|
|
|
34745
34981
|
FORCE_COLOR: "0",
|
|
34746
34982
|
NO_COLOR: "1"
|
|
34747
34983
|
};
|
|
34984
|
+
if (this.opts.capabilityBinDir) {
|
|
34985
|
+
const pathKey = IS_WIN32 ? Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH" : "PATH";
|
|
34986
|
+
const existing = env[pathKey];
|
|
34987
|
+
env[pathKey] = existing ? `${this.opts.capabilityBinDir}${path8.delimiter}${existing}` : this.opts.capabilityBinDir;
|
|
34988
|
+
}
|
|
34748
34989
|
if (this.opts.contextFilePath) {
|
|
34749
34990
|
env.PRLL_CONTEXT_FILE = this.opts.contextFilePath;
|
|
34750
34991
|
}
|
|
@@ -34896,7 +35137,7 @@ var TurnSink = class {
|
|
|
34896
35137
|
}
|
|
34897
35138
|
};
|
|
34898
35139
|
function ensureGitRepo(workingDirectory) {
|
|
34899
|
-
|
|
35140
|
+
fs7.mkdirSync(workingDirectory, { recursive: true });
|
|
34900
35141
|
try {
|
|
34901
35142
|
execSync2("git rev-parse --is-inside-work-tree", { cwd: workingDirectory, stdio: "pipe" });
|
|
34902
35143
|
ensureLocalAttachmentGitExclude(workingDirectory);
|
|
@@ -34966,8 +35207,8 @@ function errToString(err) {
|
|
|
34966
35207
|
}
|
|
34967
35208
|
|
|
34968
35209
|
// ts/codex-agent/dist/session-manager.js
|
|
34969
|
-
import * as
|
|
34970
|
-
import * as
|
|
35210
|
+
import * as fs8 from "node:fs";
|
|
35211
|
+
import * as path9 from "node:path";
|
|
34971
35212
|
var CodexSessionManager = class {
|
|
34972
35213
|
mainSessionKey;
|
|
34973
35214
|
stateFilePath;
|
|
@@ -35004,14 +35245,14 @@ var CodexSessionManager = class {
|
|
|
35004
35245
|
clearMainThread() {
|
|
35005
35246
|
this.threadIds.delete(this.mainSessionKey);
|
|
35006
35247
|
try {
|
|
35007
|
-
|
|
35248
|
+
fs8.rmSync(this.stateFilePath, { force: true });
|
|
35008
35249
|
} catch (error) {
|
|
35009
35250
|
this.logger?.warn(`codex-agent: failed to clear main thread state at ${this.stateFilePath}: ${String(error)}`);
|
|
35010
35251
|
}
|
|
35011
35252
|
}
|
|
35012
35253
|
restore() {
|
|
35013
35254
|
try {
|
|
35014
|
-
const raw =
|
|
35255
|
+
const raw = fs8.readFileSync(this.stateFilePath, "utf8");
|
|
35015
35256
|
const parsed = JSON.parse(raw);
|
|
35016
35257
|
if (parsed.runtimeKey === this.mainSessionKey && typeof parsed.threadId === "string" && parsed.threadId.trim()) {
|
|
35017
35258
|
this.threadIds.set(this.mainSessionKey, parsed.threadId.trim());
|
|
@@ -35024,10 +35265,10 @@ var CodexSessionManager = class {
|
|
|
35024
35265
|
}
|
|
35025
35266
|
persist(threadId) {
|
|
35026
35267
|
try {
|
|
35027
|
-
|
|
35268
|
+
fs8.mkdirSync(path9.dirname(this.stateFilePath), { recursive: true });
|
|
35028
35269
|
const tmpPath = `${this.stateFilePath}.tmp`;
|
|
35029
|
-
|
|
35030
|
-
|
|
35270
|
+
fs8.writeFileSync(tmpPath, JSON.stringify({ runtimeKey: this.mainSessionKey, threadId }, null, 2));
|
|
35271
|
+
fs8.renameSync(tmpPath, this.stateFilePath);
|
|
35031
35272
|
} catch (error) {
|
|
35032
35273
|
this.logger?.warn(`codex-agent: failed to persist thread state at ${this.stateFilePath}: ${String(error)}`);
|
|
35033
35274
|
}
|
|
@@ -35035,8 +35276,8 @@ var CodexSessionManager = class {
|
|
|
35035
35276
|
};
|
|
35036
35277
|
|
|
35037
35278
|
// ts/codex-agent/dist/workspace.js
|
|
35038
|
-
import * as
|
|
35039
|
-
import * as
|
|
35279
|
+
import * as fs9 from "node:fs";
|
|
35280
|
+
import * as path10 from "node:path";
|
|
35040
35281
|
|
|
35041
35282
|
// ts/node_modules/.pnpm/smol-toml@1.6.1/node_modules/smol-toml/dist/error.js
|
|
35042
35283
|
function getLineColFromPtr(string, ptr) {
|
|
@@ -35739,16 +35980,16 @@ function sleepSync(ms) {
|
|
|
35739
35980
|
Atomics.wait(SLEEP_SIGNAL, 0, 0, ms);
|
|
35740
35981
|
}
|
|
35741
35982
|
function withConfigLock(codexHome, log2, fn) {
|
|
35742
|
-
const queueDir =
|
|
35983
|
+
const queueDir = path10.join(codexHome, "config.toml.lock.d");
|
|
35743
35984
|
let ticketName = bakeryEnqueue(queueDir);
|
|
35744
|
-
let ticketPath = ticketName ?
|
|
35985
|
+
let ticketPath = ticketName ? path10.join(queueDir, ticketName) : "";
|
|
35745
35986
|
let acquired = false;
|
|
35746
35987
|
let heldPath = "";
|
|
35747
35988
|
const deadline = Date.now() + CONFIG_LOCK_TIMINGS.waitMs;
|
|
35748
35989
|
while (ticketName && Date.now() < deadline) {
|
|
35749
35990
|
let names;
|
|
35750
35991
|
try {
|
|
35751
|
-
names =
|
|
35992
|
+
names = fs9.readdirSync(queueDir).sort();
|
|
35752
35993
|
} catch {
|
|
35753
35994
|
break;
|
|
35754
35995
|
}
|
|
@@ -35756,7 +35997,7 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
35756
35997
|
ticketName = bakeryEnqueue(queueDir);
|
|
35757
35998
|
if (!ticketName)
|
|
35758
35999
|
break;
|
|
35759
|
-
ticketPath =
|
|
36000
|
+
ticketPath = path10.join(queueDir, ticketName);
|
|
35760
36001
|
continue;
|
|
35761
36002
|
}
|
|
35762
36003
|
const now = Date.now();
|
|
@@ -35764,12 +36005,12 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
35764
36005
|
let blocked = false;
|
|
35765
36006
|
let head;
|
|
35766
36007
|
for (const name of names) {
|
|
35767
|
-
const entryPath =
|
|
36008
|
+
const entryPath = path10.join(queueDir, name);
|
|
35768
36009
|
if (name.startsWith("held-")) {
|
|
35769
36010
|
const enteredAt = Number.parseInt(name.slice(5, 20), 10);
|
|
35770
36011
|
if (Number.isFinite(enteredAt) && now - enteredAt > CONFIG_LOCK_TIMINGS.staleMs) {
|
|
35771
36012
|
try {
|
|
35772
|
-
|
|
36013
|
+
fs9.unlinkSync(entryPath);
|
|
35773
36014
|
} catch {
|
|
35774
36015
|
}
|
|
35775
36016
|
rescan = true;
|
|
@@ -35780,14 +36021,14 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
35780
36021
|
}
|
|
35781
36022
|
let mtimeMs;
|
|
35782
36023
|
try {
|
|
35783
|
-
mtimeMs =
|
|
36024
|
+
mtimeMs = fs9.statSync(entryPath).mtimeMs;
|
|
35784
36025
|
} catch {
|
|
35785
36026
|
rescan = true;
|
|
35786
36027
|
break;
|
|
35787
36028
|
}
|
|
35788
36029
|
if (now - mtimeMs > CONFIG_LOCK_TIMINGS.staleMs) {
|
|
35789
36030
|
try {
|
|
35790
|
-
|
|
36031
|
+
fs9.unlinkSync(entryPath);
|
|
35791
36032
|
} catch {
|
|
35792
36033
|
}
|
|
35793
36034
|
rescan = true;
|
|
@@ -35807,9 +36048,9 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
35807
36048
|
if (!blocked && head === ticketName) {
|
|
35808
36049
|
CONFIG_LOCK_TEST_HOOKS.beforeTicketEntry?.();
|
|
35809
36050
|
const heldName = `held-${String(Date.now()).padStart(15, "0")}-${ticketName.slice(2)}`;
|
|
35810
|
-
const candidateHeldPath =
|
|
36051
|
+
const candidateHeldPath = path10.join(queueDir, heldName);
|
|
35811
36052
|
try {
|
|
35812
|
-
|
|
36053
|
+
fs9.renameSync(ticketPath, candidateHeldPath);
|
|
35813
36054
|
} catch {
|
|
35814
36055
|
continue;
|
|
35815
36056
|
}
|
|
@@ -35819,7 +36060,7 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
35819
36060
|
}
|
|
35820
36061
|
try {
|
|
35821
36062
|
const t = /* @__PURE__ */ new Date();
|
|
35822
|
-
|
|
36063
|
+
fs9.utimesSync(ticketPath, t, t);
|
|
35823
36064
|
} catch {
|
|
35824
36065
|
}
|
|
35825
36066
|
sleepSync(CONFIG_LOCK_TIMINGS.retryMs);
|
|
@@ -35828,7 +36069,7 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
35828
36069
|
log2?.warn(`could not acquire ${queueDir}; writing config.toml without lock`);
|
|
35829
36070
|
if (ticketName) {
|
|
35830
36071
|
try {
|
|
35831
|
-
|
|
36072
|
+
fs9.unlinkSync(ticketPath);
|
|
35832
36073
|
} catch {
|
|
35833
36074
|
}
|
|
35834
36075
|
}
|
|
@@ -35838,7 +36079,7 @@ function withConfigLock(codexHome, log2, fn) {
|
|
|
35838
36079
|
} finally {
|
|
35839
36080
|
if (acquired) {
|
|
35840
36081
|
try {
|
|
35841
|
-
|
|
36082
|
+
fs9.unlinkSync(heldPath);
|
|
35842
36083
|
} catch {
|
|
35843
36084
|
}
|
|
35844
36085
|
}
|
|
@@ -35848,17 +36089,17 @@ var CONFIG_LOCK_TEST_HOOKS = {};
|
|
|
35848
36089
|
function bakeryEnqueue(queueDir) {
|
|
35849
36090
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
35850
36091
|
const token = `${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
|
|
35851
|
-
const markerPath =
|
|
36092
|
+
const markerPath = path10.join(queueDir, `choosing-${token}`);
|
|
35852
36093
|
try {
|
|
35853
|
-
|
|
36094
|
+
fs9.mkdirSync(queueDir, { recursive: true });
|
|
35854
36095
|
CONFIG_LOCK_TEST_HOOKS.beforeChoosingMarker?.();
|
|
35855
|
-
|
|
36096
|
+
fs9.writeFileSync(markerPath, "", { flag: "wx" });
|
|
35856
36097
|
} catch {
|
|
35857
36098
|
return null;
|
|
35858
36099
|
}
|
|
35859
36100
|
try {
|
|
35860
36101
|
let maxSeq = 0;
|
|
35861
|
-
for (const name of
|
|
36102
|
+
for (const name of fs9.readdirSync(queueDir)) {
|
|
35862
36103
|
if (!name.startsWith("t-"))
|
|
35863
36104
|
continue;
|
|
35864
36105
|
const seq = Number.parseInt(name.slice(2, 12), 10);
|
|
@@ -35866,18 +36107,18 @@ function bakeryEnqueue(queueDir) {
|
|
|
35866
36107
|
maxSeq = seq;
|
|
35867
36108
|
}
|
|
35868
36109
|
const ticketName = `t-${String(maxSeq + 1).padStart(10, "0")}-${token}`;
|
|
35869
|
-
const ticketPath =
|
|
36110
|
+
const ticketPath = path10.join(queueDir, ticketName);
|
|
35870
36111
|
CONFIG_LOCK_TEST_HOOKS.beforeTicketPublish?.();
|
|
35871
|
-
|
|
36112
|
+
fs9.renameSync(markerPath, ticketPath);
|
|
35872
36113
|
try {
|
|
35873
36114
|
const t = /* @__PURE__ */ new Date();
|
|
35874
|
-
|
|
36115
|
+
fs9.utimesSync(ticketPath, t, t);
|
|
35875
36116
|
} catch {
|
|
35876
36117
|
}
|
|
35877
36118
|
return ticketName;
|
|
35878
36119
|
} catch (err) {
|
|
35879
36120
|
try {
|
|
35880
|
-
|
|
36121
|
+
fs9.unlinkSync(markerPath);
|
|
35881
36122
|
} catch {
|
|
35882
36123
|
}
|
|
35883
36124
|
if (err.code === "ENOENT")
|
|
@@ -35891,21 +36132,21 @@ function writeConfigAtomic(filePath, content) {
|
|
|
35891
36132
|
const realPath = resolveWriteTarget(filePath);
|
|
35892
36133
|
let mode;
|
|
35893
36134
|
try {
|
|
35894
|
-
mode =
|
|
36135
|
+
mode = fs9.statSync(realPath).mode & 511;
|
|
35895
36136
|
} catch {
|
|
35896
36137
|
}
|
|
35897
36138
|
const tmpPath = `${realPath}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
35898
36139
|
let tmpCreated = false;
|
|
35899
36140
|
try {
|
|
35900
|
-
|
|
36141
|
+
fs9.writeFileSync(tmpPath, content, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
35901
36142
|
tmpCreated = true;
|
|
35902
36143
|
if (mode !== void 0)
|
|
35903
|
-
|
|
35904
|
-
|
|
36144
|
+
fs9.chmodSync(tmpPath, mode);
|
|
36145
|
+
fs9.renameSync(tmpPath, realPath);
|
|
35905
36146
|
} catch (err) {
|
|
35906
36147
|
if (tmpCreated || err.code !== "EEXIST") {
|
|
35907
36148
|
try {
|
|
35908
|
-
|
|
36149
|
+
fs9.unlinkSync(tmpPath);
|
|
35909
36150
|
} catch {
|
|
35910
36151
|
}
|
|
35911
36152
|
}
|
|
@@ -35914,13 +36155,13 @@ function writeConfigAtomic(filePath, content) {
|
|
|
35914
36155
|
}
|
|
35915
36156
|
function resolveWriteTarget(filePath) {
|
|
35916
36157
|
try {
|
|
35917
|
-
return
|
|
36158
|
+
return fs9.realpathSync(filePath);
|
|
35918
36159
|
} catch (err) {
|
|
35919
36160
|
if (err.code !== "ENOENT")
|
|
35920
36161
|
throw err;
|
|
35921
36162
|
}
|
|
35922
36163
|
const seen = /* @__PURE__ */ new Set();
|
|
35923
|
-
let p =
|
|
36164
|
+
let p = path10.resolve(filePath);
|
|
35924
36165
|
for (let depth = 0; depth < 40; depth++) {
|
|
35925
36166
|
if (seen.has(p)) {
|
|
35926
36167
|
throw new Error(`symlink cycle at ${p} while resolving ${filePath}`);
|
|
@@ -35928,14 +36169,14 @@ function resolveWriteTarget(filePath) {
|
|
|
35928
36169
|
seen.add(p);
|
|
35929
36170
|
let link;
|
|
35930
36171
|
try {
|
|
35931
|
-
link =
|
|
36172
|
+
link = fs9.readlinkSync(p);
|
|
35932
36173
|
} catch (err) {
|
|
35933
36174
|
const code = err.code;
|
|
35934
36175
|
if (code === "ENOENT" || code === "EINVAL")
|
|
35935
36176
|
return p;
|
|
35936
36177
|
throw err;
|
|
35937
36178
|
}
|
|
35938
|
-
p =
|
|
36179
|
+
p = path10.resolve(path10.dirname(p), link);
|
|
35939
36180
|
}
|
|
35940
36181
|
throw new Error(`symlink chain deeper than 40 while resolving ${filePath}`);
|
|
35941
36182
|
}
|
|
@@ -35943,12 +36184,12 @@ function ensureWorkspaceTrusted(codexHome, workspaceDir, log2) {
|
|
|
35943
36184
|
withConfigLock(codexHome, log2, () => ensureWorkspaceTrustedLocked(codexHome, workspaceDir, log2));
|
|
35944
36185
|
}
|
|
35945
36186
|
function ensureWorkspaceTrustedLocked(codexHome, workspaceDir, log2) {
|
|
35946
|
-
const configPath =
|
|
35947
|
-
const normalizedPath =
|
|
36187
|
+
const configPath = path10.join(codexHome, "config.toml");
|
|
36188
|
+
const normalizedPath = path10.resolve(workspaceDir);
|
|
35948
36189
|
try {
|
|
35949
36190
|
let content = "";
|
|
35950
36191
|
try {
|
|
35951
|
-
content =
|
|
36192
|
+
content = fs9.readFileSync(configPath, "utf8");
|
|
35952
36193
|
} catch (err) {
|
|
35953
36194
|
if (err.code !== "ENOENT")
|
|
35954
36195
|
throw err;
|
|
@@ -35999,8 +36240,8 @@ ${trustLine}
|
|
|
35999
36240
|
} else if (projects && !content.includes("[projects.")) {
|
|
36000
36241
|
log2?.warn(`Codex config.toml uses inline table for projects; skipping trust write for ${normalizedPath}`);
|
|
36001
36242
|
} else {
|
|
36002
|
-
|
|
36003
|
-
|
|
36243
|
+
fs9.mkdirSync(codexHome, { recursive: true });
|
|
36244
|
+
fs9.appendFileSync(configPath, `
|
|
36004
36245
|
${sectionHeader}
|
|
36005
36246
|
${trustLine}
|
|
36006
36247
|
`, "utf8");
|
|
@@ -36020,12 +36261,12 @@ function ensureParallProvider(codexHome, apiUrl, log2) {
|
|
|
36020
36261
|
withConfigLock(codexHome, log2, () => ensureParallProviderLocked(codexHome, apiUrl));
|
|
36021
36262
|
}
|
|
36022
36263
|
function ensureParallProviderLocked(codexHome, apiUrl) {
|
|
36023
|
-
const configPath =
|
|
36264
|
+
const configPath = path10.join(codexHome, "config.toml");
|
|
36024
36265
|
const baseUrl = apiUrl.replace(/\/$/, "") + "/api/llm/v1";
|
|
36025
36266
|
try {
|
|
36026
36267
|
let content = "";
|
|
36027
36268
|
try {
|
|
36028
|
-
content =
|
|
36269
|
+
content = fs9.readFileSync(configPath, "utf8");
|
|
36029
36270
|
} catch (err) {
|
|
36030
36271
|
if (err.code !== "ENOENT")
|
|
36031
36272
|
throw err;
|
|
@@ -36056,7 +36297,7 @@ function ensureParallProviderLocked(codexHome, apiUrl) {
|
|
|
36056
36297
|
} else {
|
|
36057
36298
|
content = content.trimEnd() + "\n\n" + providerBlock + "\n";
|
|
36058
36299
|
}
|
|
36059
|
-
|
|
36300
|
+
fs9.mkdirSync(codexHome, { recursive: true });
|
|
36060
36301
|
writeConfigAtomic(configPath, content);
|
|
36061
36302
|
} catch (err) {
|
|
36062
36303
|
throw new Error(`failed to write Parall provider config: ${String(err)}`);
|
|
@@ -36066,26 +36307,33 @@ function findSectionEnd(content, fromIndex) {
|
|
|
36066
36307
|
const nextHeader = content.indexOf("\n[", fromIndex);
|
|
36067
36308
|
return nextHeader === -1 ? content.length : nextHeader;
|
|
36068
36309
|
}
|
|
36069
|
-
function
|
|
36070
|
-
const
|
|
36310
|
+
function writeCodexSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
|
|
36311
|
+
const parts = [
|
|
36071
36312
|
buildIdentity(agentIdentity),
|
|
36072
36313
|
BRIDGE_WORKSPACE_INSTRUCTIONS,
|
|
36073
36314
|
PRLL_BEHAVIOR,
|
|
36074
|
-
PRLL_REFERENCE_GUIDE
|
|
36075
|
-
|
|
36076
|
-
|
|
36077
|
-
|
|
36078
|
-
|
|
36079
|
-
|
|
36080
|
-
|
|
36081
|
-
|
|
36082
|
-
|
|
36083
|
-
|
|
36315
|
+
PRLL_REFERENCE_GUIDE
|
|
36316
|
+
];
|
|
36317
|
+
if (capabilityFragments && capabilityFragments.length > 0) {
|
|
36318
|
+
parts.push(capabilityFragments.join("\n\n"));
|
|
36319
|
+
}
|
|
36320
|
+
parts.push(buildSkillReferences(workspaceDir));
|
|
36321
|
+
const systemPrompt = parts.join("\n\n");
|
|
36322
|
+
const parallDir = path10.join(workspaceDir, ".parall");
|
|
36323
|
+
fs9.mkdirSync(parallDir, { recursive: true });
|
|
36324
|
+
fs9.writeFileSync(path10.join(parallDir, "system-prompt.md"), systemPrompt, "utf8");
|
|
36325
|
+
const codexConfigDir = path10.join(workspaceDir, ".codex");
|
|
36326
|
+
fs9.mkdirSync(codexConfigDir, { recursive: true });
|
|
36084
36327
|
const toml = `developer_instructions = """
|
|
36085
36328
|
${systemPrompt.replace(/\\/g, "\\\\").replace(/"""/g, '\\"""')}
|
|
36086
36329
|
"""
|
|
36087
36330
|
`;
|
|
36088
|
-
|
|
36331
|
+
fs9.writeFileSync(path10.join(codexConfigDir, "config.toml"), toml, "utf8");
|
|
36332
|
+
}
|
|
36333
|
+
function ensureCodexWorkspace(workspaceDir, log2, agentIdentity, capabilityFragments) {
|
|
36334
|
+
fs9.mkdirSync(workspaceDir, { recursive: true });
|
|
36335
|
+
writeCodexSystemPrompt(workspaceDir, agentIdentity, capabilityFragments);
|
|
36336
|
+
writeSkillFiles(path10.join(workspaceDir, ".parall", "skills"));
|
|
36089
36337
|
}
|
|
36090
36338
|
|
|
36091
36339
|
// ts/codex-agent/dist/index.js
|
|
@@ -36139,11 +36387,11 @@ async function main() {
|
|
|
36139
36387
|
ensureParallProvider(config.codexHome, config.apiUrl, agentLog);
|
|
36140
36388
|
agentLog.info("parall custom provider configured (Responses API HTTP/SSE mode)");
|
|
36141
36389
|
}
|
|
36142
|
-
|
|
36390
|
+
const agentIdentity = {
|
|
36143
36391
|
userId: agentUserId,
|
|
36144
36392
|
displayName: me.display_name,
|
|
36145
36393
|
description: me.agent_profile?.description ?? void 0
|
|
36146
|
-
}
|
|
36394
|
+
};
|
|
36147
36395
|
const runtimeKey = config.runtimeKey || buildCodexRuntimeKey(agentUserId);
|
|
36148
36396
|
const mainContextFilePath = contextFilePathForSession(config.stateDir, runtimeKey);
|
|
36149
36397
|
const sessionStateFilePath = sessionStateFilePathForRuntime(config.stateDir, runtimeKey);
|
|
@@ -36160,6 +36408,14 @@ async function main() {
|
|
|
36160
36408
|
log: agentLog
|
|
36161
36409
|
});
|
|
36162
36410
|
const platformDefaults = await configMgr.fetch();
|
|
36411
|
+
const applyChannelCapabilities = () => {
|
|
36412
|
+
const caps = configMgr.capabilities();
|
|
36413
|
+
materializeChannelCapabilities(config.stateDir, caps, agentLog);
|
|
36414
|
+
return caps.map((c) => c.fragment);
|
|
36415
|
+
};
|
|
36416
|
+
const bootCapabilityFragments = applyChannelCapabilities();
|
|
36417
|
+
let lastCapabilityFragments = bootCapabilityFragments.join("\n\n");
|
|
36418
|
+
ensureCodexWorkspace(config.workspaceDir, agentLog, agentIdentity, bootCapabilityFragments);
|
|
36163
36419
|
const platformModelOverride = deriveModelIsPin(platformDefaults, me.agent_profile);
|
|
36164
36420
|
const resolvedModel = resolveRuntimeModel(platformModelOverride, platformDefaults.model, config.model);
|
|
36165
36421
|
const resolvedEffort = platformDefaults.thinkingEffort ?? config.reasoningEffort;
|
|
@@ -36179,7 +36435,8 @@ async function main() {
|
|
|
36179
36435
|
log: agentLog,
|
|
36180
36436
|
contextFilePath: mainContextFilePath,
|
|
36181
36437
|
contextDirPath: dispatchContextDirPath(config.stateDir),
|
|
36182
|
-
useParallProvider
|
|
36438
|
+
useParallProvider,
|
|
36439
|
+
capabilityBinDir: capabilityBinDir(config.stateDir)
|
|
36183
36440
|
});
|
|
36184
36441
|
const refreshPlatformConfig = async () => {
|
|
36185
36442
|
const updated = await configMgr.fetch();
|
|
@@ -36196,6 +36453,19 @@ async function main() {
|
|
|
36196
36453
|
model: resolveRuntimeModel(isPin, updated.model, config.model) ?? null,
|
|
36197
36454
|
reasoningEffort: updated.thinkingEffort ?? config.reasoningEffort ?? null
|
|
36198
36455
|
});
|
|
36456
|
+
const fragments = applyChannelCapabilities();
|
|
36457
|
+
const joinedFragments = fragments.join("\n\n");
|
|
36458
|
+
let promptWritten = true;
|
|
36459
|
+
try {
|
|
36460
|
+
writeCodexSystemPrompt(config.workspaceDir, agentIdentity, fragments);
|
|
36461
|
+
} catch (err) {
|
|
36462
|
+
promptWritten = false;
|
|
36463
|
+
agentLog.warn(`system prompt refresh write failed (retrying next refresh): ${String(err)}`);
|
|
36464
|
+
}
|
|
36465
|
+
if (promptWritten && joinedFragments !== lastCapabilityFragments) {
|
|
36466
|
+
lastCapabilityFragments = joinedFragments;
|
|
36467
|
+
adapter.requestProcessRestart();
|
|
36468
|
+
}
|
|
36199
36469
|
};
|
|
36200
36470
|
const gateway = new ParallAgentGateway({
|
|
36201
36471
|
accountId: agentUserId,
|
|
@@ -36219,6 +36489,9 @@ async function main() {
|
|
|
36219
36489
|
},
|
|
36220
36490
|
dispatchAdapter: adapter,
|
|
36221
36491
|
log: agentLog,
|
|
36492
|
+
// Live capability view for hint routing: the channel reply hint points
|
|
36493
|
+
// at the vendor CLI only while the grant is active.
|
|
36494
|
+
getCapabilityKeys: () => configMgr.capabilities().map((c) => c.key),
|
|
36222
36495
|
shutdownDeadlineMs: parseShutdownDeadlineMs(process.env.PRLL_SHUTDOWN_DEADLINE_MS),
|
|
36223
36496
|
forkDeadlineMs: parseForkDeadlineMs(process.env.PRLL_FORK_DEADLINE_MS),
|
|
36224
36497
|
dispatchDeadlineMs: parseDispatchDeadlineMs(process.env.PRLL_DISPATCH_DEADLINE_MS),
|