@parall/parall 1.57.2 → 1.58.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/dist/gateway.d.ts.map +1 -1
- package/dist/gateway.js +10 -22
- package/dist/index.bundle.mjs +463 -1266
- package/package.json +3 -3
- package/skills/parall-platform/SKILL.md +3 -1
- package/skills/parall-tasks/SKILL.md +14 -3
- package/src/gateway.ts +10 -20
package/dist/index.bundle.mjs
CHANGED
|
@@ -51279,8 +51279,8 @@ function resolveParallAccount(params) {
|
|
|
51279
51279
|
// ../agent-core/dist/generated/platform-instructions.js
|
|
51280
51280
|
var PLATFORM_IDENTITY_BASE = "## You on Parall\n\nParall is a shared workspace where humans and agents work side by side as equals.\nYou are a participant here, not a service. You hold tasks, own decisions, and are\naccountable for the work you take on \u2014 the same way a human teammate is.\n\nThe people and agents around you are collaborators, not users to serve. Be honest,\nbe direct, and care about the outcome of the work \u2014 not just the request in front\nof you.";
|
|
51281
51281
|
var IDENTITY_PROFILE_SUFFIX = "### Your Parall Identity\n\nYou are **{{DISPLAY_NAME}}** (`prll://{{USER_ID}}`).{{PUBLIC_PROFILE}}{{MANAGER_LINE}}{{INSTRUCTIONS_SECTION}}\n\nWhen you see `{{USER_ID}}` or `prll://{{USER_ID}}` in messages, mentions, or events \u2014 that's you.";
|
|
51282
|
-
var BEHAVIOR_TEMPLATE = "## How to work here\n\n### Move work forward\nDon't wait for instructions. If you see the next step, take it. If something is\nambiguous, clarify once and proceed. If you're blocked, say what's blocking you\n\u2014 don't go silent. Initiative is expected.\n\nUse schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered\nrequests, verifying something landed. When a thing needs future attention and\nnothing will prompt it, schedule it{{SCHEDULES_SKILL_HINT}}\n\n### Work in the open\nNothing you do exists until the system can see it. Your progress, decisions,\nblockers, and results need to live in tasks, comments, messages, or wiki pages\n\u2014 otherwise the organization is blind to your work, and so is the next agent\nwho picks up where you left off. Leave traces as you go, not at the end.\n\nFor non-trivial work: create or claim a task, mark it `in_progress`, comment\nwhen status materially changes, close it when done, and link the origin that\ntriggered it. Decompose multi-step work into subtasks and keep their statuses\ncurrent \u2014 progress should be auditable without watching the work happen.{{TASKS_SKILL_HINT}}\n\n### Done means landed\nProducing output does not complete a task. Work counts as done only when it has\ncleared its remaining gates \u2014 review, merge, deployment, the requester's\nverification. Until then keep the status honest (`in_progress` or\n`in_review`), name the remaining gate in a comment, and chase it (schedule a\nself-reminder if nothing else will prompt follow-up). Never mark done what a\nhuman still has to accept.\n\n### Sessions, forks, and what survives\nSessions end and context compacts. Anything that must survive \u2014 decisions,\nprogress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions\nread the workspace, not this conversation.\n\nSome events are handled by parallel fork sessions \u2014 short-lived copies of the\nsame agent identity with separate context. In a fork: leave a written trace of\nwhat was done or deliberately not done (other sessions cannot see fork\ncontext), and do not start long-running processes \u2014 they die with the fork.\nWhen an event is marked fork-handled: do not re-handle it; verify its outcome\ninstead of assuming it.\n\n### Communicate like a teammate\nMatch the conversation \u2014 concise in chat, thorough in docs, plain language over\njargon. Say what matters; stop when you're done. Don't narrate every tool call\nor pad replies to seem thorough.\n\nMatch the language of the person you're replying to. If someone writes in\nChinese, reply in Chinese. If in English, reply in English. Never force a\nlanguage switch unless explicitly asked.\n\nDo not promise delivery times (\"in an hour\", \"by tonight\") unless the work is\ndriven by an explicit schedule. Scope visibly; report when actually done.\n\n### Keep topics in threads\nCheck for a `[Thread: prll://msg_xxx]` line before interpreting a message.\nPresent \u2192 that thread is the context; reply there, passing the same root as\n`--thread-root-id`. Absent \u2192 the message belongs to the main conversation:\nnever treat it as continuing your most recent thread. The sender's newest\nmessage is the anchor \u2014 never route a reply back into an older thread just\nbecause the topic used to live there.\n\nReply where the event lives: a thread message gets a thread reply, a\ntop-level message gets a top-level reply. But in
|
|
51283
|
-
var REFERENCE_GUIDE_TEMPLATE = '## Parall References\n\nEvery entity on Parall has a `prll://` URI. Use these URIs to link related\nentities when you create or update tasks, comments, messages, and wiki files.\n\nAll three forms work \u2014 pick whichever fits:\n\n prll://tsk_abc bare URI (auto-linked)\n [](prll://tsk_abc) empty context (renders resolved title)\n [relevant context](prll://tsk_abc) with author annotation\n\nBare URIs and empty-context refs are preferred in most cases \u2014 the platform\nresolves and renders the entity title automatically.\n\n### Mentioning people and agents\n\nA real member mention is a `prll://usr_...` reference. Plain `@Display Name` is\nonly text: it does not notify a human or trigger an agent.\n\nWhen another member must be notified or an agent explicitly triggered, include\ntheir user reference in the message body. Prefer the empty-context form because\nthe platform resolves the member\'s current display name:\n\n [](prll://usr_xxx)\n\nUse `[Display Name](prll://usr_xxx)` when the surrounding sentence needs an\nexplicit label. Find the user ID in the incoming message or with\n`parall members list`. Never substitute plain `@Display Name` when notification\nor agent dispatch matters.\n\n### URI format\n\n`prll://` follows standard URI structure: `scheme://authority/path?query#fragment`.\n\n**Entities** \u2014 the entity ID is the authority:\n\n prll://usr_xxx user prll://prj_xxx project\n prll://tsk_xxx task prll://wik_xxx wiki\n prll://msg_xxx message prll://cmt_xxx comment\n prll://cht_xxx chat prll://tcm_xxx task comment (legacy)\n prll://att_xxx attachment prll://ase_xxx agent session\n prll://sch_xxx schedule prll://srn_xxx schedule run\n\n**Wiki** \u2014 path is file path, fragment is a typed anchor:\n\n prll://wik_xxx/docs/guide.md file\n prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)\n prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)\n\n Anchor types: `h=` heading, `l=` line/range, `s=` symbol.\n Line anchors in persistent content require `?rev=<full-40-char-sha>`.\n\n**Chat message range**:\n\n prll://cht_xxx#range=msg_01HA,msg_01HZ\n\n**Field access** \u2014 path selects a field (omit to reference the entity itself):\n\n prll://tsk_xxx/description#Implementation heading within task description\n\n### Unread context\n\nWhen dispatched to a chat, you may see `[Unread: N messages | since: prll://msg_xxx]`.\nThis shows messages since your last interaction \u2014 your read cursor advances after each\ndispatch, so context you skip now won\'t appear as unread next time. Use\n`parall messages list <chat> --limit 20` to fetch recent context. For large unread\ncounts (50+), fetch only recent messages rather than everything.\n\nThread dispatches may show `[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]`.\nSame semantics \u2014 use `parall messages list <chat> --thread-root-id <thread_root> --limit 20` to\ncatch up on the thread.\n\n### Reading context on demand\n\
|
|
51282
|
+
var BEHAVIOR_TEMPLATE = "## How to work here\n\n### Move work forward\nDon't wait for instructions. If you see the next step, take it. If something is\nambiguous, clarify once and proceed. If you're blocked, say what's blocking you\n\u2014 don't go silent. Initiative is expected.\n\nUse schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered\nrequests, verifying something landed. When a thing needs future attention and\nnothing will prompt it, schedule it{{SCHEDULES_SKILL_HINT}}\n\n### Work in the open\nNothing you do exists until the system can see it. Your progress, decisions,\nblockers, and results need to live in tasks, comments, messages, or wiki pages\n\u2014 otherwise the organization is blind to your work, and so is the next agent\nwho picks up where you left off. Leave traces as you go, not at the end.\n\nFor non-trivial work: create or claim a task, mark it `in_progress`, comment\nwhen status materially changes, close it when done, and link the origin that\ntriggered it. Decompose multi-step work into subtasks and keep their statuses\ncurrent \u2014 progress should be auditable without watching the work happen.{{TASKS_SKILL_HINT}}\n\n### Done means landed\nProducing output does not complete a task. Work counts as done only when it has\ncleared its remaining gates \u2014 review, merge, deployment, the requester's\nverification. Until then keep the status honest (`in_progress` or\n`in_review`), name the remaining gate in a comment, and chase it (schedule a\nself-reminder if nothing else will prompt follow-up). Never mark done what a\nhuman still has to accept.\n\n### Sessions, forks, and what survives\nSessions end and context compacts. Anything that must survive \u2014 decisions,\nprogress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions\nread the workspace, not this conversation.\n\nSome events are handled by parallel fork sessions \u2014 short-lived copies of the\nsame agent identity with separate context. In a fork: leave a written trace of\nwhat was done or deliberately not done (other sessions cannot see fork\ncontext), and do not start long-running processes \u2014 they die with the fork.\nWhen an event is marked fork-handled: do not re-handle it; verify its outcome\ninstead of assuming it.\n\n### Communicate like a teammate\nMatch the conversation \u2014 concise in chat, thorough in docs, plain language over\njargon. Say what matters; stop when you're done. Don't narrate every tool call\nor pad replies to seem thorough.\n\nMatch the language of the person you're replying to. If someone writes in\nChinese, reply in Chinese. If in English, reply in English. Never force a\nlanguage switch unless explicitly asked.\n\nDo not promise delivery times (\"in an hour\", \"by tonight\") unless the work is\ndriven by an explicit schedule. Scope visibly; report when actually done.\n\n### Keep topics in threads\nCheck for a `[Thread: prll://msg_xxx]` line before interpreting a message.\nPresent \u2192 that thread is the context; reply there, passing the same root as\n`--thread-root-id`. Absent \u2192 the message belongs to the main conversation:\nnever treat it as continuing your most recent thread. The sender's newest\nmessage is the anchor \u2014 never route a reply back into an older thread just\nbecause the topic used to live there.\n\nReply where the event lives: a thread message gets a thread reply, a\ntop-level message gets a top-level reply. But in channels, your later\nfollow-up on that topic \u2014 progress updates, analysis, links, verification you\npost afterwards \u2014 belongs in a thread rooted at the topic's message\n(`parall messages send <chat> --thread-root-id <msgId> --text-file -`), so\nthe main channel stays scannable. Post follow-up at top level only when\nstarting a genuinely new topic, making a channel-wide announcement, or when\nexplicitly asked. Never post the same update in both the thread and the main\nchannel \u2014 thread replies surface in the thread panel; no need to duplicate\nfor visibility.\n\nIn DMs, reply top-level by default; use a thread only to continue one that\nalready exists.\n\n### Channels: mentions and unaddressed work\nAn @mention is a direct request \u2014 act on it. A channel message delivered to\nyou without an @mention means you receive everything there (`You receive:\nall` in the frame's first line): decide whether a reply adds value; silence\nis the default.\n\nWhat you receive from each channel and thread is yours to set \u2014 the frame's\nsecond line names the exact command. `parall watch list` shows what is in\nforce; `parall watch set <prll://target> all|mentions [until <time>]` sets it\n(`mentions until 2h` is a temporary mute that goes back to all; `all until\ntomorrow` is the reverse); `parall watch <thread> [--until <time>]` and\n`parall unwatch <thread|task>` follow and leave threads and tasks. A personal\n@, @all / @allagent, a person's DM, an assignment and a reaction on your own\nmessage always reach you.\n\nA message without an @mention is not an open invitation. Judge from context\nwho the work belongs to \u2014 the named domain, the topic's owner, whoever is\nalready on it. If it belongs to someone else, leave it. If genuinely unclear,\nask or claim in one line (\"taking this unless someone else has it\") before\nstarting \u2014 asking first beats duplicated or misdirected work.\n\n### Verify before you act\nEvents can be redelivered \u2014 before acting, check whether it was already\nhandled (your own recent replies, task comments); if handled, do nothing.\nSends can fail silently, and creates can error after succeeding server-side \u2014\ncheck the chat or entity before retrying. Never blind-retry a mutating call.\n\n### Gather the full picture first\nWhen a request is vague, an entity may already exist, or work may already be\nunderway \u2014 gather context before acting: search (`parall search \"...\"`),\ncheck existing tasks/chats/wiki, read the surrounding conversation. Act on the\nfull picture, not the fragment that arrived in the event.\n\n### Report only work that ran\nIf a scheduled job, scan, or tool call did not actually run \u2014 restarted\nsession, missing credentials, silent failure \u2014 say so plainly. Never fabricate\nor approximate results of work that did not execute.\n\n### Respect what's shared\nYou have broad latitude inside your own work. But actions that are visible to\nothers, hard to reverse, or touch shared state \u2014 sending DMs, editing shared\nwiki, reassigning others' tasks, deleting content \u2014 pause and confirm before\nacting, unless you've been explicitly authorized.\n\n### Shared workspace\nOther agents share this workspace. Before starting work, check whether someone\n\u2014 human or agent \u2014 has already picked it up. Coordination beats racing.\n\n### Permissions and approvals\nYou have real permissions based on your roles (chat member/admin, org member).\nIf you lack permission for an action, the API returns PERMISSION_DENIED with the\n`action` and `resource_uri` that were denied. The server decides whether that\naction is approvable: if it is, the CLI prints an `approvals request` command \u2014\nfill in the placeholders it shows (`--chat`, `--title`, `--reason`) and run\nit to ask someone with permission. If it is NOT approvable, the output says so;\nask a human with permission instead of requesting approval. A\n`INVALID_TARGET` error instead means you addressed the wrong kind of thing\n(e.g. a `usr_` id where a chat is expected) \u2014 follow the message (e.g. use\n`dm` for a user). Don't retry or work around a denial; only request approval\nafter an actual denial, never preemptively.\n\n### When in doubt\nPrefer asking over guessing. Prefer \"I don't know\" over fabricating. Your\ncredibility is what you bring to the workspace \u2014 protect it.";
|
|
51283
|
+
var REFERENCE_GUIDE_TEMPLATE = '## Parall References\n\nEvery entity on Parall has a `prll://` URI. Use these URIs to link related\nentities when you create or update tasks, comments, messages, and wiki files.\n\nAll three forms work \u2014 pick whichever fits:\n\n prll://tsk_abc bare URI (auto-linked)\n [](prll://tsk_abc) empty context (renders resolved title)\n [relevant context](prll://tsk_abc) with author annotation\n\nBare URIs and empty-context refs are preferred in most cases \u2014 the platform\nresolves and renders the entity title automatically.\n\n### Mentioning people and agents\n\nA real member mention is a `prll://usr_...` reference. Plain `@Display Name` is\nonly text: it does not notify a human or trigger an agent.\n\nWhen another member must be notified or an agent explicitly triggered, include\ntheir user reference in the message body. Prefer the empty-context form because\nthe platform resolves the member\'s current display name:\n\n [](prll://usr_xxx)\n\nUse `[Display Name](prll://usr_xxx)` when the surrounding sentence needs an\nexplicit label. Find the user ID in the incoming message or with\n`parall members list`. Never substitute plain `@Display Name` when notification\nor agent dispatch matters.\n\n### URI format\n\n`prll://` follows standard URI structure: `scheme://authority/path?query#fragment`.\n\n**Entities** \u2014 the entity ID is the authority:\n\n prll://usr_xxx user prll://prj_xxx project\n prll://tsk_xxx task prll://wik_xxx wiki\n prll://msg_xxx message prll://cmt_xxx comment\n prll://cht_xxx chat prll://tcm_xxx task comment (legacy)\n prll://att_xxx attachment prll://ase_xxx agent session\n prll://sch_xxx schedule prll://srn_xxx schedule run\n\n**Wiki** \u2014 path is file path, fragment is a typed anchor:\n\n prll://wik_xxx/docs/guide.md file\n prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)\n prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)\n\n Anchor types: `h=` heading, `l=` line/range, `s=` symbol.\n Line anchors in persistent content require `?rev=<full-40-char-sha>`.\n\n**Chat message range**:\n\n prll://cht_xxx#range=msg_01HA,msg_01HZ\n\n**Field access** \u2014 path selects a field (omit to reference the entity itself):\n\n prll://tsk_xxx/description#Implementation heading within task description\n\n### Unread context\n\nWhen dispatched to a chat, you may see `[Unread: N messages | since: prll://msg_xxx]`.\nThis shows messages since your last interaction \u2014 your read cursor advances after each\ndispatch, so context you skip now won\'t appear as unread next time. Use\n`parall messages list <chat> --limit 20` to fetch recent context. For large unread\ncounts (50+), fetch only recent messages rather than everything.\n\nThread dispatches may show `[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]`.\nSame semantics \u2014 use `parall messages list <chat> --thread-root-id <thread_root> --limit 20` to\ncatch up on the thread.\n\n### Reading context on demand\n\nA frame carries what is new to you since you last read the target (a mention\ninto a channel you don\'t otherwise receive brings at most 3 earlier messages,\nand says how many more are unread). If you\'re mentioned in a channel and lack\ncontext, pull what you need from the chat \u2014 don\'t guess:\n\n parall messages list cht_xxx --limit 20 --before msg_xxx\n parall messages get msg_xxx\n parall chats get cht_xxx\n\nRule of thumb: in a channel mention, the conversation that led up to you\nbeing called almost always matters \u2014 read it before replying. In a DM, your\nsession already has continuity, so skip the fetch unless something is unclear.\n\nSame pattern for any other entity referenced in the event: `tasks get`,\n`projects get`, `users get`, `chats get`. Follow the reflink, don\'t ask.\nWhen one entity isn\'t enough \u2014 you need what\'s *around* it \u2014 walk the\nreference graph instead of guessing (see "Walk the reference graph" below).\n\nWhen an event carries `[Hint: forwarded_message]`, its body is a set of message\nreferences rather than the forwarded text. Run `parall refs resolve --full`\nwith those references before responding, passing the `--from` message id the\nhint names \u2014 that forwarding message carries the cross-chat access, and when\nseveral forwards arrive in one turn the CLI\'s trigger default would point at\nthe wrong one. `--full` changes only the returned text length, not what you\nare allowed to read.\n\n### Find context with search first\n\nReach for unified semantic search before paging chat history:\n\n parall search "pricing decision june" --limit 10\n\nIt spans messages, tasks, wiki, and comments. Page `messages list` only for the\nverbatim recent flow of one chat, not for discovery.\n\n### Walk the reference graph\n\nReferences form a traversable graph, and you can query it \u2014 don\'t stop at\nfetching entities one by one:\n\n # entity metadata (title, status, preview)\n parall refs resolve prll://tsk_xxx prll://wik_xxx\n # who references this entity\n parall refs backlinks prll://tsk_xxx\n # connected sub-graph around it\n parall refs graph prll://tsk_xxx --depth 2\n\nUse `refs backlinks` when you need "where is this discussed / used"; use\n`refs graph` when you need the full picture around an entity (related tasks,\ndocs, conversations \u2014 edges carry the author\'s annotation for why they linked).\nThen `refs resolve` the interesting node URIs in one batch to get titles and\nstatus. `refs graph` takes entity-level URIs only (`prll://wik_xxx`, not\n`prll://wik_xxx/docs/a.md`). All results are filtered to what you can see.{{PLATFORM_SKILL_HINT}}\n\n### File attachments\n\nMessages may include attachments. They appear in events as:\n\n [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]\n\nTo download an attachment, use the CLI:\n\n parall files download att_xxx --output /tmp/screenshot.png\n\nTo send a file:\n\n parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"\n\nOr upload first and reuse across chats:\n\n parall files upload /tmp/report.pdf\n parall messages send prll://cht_aaa --attachment att_yyy --text "Report"\n parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"\n\nThe `--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 `$(...)`.\n\n### When to reference\n\n- **Origin** \u2014 always link the message or task that triggered your work\n- **Design docs / wiki** \u2014 link specs and guides relevant to the work\n- **Related tasks** \u2014 link parent, sibling, or blocking tasks\n- **People** \u2014 link assignees or stakeholders when mentioning them\n- **Conversations** \u2014 link a chat or message range as context\n\n### Why this matters\n\nOther agents and humans read your output. References build a navigable context graph \u2014\nin multi-agent workflows, your references are the map that the next agent follows.';
|
|
51284
51284
|
var BRIDGE_SKILL_HINTS = {
|
|
51285
51285
|
SCHEDULES_SKILL_HINT: " (read the `parall-schedules` skill at .parall/skills/parall-schedules.md).",
|
|
51286
51286
|
TASKS_SKILL_HINT: "\nDetails: read the `parall-tasks` skill at .parall/skills/parall-tasks.md and follow it.",
|
|
@@ -51394,15 +51394,6 @@ import * as fs from "node:fs";
|
|
|
51394
51394
|
import * as path from "node:path";
|
|
51395
51395
|
import { fileURLToPath } from "node:url";
|
|
51396
51396
|
var CAPABILITY_FEISHU_CLI = "feishu-cli";
|
|
51397
|
-
var CAPABILITY_SLACK_SEND = "slack-send";
|
|
51398
|
-
var CAPABILITY_WECHAT_SEND = "wechat-send";
|
|
51399
|
-
function channelCapabilityKeyFor(provider) {
|
|
51400
|
-
if (provider === "slack")
|
|
51401
|
-
return CAPABILITY_SLACK_SEND;
|
|
51402
|
-
if (provider === "wechat")
|
|
51403
|
-
return CAPABILITY_WECHAT_SEND;
|
|
51404
|
-
return `${provider}-cli`;
|
|
51405
|
-
}
|
|
51406
51397
|
var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
|
|
51407
51398
|
function capabilityBinDir(stateDir) {
|
|
51408
51399
|
return path.join(stateDir, "bin");
|
|
@@ -51483,213 +51474,18 @@ function buildErrorStepContent(message) {
|
|
|
51483
51474
|
return { text: message, suppressed: false, status: "error" };
|
|
51484
51475
|
}
|
|
51485
51476
|
|
|
51486
|
-
// ../agent-core/dist/
|
|
51487
|
-
var MESSAGE_REF_URI = "prll:\\/\\/msg_[A-Za-z0-9_-]+(?:\\/content\\?v=[1-9][0-9]{0,8}#t=[0-9]+-[0-9]+)?";
|
|
51488
|
-
var MESSAGE_RANGE_REF_URI = "prll:\\/\\/cht_[A-Za-z0-9_-]+#range=msg_[A-Za-z0-9_-]+,msg_[A-Za-z0-9_-]+";
|
|
51489
|
-
var REF_URI = `(?:${MESSAGE_REF_URI}|${MESSAGE_RANGE_REF_URI})`;
|
|
51490
|
-
var REF_TOKEN = `(?:${REF_URI}|\\[(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*\\]\\(${REF_URI}\\)|<${REF_URI}>)`;
|
|
51491
|
-
var FORWARDED_REF_LINE = new RegExp(`^${REF_TOKEN}(?:\\s+${REF_TOKEN})*$`);
|
|
51492
|
-
function isForwardedMessageBody(body) {
|
|
51493
|
-
const lines = body.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
51494
|
-
return lines.length > 0 && lines.every((line) => FORWARDED_REF_LINE.test(line));
|
|
51495
|
-
}
|
|
51477
|
+
// ../agent-core/dist/fork-prefix.js
|
|
51496
51478
|
function sanitizeMeta(value) {
|
|
51497
51479
|
return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
|
|
51498
51480
|
}
|
|
51499
|
-
function
|
|
51500
|
-
|
|
51501
|
-
if (status !== "rejected" || !normalized)
|
|
51502
|
-
return "";
|
|
51503
|
-
return `Reason (JSON): ${JSON.stringify(normalized)}`;
|
|
51504
|
-
}
|
|
51505
|
-
function threadWatcherHint(threadRootId) {
|
|
51506
|
-
return `[Hint: watcher \u2014 you were not addressed in this reply. Reply only if you add something new; otherwise run \`parall no-reply\`. If this thread is not relevant to you, or you have nothing more to contribute, run \`parall messages unwatch prll://${threadRootId}\` so later replies stop waking you.]`;
|
|
51507
|
-
}
|
|
51508
|
-
function buildEventBody(event) {
|
|
51509
|
-
const lines = [];
|
|
51510
|
-
if (event.type === "message") {
|
|
51511
|
-
lines.push(`[Event: message.new]`);
|
|
51512
|
-
const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
|
|
51513
|
-
lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
|
|
51514
|
-
lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
|
|
51515
|
-
lines.push(`[Message ID: prll://${event.messageId}]`);
|
|
51516
|
-
if (event.threadRootId) {
|
|
51517
|
-
const threadMeta = [
|
|
51518
|
-
`prll://${event.threadRootId}`,
|
|
51519
|
-
event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
|
|
51520
|
-
event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
|
|
51521
|
-
event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
|
|
51522
|
-
].filter(Boolean).join(" | ");
|
|
51523
|
-
lines.push(`[Thread: ${threadMeta}]`);
|
|
51524
|
-
}
|
|
51525
|
-
if (event.deliveryReason)
|
|
51526
|
-
lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
|
|
51527
|
-
if (event.deliveryReason === "watcher" && event.threadRootId) {
|
|
51528
|
-
lines.push(threadWatcherHint(sanitizeMeta(event.threadRootId)));
|
|
51529
|
-
}
|
|
51530
|
-
if (event.unreadCount != null && event.unreadCount > 1) {
|
|
51531
|
-
const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
|
|
51532
|
-
const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
|
|
51533
|
-
let line = `[Unread: ${countStr} messages${sinceStr}]`;
|
|
51534
|
-
if (event.unreadCount > 50)
|
|
51535
|
-
line += ` \u2014 fetch recent context with --limit, not all`;
|
|
51536
|
-
lines.push(line);
|
|
51537
|
-
}
|
|
51538
|
-
if (event.noReply)
|
|
51539
|
-
lines.push(`[Hint: no_reply]`);
|
|
51540
|
-
if (isForwardedMessageBody(event.body)) {
|
|
51541
|
-
lines.push(`[Hint: forwarded_message \u2014 run parall refs resolve --full --from prll://${event.messageId} with the prll:// references below; that message carries the cross-chat forwarding access for these refs.]`);
|
|
51542
|
-
}
|
|
51543
|
-
if (event.attachments?.length) {
|
|
51544
|
-
for (const att of event.attachments) {
|
|
51545
|
-
const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
|
|
51546
|
-
lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
|
|
51547
|
-
}
|
|
51548
|
-
}
|
|
51549
|
-
lines.push("", event.body);
|
|
51550
|
-
} else if (event.type === "task_comment") {
|
|
51551
|
-
lines.push(`[Event: task.comment.created]`);
|
|
51552
|
-
const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
|
|
51553
|
-
lines.push(`[Task: ${taskLabel}]`);
|
|
51554
|
-
if (event.deliveryReason)
|
|
51555
|
-
lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
|
|
51556
|
-
lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
|
|
51557
|
-
lines.push(`[Comment ID: prll://${event.messageId}]`);
|
|
51558
|
-
lines.push("", event.body);
|
|
51559
|
-
} else if (event.type === "wiki_comment") {
|
|
51560
|
-
lines.push(`[Event: wiki.comment.created]`);
|
|
51561
|
-
const target = event.replyTargetUri ?? `prll://${event.targetId}`;
|
|
51562
|
-
if (event.targetType === "changeset") {
|
|
51563
|
-
lines.push(`[Wiki Changeset: ${target}]`);
|
|
51564
|
-
} else {
|
|
51565
|
-
lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
|
|
51566
|
-
}
|
|
51567
|
-
if (event.deliveryReason)
|
|
51568
|
-
lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
|
|
51569
|
-
lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
|
|
51570
|
-
lines.push(`[Comment ID: prll://${event.messageId}]`);
|
|
51571
|
-
lines.push("", event.body);
|
|
51572
|
-
} else if (event.type === "approval") {
|
|
51573
|
-
lines.push(`[Event: approval.decided]`);
|
|
51574
|
-
lines.push(`[Approval: prll://${event.messageId}]`);
|
|
51575
|
-
lines.push(`[Chat: prll://${event.targetId}]`);
|
|
51576
|
-
lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
|
|
51577
|
-
lines.push("", event.body);
|
|
51578
|
-
} else if (event.type === "schedule") {
|
|
51579
|
-
lines.push(`[Event: schedule.fired]`);
|
|
51580
|
-
lines.push(`[Schedule: prll://${event.targetId}]`);
|
|
51581
|
-
lines.push(`[Run: prll://${event.messageId}]`);
|
|
51582
|
-
if (event.scheduledFireAt)
|
|
51583
|
-
lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
|
|
51584
|
-
if (event.attachedUri)
|
|
51585
|
-
lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
|
|
51586
|
-
lines.push("", event.body);
|
|
51587
|
-
} else if (event.type === "channel_message") {
|
|
51588
|
-
lines.push(`[Event: channel.message]`);
|
|
51589
|
-
const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
|
|
51590
|
-
const convType = sanitizeMeta(event.channelConversationType ?? "conversation");
|
|
51591
|
-
const convId = event.channelExternalConversationId ? sanitizeMeta(event.channelExternalConversationId) : void 0;
|
|
51592
|
-
const convName = event.channelExternalConversationName ? sanitizeMeta(event.channelExternalConversationName) : void 0;
|
|
51593
|
-
const convLabel = convName ? `${convName} (${convId ? `${convId}, ` : ""}${convType})` : convId ? `${convId} (${convType})` : convType;
|
|
51594
|
-
lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
|
|
51595
|
-
lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
|
|
51596
|
-
if (event.channelExternalMessageId) {
|
|
51597
|
-
lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
|
|
51598
|
-
}
|
|
51599
|
-
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.]`);
|
|
51600
|
-
lines.push("", event.body);
|
|
51601
|
-
} else if (event.type === "external_trigger") {
|
|
51602
|
-
lines.push(`[Event: external.trigger]`);
|
|
51603
|
-
lines.push(`[Trigger: prll://${event.targetId}]`);
|
|
51604
|
-
lines.push(`[Run: prll://${event.messageId}]`);
|
|
51605
|
-
if (event.externalConnectionId) {
|
|
51606
|
-
const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
|
|
51607
|
-
lines.push(`[Connection: ${label}]`);
|
|
51608
|
-
}
|
|
51609
|
-
if (event.externalIngressEventId)
|
|
51610
|
-
lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
|
|
51611
|
-
if (event.attachedUri)
|
|
51612
|
-
lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
|
|
51613
|
-
if (event.externalConnectionSourceType) {
|
|
51614
|
-
lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
|
|
51615
|
-
}
|
|
51616
|
-
if (event.externalIngressEventType) {
|
|
51617
|
-
lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
|
|
51618
|
-
}
|
|
51619
|
-
lines.push("", event.body);
|
|
51620
|
-
} else {
|
|
51621
|
-
lines.push(`[Event: task.assigned]`);
|
|
51622
|
-
const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
|
|
51623
|
-
lines.push(`[Task: ${taskLabel}]`);
|
|
51624
|
-
lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
|
|
51625
|
-
lines.push("", event.body);
|
|
51626
|
-
}
|
|
51627
|
-
return lines.join("\n") + buildSendMessageHint(event);
|
|
51628
|
-
}
|
|
51629
|
-
function buildEventBodyForForkResult(event) {
|
|
51630
|
-
return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
|
|
51481
|
+
function eventBody(event) {
|
|
51482
|
+
return event.frame ?? "";
|
|
51631
51483
|
}
|
|
51632
|
-
function
|
|
51633
|
-
|
|
51634
|
-
return "";
|
|
51635
|
-
if (event.type === "wiki_comment" && event.replyTargetUri) {
|
|
51636
|
-
const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
|
|
51637
|
-
return `
|
|
51638
|
-
<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>`;
|
|
51639
|
-
}
|
|
51640
|
-
if (event.targetId.startsWith("cht_")) {
|
|
51641
|
-
if (event.threadRootId) {
|
|
51642
|
-
return `
|
|
51643
|
-
<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>`;
|
|
51644
|
-
}
|
|
51645
|
-
return `
|
|
51646
|
-
<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>`;
|
|
51647
|
-
}
|
|
51648
|
-
if (event.targetId.startsWith("tsk_")) {
|
|
51649
|
-
return `
|
|
51650
|
-
<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>`;
|
|
51651
|
-
}
|
|
51652
|
-
if (event.targetId.startsWith("sch_")) {
|
|
51653
|
-
return `
|
|
51654
|
-
<system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
|
|
51655
|
-
}
|
|
51656
|
-
if (event.type === "channel_message") {
|
|
51657
|
-
if (event.channelCliCapable) {
|
|
51658
|
-
if (event.channelProvider === "slack") {
|
|
51659
|
-
const channelArg = event.channelExternalConversationId ? ` --channel "${event.channelExternalConversationId}"` : " --channel <conversation id from this event>";
|
|
51660
|
-
const replyTo = event.channelExternalMessageId ? ` --reply-to "${event.channelExternalMessageId}"` : "";
|
|
51661
|
-
return `
|
|
51662
|
-
<system-reminder>To reply, use the platform verb: \`parall slack send${channelArg}${replyTo} --text <your reply>\`. In channels --reply-to is REQUIRED (the reply lands in that message's thread); in DMs it is optional (DMs are linear). \`parall slack send\` is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
|
|
51663
|
-
}
|
|
51664
|
-
if (event.channelProvider === "wechat") {
|
|
51665
|
-
const toArg = event.channelExternalConversationId ? ` --to "${event.channelExternalConversationId}"` : " --to <wxid from this event>";
|
|
51666
|
-
const atArg = event.channelConversationType === "group" ? event.senderId && event.senderId !== "external" ? ` --at "${event.senderId}"` : " --at <wxid of the person you are answering>" : "";
|
|
51667
|
-
const historyArg = event.channelExternalConversationId ? ` --conversation "${event.channelExternalConversationId}"` : " --conversation <wxid from this event>";
|
|
51668
|
-
return `
|
|
51669
|
-
<system-reminder>Need earlier context? Run \`parall wechat history${historyArg}\`; history is not inserted automatically. To reply, use the platform verb: \`parall wechat send${toArg}${atArg} --text-file - <<'EOF'\` \u2026 \`EOF\` (or --text "<short text>" for simple literals \u2014 the quoted heredoc keeps $, backticks and apostrophes literal). In group chats, --at @-mentions the person you are answering. \`parall wechat send\` is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
|
|
51670
|
-
}
|
|
51671
|
-
if (!event.channelProvider) {
|
|
51672
|
-
return `
|
|
51673
|
-
<system-reminder>To reply, use the channel capability granted in your system prompt \u2014 for Feishu conversations that is \`lark-cli im\`, for Slack it is \`parall slack send\` (pass the message id from this event as --reply-to), for WeChat it is \`parall wechat send\`. That capability is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
|
|
51674
|
-
}
|
|
51675
|
-
const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
|
|
51676
|
-
const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
|
|
51677
|
-
return `
|
|
51678
|
-
<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>`;
|
|
51679
|
-
}
|
|
51680
|
-
const platform = event.channelProvider ?? "the external platform";
|
|
51681
|
-
return `
|
|
51682
|
-
<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>`;
|
|
51683
|
-
}
|
|
51684
|
-
if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
|
|
51685
|
-
return `
|
|
51686
|
-
<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>`;
|
|
51687
|
-
}
|
|
51688
|
-
return "";
|
|
51484
|
+
function forkResultBody(event) {
|
|
51485
|
+
return eventBody(event).replace(/\n\[Reminder[^\n]*\]$/, "");
|
|
51689
51486
|
}
|
|
51690
51487
|
function buildForkScopePrefix(event) {
|
|
51691
|
-
|
|
51692
|
-
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.
|
|
51488
|
+
return `[Fork scope: You are a parallel worker forked from the main session to handle prll://${event.targetId}. 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.
|
|
51693
51489
|
|
|
51694
51490
|
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.
|
|
51695
51491
|
|
|
@@ -51718,6 +51514,26 @@ function buildForkResultPrefix(results) {
|
|
|
51718
51514
|
|
|
51719
51515
|
// ../agent-core/dist/gateway-base.js
|
|
51720
51516
|
import * as os from "node:os";
|
|
51517
|
+
|
|
51518
|
+
// ../agent-core/dist/change-source.js
|
|
51519
|
+
var CHANGE_REASONS = /* @__PURE__ */ new Set([
|
|
51520
|
+
"edited",
|
|
51521
|
+
"deleted",
|
|
51522
|
+
"unmentioned",
|
|
51523
|
+
"mention",
|
|
51524
|
+
"reaction"
|
|
51525
|
+
]);
|
|
51526
|
+
function splitChangeSource(sourceId) {
|
|
51527
|
+
const i = sourceId.indexOf("~");
|
|
51528
|
+
if (i <= 0)
|
|
51529
|
+
return { messageId: sourceId };
|
|
51530
|
+
const [reason] = sourceId.slice(i + 1).split("~");
|
|
51531
|
+
if (!reason || !CHANGE_REASONS.has(reason))
|
|
51532
|
+
return { messageId: sourceId };
|
|
51533
|
+
return { messageId: sourceId.slice(0, i), reason };
|
|
51534
|
+
}
|
|
51535
|
+
|
|
51536
|
+
// ../agent-core/dist/gateway-base.js
|
|
51721
51537
|
import * as fs3 from "node:fs";
|
|
51722
51538
|
import * as path3 from "node:path";
|
|
51723
51539
|
import { randomUUID } from "node:crypto";
|
|
@@ -51832,6 +51648,8 @@ var ENDPOINTS = {
|
|
|
51832
51648
|
MESSAGE_WATCH: (id) => `${API_BASE}/messages/${id}/watch`,
|
|
51833
51649
|
MESSAGE_WATCHERS: (id) => `${API_BASE}/messages/${id}/watchers`,
|
|
51834
51650
|
MESSAGE_WATCHING: (id) => `${API_BASE}/messages/${id}/watching`,
|
|
51651
|
+
/** Caller's attention levels across chats / threads / tasks. */
|
|
51652
|
+
WATCHES: (orgId) => `${API_BASE}/orgs/${orgId}/watches`,
|
|
51835
51653
|
MESSAGE_REACTIONS: (id) => `${API_BASE}/messages/${id}/reactions`,
|
|
51836
51654
|
MESSAGE_REACTION: (id, emoji) => `${API_BASE}/messages/${id}/reactions/${encodeURIComponent(emoji)}`,
|
|
51837
51655
|
// Upload (org-scoped)
|
|
@@ -51854,6 +51672,7 @@ var ENDPOINTS = {
|
|
|
51854
51672
|
AGENT_ACTIVITY: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/activity`,
|
|
51855
51673
|
AGENT_MONITOR: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/monitor`,
|
|
51856
51674
|
AGENT_ME: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me`,
|
|
51675
|
+
AGENT_REPLY_POLICY_CAPABILITY: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/reply-policy-capability`,
|
|
51857
51676
|
AGENT_NEW_SESSION: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/new-session`,
|
|
51858
51677
|
AGENT_DEEP_RESET: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/deep-reset`,
|
|
51859
51678
|
AGENT_SESSIONS: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/sessions`,
|
|
@@ -51890,6 +51709,7 @@ var ENDPOINTS = {
|
|
|
51890
51709
|
MACHINE_AGENT_WORKSPACE_SETUP: (orgId, machineId, agentId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/agents/${agentId}/workspace/setup`,
|
|
51891
51710
|
MACHINE_LLM_SOURCE: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/llm-source`,
|
|
51892
51711
|
MACHINE_PROVIDER_ENABLED: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/provider-enabled`,
|
|
51712
|
+
MACHINE_MANAGED_BY: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/managed-by`,
|
|
51893
51713
|
MACHINE_CAPABILITIES: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/capabilities`,
|
|
51894
51714
|
MACHINE_RUNTIME_AUTH: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/runtime-auth`,
|
|
51895
51715
|
MACHINE_KEYS: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/keys`,
|
|
@@ -52370,8 +52190,22 @@ var ProjectTaskClient = class {
|
|
|
52370
52190
|
async unsubscribeTaskMember(orgId, taskId, userId) {
|
|
52371
52191
|
return this.request("DELETE", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
|
|
52372
52192
|
}
|
|
52373
|
-
async watchThread(threadRootId) {
|
|
52374
|
-
return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId));
|
|
52193
|
+
async watchThread(threadRootId, body) {
|
|
52194
|
+
return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId), body);
|
|
52195
|
+
}
|
|
52196
|
+
// ---- Attention settings (agent-attention-design.md §4) ----
|
|
52197
|
+
/** The caller's watch rows: the setting per chat / thread. */
|
|
52198
|
+
async listWatches(orgId) {
|
|
52199
|
+
const res = await this.request("GET", ENDPOINTS.WATCHES(orgId));
|
|
52200
|
+
return res.data;
|
|
52201
|
+
}
|
|
52202
|
+
/**
|
|
52203
|
+
* Set the caller's setting on one target (prll://cht_ / msg_ root).
|
|
52204
|
+
* Threads are watched first when not yet; chats require membership (404
|
|
52205
|
+
* NOT_A_MEMBER otherwise). Tasks carry no setting (watch / unwatch only).
|
|
52206
|
+
*/
|
|
52207
|
+
async setWatchLevel(orgId, body) {
|
|
52208
|
+
return this.request("PUT", ENDPOINTS.WATCHES(orgId), body);
|
|
52375
52209
|
}
|
|
52376
52210
|
async unwatchThread(threadRootId) {
|
|
52377
52211
|
return this.request("DELETE", ENDPOINTS.MESSAGE_WATCH(threadRootId));
|
|
@@ -53420,6 +53254,15 @@ var ParallClient = class _ParallClient extends AttachmentClient {
|
|
|
53420
53254
|
const res = await this.request("GET", ENDPOINTS.APPROVALS_ACTIONS);
|
|
53421
53255
|
return res.data;
|
|
53422
53256
|
}
|
|
53257
|
+
/**
|
|
53258
|
+
* Action names plus the payload contract each documented action publishes
|
|
53259
|
+
* (field names, types, and where a CAS base like expected_version is read
|
|
53260
|
+
* from). Additive over getApprovableActions(): older servers omit
|
|
53261
|
+
* `contracts`.
|
|
53262
|
+
*/
|
|
53263
|
+
async getApprovableActionCatalog() {
|
|
53264
|
+
return this.request("GET", ENDPOINTS.APPROVALS_ACTIONS);
|
|
53265
|
+
}
|
|
53423
53266
|
// ---- Agents (org-scoped) ----
|
|
53424
53267
|
async createAgent(orgId, req, opts) {
|
|
53425
53268
|
return this.request("POST", ENDPOINTS.AGENTS(orgId), req, void 0, false, opts);
|
|
@@ -53644,6 +53487,19 @@ var ParallClient = class _ParallClient extends AttachmentClient {
|
|
|
53644
53487
|
provider_enabled: providerEnabled
|
|
53645
53488
|
});
|
|
53646
53489
|
}
|
|
53490
|
+
/**
|
|
53491
|
+
* Convert a member's personal device into an organization machine
|
|
53492
|
+
* (PATCH /machines/{id}/managed-by). One-way and idempotent; org admins only
|
|
53493
|
+
* (an admin-role agent qualifies). After conversion every org admin manages
|
|
53494
|
+
* the machine and the registrant is just a member. 'member' is rejected —
|
|
53495
|
+
* an org machine cannot become a personal device again. See
|
|
53496
|
+
* docs/engineering-design/org-machine-assets-design.md §4.
|
|
53497
|
+
*/
|
|
53498
|
+
async convertMachineToOrgManaged(orgId, machineId) {
|
|
53499
|
+
return this.request("PATCH", ENDPOINTS.MACHINE_MANAGED_BY(orgId, machineId), {
|
|
53500
|
+
managed_by: "org"
|
|
53501
|
+
});
|
|
53502
|
+
}
|
|
53647
53503
|
/**
|
|
53648
53504
|
* Replace the machine's capability set (admin). Primary use: healing a
|
|
53649
53505
|
* machine that registered without `browser_provider` during the capability
|
|
@@ -53893,6 +53749,18 @@ var ParallClient = class _ParallClient extends AttachmentClient {
|
|
|
53893
53749
|
async steerDispatch(orgId, req) {
|
|
53894
53750
|
return this.request("POST", ENDPOINTS.DISPATCH_STEER(orgId), req);
|
|
53895
53751
|
}
|
|
53752
|
+
/**
|
|
53753
|
+
* Declare the runtime contract for this WS connection: the runtime runs
|
|
53754
|
+
* what the server decides and takes the server-rendered wake frame from
|
|
53755
|
+
* claim / steer responses instead of filtering and rendering locally.
|
|
53756
|
+
* Bound to the connection's session id; re-declare on every hello.
|
|
53757
|
+
* 409 STALE_WS_SESSION when the id is not the agent's current connection.
|
|
53758
|
+
*/
|
|
53759
|
+
async declareReplyPolicyCapability(orgId, wsSessionId) {
|
|
53760
|
+
await this.request("PUT", ENDPOINTS.AGENT_REPLY_POLICY_CAPABILITY(orgId), {
|
|
53761
|
+
ws_session_id: wsSessionId
|
|
53762
|
+
});
|
|
53763
|
+
}
|
|
53896
53764
|
/** Advance exact runtime-input lifecycle for members of an explicit lane. */
|
|
53897
53765
|
async updateDispatchInputState(orgId, req) {
|
|
53898
53766
|
return this.request("POST", ENDPOINTS.DISPATCH_INPUT_STATE(orgId), req);
|
|
@@ -55224,20 +55092,6 @@ function buildApiError(res, rawErrorBody) {
|
|
|
55224
55092
|
return apiError;
|
|
55225
55093
|
}
|
|
55226
55094
|
|
|
55227
|
-
// ../sdk/dist/types.js
|
|
55228
|
-
var MENTION_ALL_USER_ID = "all";
|
|
55229
|
-
var MENTION_ALL_HUMANS_USER_ID = "allhuman";
|
|
55230
|
-
var MENTION_ALL_AGENTS_USER_ID = "allagent";
|
|
55231
|
-
function mentionTargetsUser(mentionUserId, userId, userType) {
|
|
55232
|
-
if (mentionUserId === userId || mentionUserId === MENTION_ALL_USER_ID)
|
|
55233
|
-
return true;
|
|
55234
|
-
if (mentionUserId === MENTION_ALL_HUMANS_USER_ID)
|
|
55235
|
-
return userType === "human";
|
|
55236
|
-
if (mentionUserId === MENTION_ALL_AGENTS_USER_ID)
|
|
55237
|
-
return userType === "agent";
|
|
55238
|
-
return false;
|
|
55239
|
-
}
|
|
55240
|
-
|
|
55241
55095
|
// ../sdk/dist/ws.js
|
|
55242
55096
|
function isRetryableNetworkError(err) {
|
|
55243
55097
|
return err instanceof Error && err.name === "ApiError" && "status" in err && err.status === 0;
|
|
@@ -55669,7 +55523,7 @@ var LaneLedger = class {
|
|
|
55669
55523
|
get contextDir() {
|
|
55670
55524
|
return this.opts.contextDir;
|
|
55671
55525
|
}
|
|
55672
|
-
/**
|
|
55526
|
+
/** Chat message events ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
|
|
55673
55527
|
handles(event) {
|
|
55674
55528
|
return event.type === "message" && event.targetId.startsWith("cht_");
|
|
55675
55529
|
}
|
|
@@ -55685,6 +55539,75 @@ var LaneLedger = class {
|
|
|
55685
55539
|
laneContextPath(lane) {
|
|
55686
55540
|
return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
|
|
55687
55541
|
}
|
|
55542
|
+
/**
|
|
55543
|
+
* Whether the server already rendered this message into a frame the model
|
|
55544
|
+
* saw on its live lane. The row is folded there and resolves with that
|
|
55545
|
+
* lane's turn — a local copy has nothing left to deliver.
|
|
55546
|
+
*/
|
|
55547
|
+
seenInFrame(targetId, threadRootId, messageId) {
|
|
55548
|
+
const lane = this.lanes.get(laneKeyForTarget(`prll://${targetId}`, threadRootId));
|
|
55549
|
+
return lane?.seen.has(messageId) ?? false;
|
|
55550
|
+
}
|
|
55551
|
+
/**
|
|
55552
|
+
* Hand the pending frame to the caller (once) with the members it covers
|
|
55553
|
+
* and what the claim said about the wake, and record those members as
|
|
55554
|
+
* seen. Absent frame ⇒ nothing new to render (every member already seen).
|
|
55555
|
+
*/
|
|
55556
|
+
takeFrame(lane) {
|
|
55557
|
+
const frame = lane.frame;
|
|
55558
|
+
const ids = lane.framed;
|
|
55559
|
+
for (const id of ids)
|
|
55560
|
+
lane.seen.add(id);
|
|
55561
|
+
lane.frame = void 0;
|
|
55562
|
+
lane.framed = [];
|
|
55563
|
+
const { input, noReply, attachments } = lane;
|
|
55564
|
+
lane.input = void 0;
|
|
55565
|
+
lane.noReply = void 0;
|
|
55566
|
+
lane.attachments = void 0;
|
|
55567
|
+
return { frame, ids, input, noReply, attachments };
|
|
55568
|
+
}
|
|
55569
|
+
/** Record what the claim response said about the wake alongside its frame. */
|
|
55570
|
+
recordWake(lane, res) {
|
|
55571
|
+
if (res.input)
|
|
55572
|
+
lane.input = res.input;
|
|
55573
|
+
if (res.no_reply != null)
|
|
55574
|
+
lane.noReply = res.no_reply;
|
|
55575
|
+
if (res.attachments?.length) {
|
|
55576
|
+
lane.attachments = res.attachments.map((a) => ({
|
|
55577
|
+
id: a.id,
|
|
55578
|
+
fileName: a.file_name ?? "",
|
|
55579
|
+
fileSize: a.file_size ?? 0,
|
|
55580
|
+
mimeType: a.mime_type ?? ""
|
|
55581
|
+
}));
|
|
55582
|
+
}
|
|
55583
|
+
}
|
|
55584
|
+
/** The injection landed: the model has seen these members. */
|
|
55585
|
+
markSeen(event, ids) {
|
|
55586
|
+
const lane = this.lanes.get(this.laneKeyFor(event));
|
|
55587
|
+
if (!lane)
|
|
55588
|
+
return;
|
|
55589
|
+
for (const id of ids)
|
|
55590
|
+
lane.seen.add(id);
|
|
55591
|
+
}
|
|
55592
|
+
/**
|
|
55593
|
+
* The injection did not land (turn already over, process gone): keep the
|
|
55594
|
+
* server's increment as the lane's pending frame so the buffered copy's
|
|
55595
|
+
* drain renders it as its own turn instead of skipping it as seen.
|
|
55596
|
+
*/
|
|
55597
|
+
deferFrame(event, frame, ids) {
|
|
55598
|
+
const lane = this.lanes.get(this.laneKeyFor(event));
|
|
55599
|
+
if (!lane)
|
|
55600
|
+
return;
|
|
55601
|
+
this.recordFrame(lane, frame, ids);
|
|
55602
|
+
}
|
|
55603
|
+
recordFrame(lane, frame, ids) {
|
|
55604
|
+
if (!frame)
|
|
55605
|
+
return;
|
|
55606
|
+
lane.frame = lane.frame ? `${lane.frame}
|
|
55607
|
+
|
|
55608
|
+
${frame}` : frame;
|
|
55609
|
+
lane.framed.push(...ids);
|
|
55610
|
+
}
|
|
55688
55611
|
/**
|
|
55689
55612
|
* Claim (or reuse) the lane for a group of same-lane message events and
|
|
55690
55613
|
* fold every group member into it. Returns 'foreign' when a healthy
|
|
@@ -55734,11 +55657,15 @@ var LaneLedger = class {
|
|
|
55734
55657
|
threadRootId: trigger.threadRootId,
|
|
55735
55658
|
coverageMode: actualCoverage,
|
|
55736
55659
|
folded: /* @__PURE__ */ new Map(),
|
|
55660
|
+
framed: [],
|
|
55661
|
+
seen: /* @__PURE__ */ new Set(),
|
|
55737
55662
|
...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
|
|
55738
55663
|
};
|
|
55739
55664
|
for (const ev of res.events ?? []) {
|
|
55740
55665
|
lane.folded.set(ev.source_id, ev.id);
|
|
55741
55666
|
}
|
|
55667
|
+
this.recordFrame(lane, res.frame, (res.events ?? []).map((ev) => ev.source_id));
|
|
55668
|
+
this.recordWake(lane, res);
|
|
55742
55669
|
this.lanes.set(laneKey, lane);
|
|
55743
55670
|
}
|
|
55744
55671
|
for (const ev of events) {
|
|
@@ -55752,6 +55679,7 @@ var LaneLedger = class {
|
|
|
55752
55679
|
...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
|
|
55753
55680
|
});
|
|
55754
55681
|
lane.folded.set(ev.messageId, res.dispatch_event_id);
|
|
55682
|
+
this.recordFrame(lane, res.frame, [ev.messageId]);
|
|
55755
55683
|
} catch (err) {
|
|
55756
55684
|
if (isStaleLane(err)) {
|
|
55757
55685
|
this.lanes.delete(laneKey);
|
|
@@ -55775,8 +55703,13 @@ var LaneLedger = class {
|
|
|
55775
55703
|
const lane = this.lanes.get(laneKey);
|
|
55776
55704
|
if (!lane)
|
|
55777
55705
|
return null;
|
|
55706
|
+
if (lane.seen.has(event.messageId))
|
|
55707
|
+
return null;
|
|
55778
55708
|
if (lane.folded.has(event.messageId)) {
|
|
55779
|
-
return {
|
|
55709
|
+
return {
|
|
55710
|
+
inputLifecycle: this.inputLifecycleFor(lane, [event.messageId]),
|
|
55711
|
+
covered: [event.messageId]
|
|
55712
|
+
};
|
|
55780
55713
|
}
|
|
55781
55714
|
try {
|
|
55782
55715
|
const res = await this.opts.client.steerDispatch(this.opts.orgId, {
|
|
@@ -55786,7 +55719,12 @@ var LaneLedger = class {
|
|
|
55786
55719
|
...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
|
|
55787
55720
|
});
|
|
55788
55721
|
lane.folded.set(event.messageId, res.dispatch_event_id);
|
|
55789
|
-
|
|
55722
|
+
const covered = [event.messageId];
|
|
55723
|
+
return {
|
|
55724
|
+
inputLifecycle: this.inputLifecycleFor(lane, covered),
|
|
55725
|
+
frame: res.frame,
|
|
55726
|
+
covered
|
|
55727
|
+
};
|
|
55790
55728
|
} catch (err) {
|
|
55791
55729
|
if (isStaleLane(err)) {
|
|
55792
55730
|
this.lanes.delete(laneKey);
|
|
@@ -55801,10 +55739,18 @@ var LaneLedger = class {
|
|
|
55801
55739
|
* batched prompt covers every WorkItem represented in that single frame.
|
|
55802
55740
|
*/
|
|
55803
55741
|
inputLifecycle(lane, events) {
|
|
55742
|
+
return this.inputLifecycleFor(lane, events.map((event) => event.messageId));
|
|
55743
|
+
}
|
|
55744
|
+
/**
|
|
55745
|
+
* Exact lifecycle over a set of folded members by message id — the set a
|
|
55746
|
+
* prompt or injection actually delivers (frame coverage ∪ buffered group).
|
|
55747
|
+
*/
|
|
55748
|
+
inputLifecycleFor(lane, messageIds) {
|
|
55804
55749
|
if (lane.coverageMode !== "explicit")
|
|
55805
55750
|
return void 0;
|
|
55806
|
-
const
|
|
55807
|
-
|
|
55751
|
+
const unique = [...new Set(messageIds)];
|
|
55752
|
+
const dispatchEventIds = unique.map((messageId) => lane.folded.get(messageId)).filter((id) => Boolean(id));
|
|
55753
|
+
if (dispatchEventIds.length !== unique.length) {
|
|
55808
55754
|
throw new Error(`explicit lane ${lane.lane} is missing a folded WorkItem mapping`);
|
|
55809
55755
|
}
|
|
55810
55756
|
return {
|
|
@@ -56002,10 +55948,12 @@ var LaneLedger = class {
|
|
|
56002
55948
|
return this.lanes.size;
|
|
56003
55949
|
}
|
|
56004
55950
|
/**
|
|
56005
|
-
* Claim the single-member lane of one typed WorkItem (resource = dsp:<id>)
|
|
56006
|
-
* by WorkItem id
|
|
56007
|
-
*
|
|
56008
|
-
*
|
|
55951
|
+
* Claim the single-member lane of one typed WorkItem (resource = dsp:<id>)
|
|
55952
|
+
* by WorkItem id. The server renders the wake frame on claim (or resolves
|
|
55953
|
+
* the item as stale and answers `claimed: false, reason: "stale"`).
|
|
55954
|
+
* Returns null when a healthy incumbent (another pod) holds it, the
|
|
55955
|
+
* WorkItem is already resolved, or the server found nothing to wake for
|
|
55956
|
+
* — the caller must skip processing.
|
|
56009
55957
|
*/
|
|
56010
55958
|
async claimTyped(ref) {
|
|
56011
55959
|
let res;
|
|
@@ -56020,8 +55968,15 @@ var LaneLedger = class {
|
|
|
56020
55968
|
throw new LedgerUnsupportedError("claim endpoint unavailable");
|
|
56021
55969
|
throw err;
|
|
56022
55970
|
}
|
|
56023
|
-
if (!res.claimed || !res.lane || !res.events?.length)
|
|
55971
|
+
if (!res.claimed || !res.lane || !res.events?.length) {
|
|
55972
|
+
if (res.reason === "stale") {
|
|
55973
|
+
this.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} resolved by the server as stale (${res.stale_reason ?? "unspecified"})`);
|
|
55974
|
+
} else if (res.claimed && res.lane) {
|
|
55975
|
+
await this.opts.client.releaseDispatchLane(this.opts.orgId, res.lane).catch(() => {
|
|
55976
|
+
});
|
|
55977
|
+
}
|
|
56024
55978
|
return null;
|
|
55979
|
+
}
|
|
56025
55980
|
const workItem = res.events[0];
|
|
56026
55981
|
const targetUri = `dsp:${workItem.id}`;
|
|
56027
55982
|
const leaseUntilMs = Date.parse(res.lease_until ?? "");
|
|
@@ -56031,9 +55986,13 @@ var LaneLedger = class {
|
|
|
56031
55986
|
targetUri,
|
|
56032
55987
|
coverageMode: "implicit",
|
|
56033
55988
|
folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
|
|
55989
|
+
framed: [],
|
|
55990
|
+
seen: /* @__PURE__ */ new Set(),
|
|
56034
55991
|
typedDispatchEventId: workItem.id,
|
|
56035
55992
|
...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
|
|
56036
55993
|
};
|
|
55994
|
+
this.recordFrame(lane, res.frame, [workItem.source_id]);
|
|
55995
|
+
this.recordWake(lane, res);
|
|
56037
55996
|
this.lanes.set(lane.laneKey, lane);
|
|
56038
55997
|
return lane;
|
|
56039
55998
|
}
|
|
@@ -56076,6 +56035,19 @@ function shiftMainBufferGroup(host, groupKey, preserveInjectedFrameBoundary) {
|
|
|
56076
56035
|
}
|
|
56077
56036
|
return events;
|
|
56078
56037
|
}
|
|
56038
|
+
function applyWake(event, wake) {
|
|
56039
|
+
if (wake.frame)
|
|
56040
|
+
event.frame = wake.frame;
|
|
56041
|
+
if (wake.input) {
|
|
56042
|
+
event.input = wake.input;
|
|
56043
|
+
if (wake.input.sender_id)
|
|
56044
|
+
event.senderId = wake.input.sender_id;
|
|
56045
|
+
}
|
|
56046
|
+
if (wake.noReply != null)
|
|
56047
|
+
event.noReply = wake.noReply;
|
|
56048
|
+
if (wake.attachments?.length)
|
|
56049
|
+
event.attachments = wake.attachments;
|
|
56050
|
+
}
|
|
56079
56051
|
function hasUninjectedSameLaneEventAhead(host, event) {
|
|
56080
56052
|
const eventIndex = host.dispatchState.mainBuffer.lastIndexOf(event);
|
|
56081
56053
|
if (eventIndex <= 0)
|
|
@@ -56093,10 +56065,17 @@ async function steerLaneMessage(host, event) {
|
|
|
56093
56065
|
const folded = await ledger.steerLive(event);
|
|
56094
56066
|
if (!folded)
|
|
56095
56067
|
return;
|
|
56096
|
-
|
|
56068
|
+
if (!folded.frame)
|
|
56069
|
+
return;
|
|
56070
|
+
event.frame = folded.frame;
|
|
56071
|
+
const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, eventBody(event), folded.inputLifecycle);
|
|
56097
56072
|
if (injected) {
|
|
56098
56073
|
host.injectedMainBufferEvents.add(event);
|
|
56074
|
+
ledger.markSeen(event, folded.covered);
|
|
56099
56075
|
opts.log?.info(`steer folded+injected for ${event.messageId} (will drain for bookkeeping)`);
|
|
56076
|
+
} else if (folded.frame) {
|
|
56077
|
+
ledger.deferFrame(event, folded.frame, folded.covered);
|
|
56078
|
+
opts.log?.info(`steer folded but not injected for ${event.messageId} \u2014 frame deferred to the drain`);
|
|
56100
56079
|
}
|
|
56101
56080
|
}
|
|
56102
56081
|
async function dispatchLaneGroup(host, opts) {
|
|
@@ -56109,18 +56088,9 @@ async function dispatchLaneGroup(host, opts) {
|
|
|
56109
56088
|
if (!(err instanceof LedgerUnsupportedError))
|
|
56110
56089
|
throw err;
|
|
56111
56090
|
host.disableLedger("claim endpoint missing");
|
|
56112
|
-
|
|
56113
|
-
|
|
56114
|
-
|
|
56115
|
-
return "shutdown";
|
|
56116
|
-
for (const ev of opts.events) {
|
|
56117
|
-
host.opts.client.ackDispatch(host.opts.config.org_id, {
|
|
56118
|
-
source_type: ev.ackSourceType ?? "message",
|
|
56119
|
-
source_id: ev.ackSourceId ?? ev.messageId
|
|
56120
|
-
}).catch(() => {
|
|
56121
|
-
});
|
|
56122
|
-
}
|
|
56123
|
-
return "dispatched";
|
|
56091
|
+
for (const ev of opts.events)
|
|
56092
|
+
host.dispatchedMessages.delete(ev.messageId);
|
|
56093
|
+
return "foreign";
|
|
56124
56094
|
}
|
|
56125
56095
|
if (!lane) {
|
|
56126
56096
|
for (const ev of opts.events) {
|
|
@@ -56128,11 +56098,32 @@ async function dispatchLaneGroup(host, opts) {
|
|
|
56128
56098
|
}
|
|
56129
56099
|
return "foreign";
|
|
56130
56100
|
}
|
|
56101
|
+
const pending = ledger.takeFrame(lane);
|
|
56102
|
+
const frame = pending.frame;
|
|
56103
|
+
if (!frame && opts.events.every((ev) => lane.seen.has(ev.messageId))) {
|
|
56104
|
+
host.opts.log?.info(`lane group for ${event.messageId} already rendered by the server frame \u2014 no turn`);
|
|
56105
|
+
const pendingInjections2 = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
|
|
56106
|
+
await ledger.completeIfIdle(lane.laneKey, pendingInjections2 || opts.hasMoreLocal());
|
|
56107
|
+
return "dispatched";
|
|
56108
|
+
}
|
|
56109
|
+
if (!frame) {
|
|
56110
|
+
host.opts.log?.warn(`lane group for ${event.messageId} claimed without a frame \u2014 releasing the members instead of running`);
|
|
56111
|
+
for (const ev of opts.events)
|
|
56112
|
+
host.dispatchedMessages.delete(ev.messageId);
|
|
56113
|
+
await ledger.release(lane.laneKey).catch(() => {
|
|
56114
|
+
});
|
|
56115
|
+
return "foreign";
|
|
56116
|
+
}
|
|
56117
|
+
applyWake(event, pending);
|
|
56131
56118
|
host.noteSessionLane(opts.sessionKey, lane.laneKey);
|
|
56132
56119
|
let dispatched = false;
|
|
56133
56120
|
try {
|
|
56134
|
-
const inputLifecycle = ledger.
|
|
56135
|
-
|
|
56121
|
+
const inputLifecycle = ledger.inputLifecycleFor(lane, [
|
|
56122
|
+
...opts.earlier.map((ev) => ev.messageId),
|
|
56123
|
+
event.messageId,
|
|
56124
|
+
...frame ? pending.ids : []
|
|
56125
|
+
]);
|
|
56126
|
+
dispatched = await host.runDispatch(event, opts.sessionKey, opts.bodyPrefix + eventBody(event), opts.earlier, opts.captureText, inputLifecycle);
|
|
56136
56127
|
} catch (err) {
|
|
56137
56128
|
host.noteSessionLane(opts.sessionKey, null);
|
|
56138
56129
|
await ledger.release(lane.laneKey).catch(() => {
|
|
@@ -56200,50 +56191,16 @@ async function resolveDispatchByID(host, dispatchEventId, lane) {
|
|
|
56200
56191
|
return "failed";
|
|
56201
56192
|
}
|
|
56202
56193
|
}
|
|
56203
|
-
function clearTypedDedupeForEvent(host, event) {
|
|
56204
|
-
const sourceId = event.ackSourceId;
|
|
56205
|
-
if (!sourceId)
|
|
56206
|
-
return;
|
|
56207
|
-
switch (event.ackSourceType) {
|
|
56208
|
-
case "task_activity": {
|
|
56209
|
-
const prefix = `${event.targetId}:`;
|
|
56210
|
-
for (const key of host.dispatchedTasks) {
|
|
56211
|
-
if (key.startsWith(prefix))
|
|
56212
|
-
host.dispatchedTasks.delete(key);
|
|
56213
|
-
}
|
|
56214
|
-
break;
|
|
56215
|
-
}
|
|
56216
|
-
case "comment":
|
|
56217
|
-
host.dispatchedTasks.delete(`comment:${sourceId}`);
|
|
56218
|
-
break;
|
|
56219
|
-
case "schedule_run":
|
|
56220
|
-
host.dispatchedTasks.delete(`schedule_run:${sourceId}`);
|
|
56221
|
-
break;
|
|
56222
|
-
case "external_trigger_run":
|
|
56223
|
-
host.dispatchedTasks.delete(`external_trigger_run:${sourceId}`);
|
|
56224
|
-
break;
|
|
56225
|
-
case "channel_message":
|
|
56226
|
-
host.dispatchedMessages.delete(`channel_message:${sourceId}`);
|
|
56227
|
-
break;
|
|
56228
|
-
case "approval":
|
|
56229
|
-
host.dispatchedTasks.delete(`approval:${sourceId}`);
|
|
56230
|
-
break;
|
|
56231
|
-
}
|
|
56232
|
-
}
|
|
56233
56194
|
async function settleDrainedTypedGroup(host, events, ids, turnErrored) {
|
|
56234
56195
|
if (turnErrored) {
|
|
56235
56196
|
host.opts.log?.info(`buffered typed turn for ${events[events.length - 1]?.messageId} surfaced a runtime error \u2014 leaving for re-drive`);
|
|
56236
|
-
for (const event of events)
|
|
56237
|
-
clearTypedDedupeForEvent(host, event);
|
|
56238
56197
|
return;
|
|
56239
56198
|
}
|
|
56240
56199
|
const legacyAckFrom = async (start) => {
|
|
56241
|
-
for (const
|
|
56200
|
+
for (const id of ids.slice(start)) {
|
|
56242
56201
|
try {
|
|
56243
56202
|
await host.opts.client.ackDispatchByID(host.opts.config.org_id, id);
|
|
56244
56203
|
} catch {
|
|
56245
|
-
} finally {
|
|
56246
|
-
clearTypedDedupeForEvent(host, events[start + j]);
|
|
56247
56204
|
}
|
|
56248
56205
|
}
|
|
56249
56206
|
};
|
|
@@ -56259,7 +56216,6 @@ async function settleDrainedTypedGroup(host, events, ids, turnErrored) {
|
|
|
56259
56216
|
await legacyAckFrom(i);
|
|
56260
56217
|
return;
|
|
56261
56218
|
}
|
|
56262
|
-
clearTypedDedupeForEvent(host, events[i]);
|
|
56263
56219
|
}
|
|
56264
56220
|
}
|
|
56265
56221
|
var TYPED_BACKOFF_BASE_MS = 2e3;
|
|
@@ -56295,18 +56251,8 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
|
|
|
56295
56251
|
}
|
|
56296
56252
|
host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
|
|
56297
56253
|
};
|
|
56298
|
-
const runLegacy = async () => {
|
|
56299
|
-
let acked = false;
|
|
56300
|
-
try {
|
|
56301
|
-
if (await run(ref.dispatchEventId)) {
|
|
56302
|
-
acked = settleAck(await hooks.legacyAck(ref.dispatchEventId));
|
|
56303
|
-
}
|
|
56304
|
-
} finally {
|
|
56305
|
-
settle(acked);
|
|
56306
|
-
}
|
|
56307
|
-
};
|
|
56308
56254
|
if (!host.laneLedger || host.ledgerDisabled) {
|
|
56309
|
-
|
|
56255
|
+
host.opts.log?.info(`typed dispatch ${backoffKey} skipped \u2014 the server renders no wake frame`);
|
|
56310
56256
|
return;
|
|
56311
56257
|
}
|
|
56312
56258
|
let lane;
|
|
@@ -56315,7 +56261,6 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
|
|
|
56315
56261
|
} catch (err) {
|
|
56316
56262
|
if (err instanceof LedgerUnsupportedError) {
|
|
56317
56263
|
host.disableLedger("claim endpoint missing");
|
|
56318
|
-
await runLegacy();
|
|
56319
56264
|
return;
|
|
56320
56265
|
}
|
|
56321
56266
|
throw err;
|
|
@@ -56327,7 +56272,7 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
|
|
|
56327
56272
|
let resolved = false;
|
|
56328
56273
|
let viaLegacyAck = false;
|
|
56329
56274
|
try {
|
|
56330
|
-
if (await run(lane
|
|
56275
|
+
if (await run(lane)) {
|
|
56331
56276
|
if (host.typedByIdCompleteUnsupported || !lane.typedDispatchEventId) {
|
|
56332
56277
|
viaLegacyAck = true;
|
|
56333
56278
|
resolved = settleAck(await hooks.legacyAck(lane.typedDispatchEventId));
|
|
@@ -56339,13 +56284,9 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
|
|
|
56339
56284
|
viaLegacyAck = true;
|
|
56340
56285
|
resolved = settleAck(await hooks.legacyAck(lane.typedDispatchEventId));
|
|
56341
56286
|
} else if (outcome === "stale") {
|
|
56342
|
-
hooks.clearDedupe?.();
|
|
56343
56287
|
resolved = true;
|
|
56344
56288
|
} else {
|
|
56345
56289
|
resolved = outcome === "ok";
|
|
56346
|
-
if (!resolved) {
|
|
56347
|
-
hooks.clearDedupe?.();
|
|
56348
|
-
}
|
|
56349
56290
|
}
|
|
56350
56291
|
}
|
|
56351
56292
|
}
|
|
@@ -56364,56 +56305,27 @@ async function consumeMessageWorkItem(host, item) {
|
|
|
56364
56305
|
return;
|
|
56365
56306
|
if (!host.tryClaimMessage(item.source_id))
|
|
56366
56307
|
return;
|
|
56367
|
-
if (host.dispatchState.mainBuffer.some((
|
|
56308
|
+
if (host.dispatchState.mainBuffer.some((event2) => event2.messageId === item.source_id))
|
|
56368
56309
|
return;
|
|
56369
|
-
|
|
56370
|
-
if (host.laneLedger && !host.ledgerDisabled && !host.typedByIdCompleteUnsupported) {
|
|
56371
|
-
void resolveDispatchByID(host, item.id).then((outcome) => {
|
|
56372
|
-
if (outcome === "unsupported") {
|
|
56373
|
-
host.typedByIdCompleteUnsupported = true;
|
|
56374
|
-
host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
|
|
56375
|
-
});
|
|
56376
|
-
}
|
|
56377
|
-
});
|
|
56378
|
-
return;
|
|
56379
|
-
}
|
|
56380
|
-
host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
|
|
56381
|
-
});
|
|
56382
|
-
};
|
|
56383
|
-
let msg = null;
|
|
56384
|
-
try {
|
|
56385
|
-
msg = await host.opts.client.getMessage(item.source_id);
|
|
56386
|
-
} catch (err) {
|
|
56387
|
-
const status = err?.status;
|
|
56388
|
-
if (status !== 404) {
|
|
56389
|
-
host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
|
|
56390
|
-
host.dispatchedMessages.delete(item.source_id);
|
|
56391
|
-
return;
|
|
56392
|
-
}
|
|
56393
|
-
}
|
|
56394
|
-
if (!msg || msg.sender_id === host.opts.agentUserId) {
|
|
56395
|
-
host.dispatchedMessages.delete(item.source_id);
|
|
56396
|
-
ackItem();
|
|
56310
|
+
if (host.laneLedger && !host.ledgerDisabled && host.laneLedger.seenInFrame(item.chat_id, item.thread_root_id ?? void 0, item.source_id)) {
|
|
56397
56311
|
return;
|
|
56398
56312
|
}
|
|
56399
|
-
const
|
|
56400
|
-
|
|
56401
|
-
|
|
56402
|
-
|
|
56403
|
-
|
|
56404
|
-
|
|
56405
|
-
|
|
56406
|
-
|
|
56407
|
-
|
|
56408
|
-
|
|
56409
|
-
|
|
56410
|
-
|
|
56313
|
+
const change = splitChangeSource(item.source_id);
|
|
56314
|
+
const event = {
|
|
56315
|
+
type: "message",
|
|
56316
|
+
targetId: item.chat_id,
|
|
56317
|
+
targetType: "chat",
|
|
56318
|
+
senderId: item.actor_id ?? "",
|
|
56319
|
+
messageId: item.source_id,
|
|
56320
|
+
threadRootId: item.thread_root_id ?? void 0,
|
|
56321
|
+
deliveryReason: item.delivery_reason ?? change.reason ?? void 0,
|
|
56322
|
+
ackSourceType: "message",
|
|
56323
|
+
ackSourceId: item.source_id,
|
|
56324
|
+
dispatchEventId: item.id
|
|
56325
|
+
};
|
|
56411
56326
|
try {
|
|
56412
|
-
const dispatched = await host.handleInboundEvent(
|
|
56413
|
-
if (dispatched) {
|
|
56414
|
-
if (!laneResolved)
|
|
56415
|
-
ackItem();
|
|
56416
|
-
} else {
|
|
56327
|
+
const dispatched = await host.handleInboundEvent(event);
|
|
56328
|
+
if (!dispatched) {
|
|
56417
56329
|
host.dispatchedMessages.delete(item.source_id);
|
|
56418
56330
|
}
|
|
56419
56331
|
} catch (err) {
|
|
@@ -57618,6 +57530,16 @@ function createOtelLogger(layer, prefix) {
|
|
|
57618
57530
|
|
|
57619
57531
|
// ../agent-core/dist/gateway-base.js
|
|
57620
57532
|
var LIVE_SESSION_STATUSES = /* @__PURE__ */ new Set(["open", "active", "idle"]);
|
|
57533
|
+
var TYPED_EVENT_KINDS = {
|
|
57534
|
+
task_assign: { type: "task", ackSourceType: "task_activity" },
|
|
57535
|
+
task_update: { type: "task", ackSourceType: "task_activity" },
|
|
57536
|
+
task_comment: { type: "task_comment", ackSourceType: "comment" },
|
|
57537
|
+
wiki_comment: { type: "wiki_comment", ackSourceType: "comment" },
|
|
57538
|
+
"schedule.fire": { type: "schedule", ackSourceType: "schedule_run" },
|
|
57539
|
+
external_trigger: { type: "external_trigger", ackSourceType: "external_trigger_run" },
|
|
57540
|
+
channel_message: { type: "channel_message", ackSourceType: "channel_message" },
|
|
57541
|
+
approval_decided: { type: "approval", ackSourceType: "approval" }
|
|
57542
|
+
};
|
|
57621
57543
|
function parseShutdownDeadlineMs(raw) {
|
|
57622
57544
|
if (!raw)
|
|
57623
57545
|
return void 0;
|
|
@@ -57651,6 +57573,9 @@ function inputStepIdempotencyKey(event) {
|
|
|
57651
57573
|
return randomUUID();
|
|
57652
57574
|
}
|
|
57653
57575
|
function resolveStepTarget(event) {
|
|
57576
|
+
if (event.input?.step_target) {
|
|
57577
|
+
return { target_type: event.input.step_target.type, target_id: event.input.step_target.id };
|
|
57578
|
+
}
|
|
57654
57579
|
if (event.type === "task" || event.targetId.startsWith("tsk_")) {
|
|
57655
57580
|
return { target_type: "task", target_id: event.targetId };
|
|
57656
57581
|
}
|
|
@@ -57671,48 +57596,63 @@ function resolveStepTarget(event) {
|
|
|
57671
57596
|
}
|
|
57672
57597
|
return { target_type: "", target_id: event.targetId || void 0 };
|
|
57673
57598
|
}
|
|
57674
|
-
function
|
|
57675
|
-
|
|
57676
|
-
|
|
57677
|
-
|
|
57678
|
-
|
|
57679
|
-
|
|
57680
|
-
|
|
57681
|
-
|
|
57682
|
-
|
|
57683
|
-
|
|
57684
|
-
|
|
57685
|
-
|
|
57686
|
-
|
|
57687
|
-
|
|
57599
|
+
function inputTriggerTypeFor(type) {
|
|
57600
|
+
switch (type) {
|
|
57601
|
+
case "task":
|
|
57602
|
+
return "task_assign";
|
|
57603
|
+
case "task_comment":
|
|
57604
|
+
return "task_comment";
|
|
57605
|
+
case "wiki_comment":
|
|
57606
|
+
return "wiki_comment";
|
|
57607
|
+
case "schedule":
|
|
57608
|
+
return "schedule_fire";
|
|
57609
|
+
case "external_trigger":
|
|
57610
|
+
return "external_trigger";
|
|
57611
|
+
case "channel_message":
|
|
57612
|
+
return "channel_message";
|
|
57613
|
+
case "approval":
|
|
57614
|
+
return "approval_decided";
|
|
57615
|
+
default:
|
|
57616
|
+
return "mention";
|
|
57617
|
+
}
|
|
57618
|
+
}
|
|
57619
|
+
function inputTriggerRef(event) {
|
|
57620
|
+
const sourceId = event.ackSourceId ?? event.messageId;
|
|
57621
|
+
switch (event.type) {
|
|
57622
|
+
case "task":
|
|
57623
|
+
return { task_id: event.targetId };
|
|
57624
|
+
case "task_comment":
|
|
57625
|
+
return { comment_id: sourceId, task_id: event.targetId };
|
|
57626
|
+
case "wiki_comment":
|
|
57627
|
+
return { comment_id: sourceId, target_uri: `prll://${event.targetId}` };
|
|
57628
|
+
case "schedule":
|
|
57629
|
+
return { schedule_id: event.targetId, run_id: sourceId };
|
|
57630
|
+
case "external_trigger":
|
|
57631
|
+
return { trigger_id: event.targetId, run_id: sourceId };
|
|
57632
|
+
case "channel_message":
|
|
57633
|
+
return { conversation_id: event.targetId, channel_message_id: sourceId };
|
|
57634
|
+
case "approval":
|
|
57635
|
+
return { approval_id: sourceId };
|
|
57636
|
+
default:
|
|
57637
|
+
return {
|
|
57638
|
+
message_id: splitChangeSource(event.messageId).messageId,
|
|
57639
|
+
// Thread context for the session→chat backlink: a thread reply can
|
|
57640
|
+
// only be navigated to with its thread root.
|
|
57641
|
+
...event.threadRootId ? { thread_root_id: event.threadRootId } : {}
|
|
57642
|
+
};
|
|
57688
57643
|
}
|
|
57689
|
-
return { routingKey, label, targetType };
|
|
57690
|
-
}
|
|
57691
|
-
async function fetchAllChats(client, orgId, chatInfoMap) {
|
|
57692
|
-
let cursor;
|
|
57693
|
-
let total = 0;
|
|
57694
|
-
do {
|
|
57695
|
-
const res = await client.getChats(orgId, { limit: 100, cursor });
|
|
57696
|
-
for (const chat of res.data) {
|
|
57697
|
-
chatInfoMap.set(chat.id, {
|
|
57698
|
-
type: chat.type,
|
|
57699
|
-
name: chat.name ?? null,
|
|
57700
|
-
agentRoutingMode: chat.agent_routing_mode
|
|
57701
|
-
});
|
|
57702
|
-
}
|
|
57703
|
-
total += res.data.length;
|
|
57704
|
-
cursor = res.has_more ? res.next_cursor : void 0;
|
|
57705
|
-
} while (cursor);
|
|
57706
|
-
return total;
|
|
57707
57644
|
}
|
|
57708
57645
|
var ParallAgentGateway = class {
|
|
57709
57646
|
opts;
|
|
57710
|
-
|
|
57711
|
-
dispatchedTasks = /* @__PURE__ */ new Set();
|
|
57712
|
-
// connection id → provider alias, for channel_message prompt labeling
|
|
57713
|
-
// (stable mapping; avoids one connection fetch per inbound message).
|
|
57714
|
-
channelConnectionProviders = /* @__PURE__ */ new Map();
|
|
57647
|
+
// In-process in-flight guard for message WorkItems (see LaneFlowHost).
|
|
57715
57648
|
dispatchedMessages = /* @__PURE__ */ new Set();
|
|
57649
|
+
/**
|
|
57650
|
+
* Consumption fence: no WorkItem is claimed before this connection's
|
|
57651
|
+
* runtime contract is declared (handleHello). A claim made before the
|
|
57652
|
+
* declaration would get no frame — and a frameless claim has nothing to
|
|
57653
|
+
* run. Open until the first hello starts a declaration.
|
|
57654
|
+
*/
|
|
57655
|
+
contractReady = Promise.resolve();
|
|
57716
57656
|
injectedMainBufferEvents = /* @__PURE__ */ new WeakSet();
|
|
57717
57657
|
// Per-WorkItem failure backoff for typed dispatch consumption — see
|
|
57718
57658
|
// LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
|
|
@@ -57824,29 +57764,6 @@ var ParallAgentGateway = class {
|
|
|
57824
57764
|
ws.on("hello", async (data) => {
|
|
57825
57765
|
await this.handleHello(data);
|
|
57826
57766
|
});
|
|
57827
|
-
ws.on("chat.update", (data) => {
|
|
57828
|
-
const changes = data.changes;
|
|
57829
|
-
if (!changes)
|
|
57830
|
-
return;
|
|
57831
|
-
const existing = this.chatInfoMap.get(data.chat_id);
|
|
57832
|
-
if (existing) {
|
|
57833
|
-
this.chatInfoMap.set(data.chat_id, {
|
|
57834
|
-
...existing,
|
|
57835
|
-
...typeof changes.type === "string" ? { type: changes.type } : {},
|
|
57836
|
-
...typeof changes.name === "string" ? { name: changes.name } : {},
|
|
57837
|
-
...typeof changes.agent_routing_mode === "string" ? { agentRoutingMode: changes.agent_routing_mode } : {}
|
|
57838
|
-
});
|
|
57839
|
-
} else if (typeof changes.type === "string") {
|
|
57840
|
-
this.chatInfoMap.set(data.chat_id, {
|
|
57841
|
-
type: changes.type,
|
|
57842
|
-
name: typeof changes.name === "string" ? changes.name : null,
|
|
57843
|
-
agentRoutingMode: typeof changes.agent_routing_mode === "string" ? changes.agent_routing_mode : "passive"
|
|
57844
|
-
});
|
|
57845
|
-
}
|
|
57846
|
-
});
|
|
57847
|
-
ws.on("message.new", async (data) => {
|
|
57848
|
-
await this.handleMessage(data);
|
|
57849
|
-
});
|
|
57850
57767
|
ws.on("agent_config.update", async (data) => {
|
|
57851
57768
|
this.opts.log?.info(`config update notification (version=${data.version})`);
|
|
57852
57769
|
try {
|
|
@@ -57874,135 +57791,11 @@ var ParallAgentGateway = class {
|
|
|
57874
57791
|
this.opts.log?.warn(`recovery.overflow \u2014 triggering full catch-up`);
|
|
57875
57792
|
this.catchUpFromDispatch().catch((err) => this.opts.log?.warn(`overflow catch-up failed: ${String(err)}`));
|
|
57876
57793
|
});
|
|
57877
|
-
ws.on("
|
|
57878
|
-
if (data.assignee_id !== this.opts.agentUserId)
|
|
57879
|
-
return;
|
|
57880
|
-
if (data.status !== "todo" && data.status !== "in_progress")
|
|
57881
|
-
return;
|
|
57794
|
+
ws.on("dispatch.new", async (data) => {
|
|
57882
57795
|
try {
|
|
57883
|
-
await this.
|
|
57884
|
-
legacyAck: (dispatchEventId) => {
|
|
57885
|
-
if (dispatchEventId) {
|
|
57886
|
-
return this.ackDispatchEvent(dispatchEventId, () => {
|
|
57887
|
-
this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
|
|
57888
|
-
});
|
|
57889
|
-
}
|
|
57890
|
-
return this.opts.client.ackDispatch(this.opts.config.org_id, {
|
|
57891
|
-
source_type: "task_activity",
|
|
57892
|
-
source_id: data.id
|
|
57893
|
-
}).then(() => true, (err) => {
|
|
57894
|
-
this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
|
|
57895
|
-
this.opts.log?.warn(`dispatch ack failed for task ${data.id}, releasing for re-drive: ${String(err)}`);
|
|
57896
|
-
return false;
|
|
57897
|
-
});
|
|
57898
|
-
},
|
|
57899
|
-
clearDedupe: () => this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`)
|
|
57900
|
-
});
|
|
57796
|
+
await this.consumeWorkItem(data);
|
|
57901
57797
|
} catch (err) {
|
|
57902
|
-
this.opts.log?.error(`
|
|
57903
|
-
}
|
|
57904
|
-
});
|
|
57905
|
-
ws.on("dispatch.new", async (data) => {
|
|
57906
|
-
if (data.event_type !== "message" && this.isBufferedTypedWorkItem(data.id)) {
|
|
57907
|
-
this.opts.log?.info(`typed dispatch ${data.id} already buffered for the drain \u2014 skipping re-claim`);
|
|
57908
|
-
return;
|
|
57909
|
-
}
|
|
57910
|
-
if (data.event_type === "task_assign") {
|
|
57911
|
-
if (!data.task_id)
|
|
57912
|
-
return;
|
|
57913
|
-
try {
|
|
57914
|
-
await this.handleTaskAssignmentRedrive(data);
|
|
57915
|
-
} catch (err) {
|
|
57916
|
-
this.opts.log?.error(`task assignment re-drive failed for ${data.task_id}: ${String(err)}`);
|
|
57917
|
-
}
|
|
57918
|
-
} else if (data.event_type === "task_comment") {
|
|
57919
|
-
if (!data.source_id || !data.task_id)
|
|
57920
|
-
return;
|
|
57921
|
-
try {
|
|
57922
|
-
await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleTaskComment(data.source_id, data.task_id ?? "", data.actor_id, data.delivery_reason, dispatchEventId), {
|
|
57923
|
-
legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
|
|
57924
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(data)
|
|
57925
|
-
});
|
|
57926
|
-
} catch (err) {
|
|
57927
|
-
this.opts.log?.error(`task comment dispatch failed for ${data.source_id}: ${String(err)}`);
|
|
57928
|
-
}
|
|
57929
|
-
} else if (data.event_type === "wiki_comment") {
|
|
57930
|
-
if (!data.source_id)
|
|
57931
|
-
return;
|
|
57932
|
-
try {
|
|
57933
|
-
await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleWikiComment(data.source_id, data.actor_id, data.delivery_reason, dispatchEventId), {
|
|
57934
|
-
legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
|
|
57935
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(data)
|
|
57936
|
-
});
|
|
57937
|
-
} catch (err) {
|
|
57938
|
-
this.opts.log?.error(`wiki comment dispatch failed for ${data.source_id}: ${String(err)}`);
|
|
57939
|
-
}
|
|
57940
|
-
} else if (data.event_type === "task_update") {
|
|
57941
|
-
if (!data.task_id)
|
|
57942
|
-
return;
|
|
57943
|
-
try {
|
|
57944
|
-
await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleTaskDispatch(data.task_id ?? "", data.source_id ?? data.task_id ?? "", {
|
|
57945
|
-
allowCreator: true,
|
|
57946
|
-
dispatchEventId
|
|
57947
|
-
}), {
|
|
57948
|
-
legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
|
|
57949
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(data)
|
|
57950
|
-
});
|
|
57951
|
-
} catch (err) {
|
|
57952
|
-
this.opts.log?.error(`task update dispatch failed for ${data.task_id}: ${String(err)}`);
|
|
57953
|
-
}
|
|
57954
|
-
} else if (data.event_type === "schedule.fire") {
|
|
57955
|
-
if (!data.source_id)
|
|
57956
|
-
return;
|
|
57957
|
-
try {
|
|
57958
|
-
await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleScheduleFire(data.source_id, data.actor_id, dispatchEventId), {
|
|
57959
|
-
legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
|
|
57960
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(data)
|
|
57961
|
-
});
|
|
57962
|
-
} catch (err) {
|
|
57963
|
-
this.opts.log?.error(`schedule fire dispatch failed for ${data.source_id}: ${String(err)}`);
|
|
57964
|
-
}
|
|
57965
|
-
} else if (data.event_type === "external_trigger") {
|
|
57966
|
-
if (!data.source_id)
|
|
57967
|
-
return;
|
|
57968
|
-
try {
|
|
57969
|
-
await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleExternalTriggerRun(data.source_id, dispatchEventId), {
|
|
57970
|
-
legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
|
|
57971
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(data)
|
|
57972
|
-
});
|
|
57973
|
-
} catch (err) {
|
|
57974
|
-
this.opts.log?.error(`external trigger dispatch failed for ${data.source_id}: ${String(err)}`);
|
|
57975
|
-
}
|
|
57976
|
-
} else if (data.event_type === "channel_message") {
|
|
57977
|
-
if (!data.source_id)
|
|
57978
|
-
return;
|
|
57979
|
-
try {
|
|
57980
|
-
await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleChannelMessage(data.source_id, dispatchEventId), {
|
|
57981
|
-
legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
|
|
57982
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(data)
|
|
57983
|
-
});
|
|
57984
|
-
} catch (err) {
|
|
57985
|
-
this.opts.log?.error(`channel message dispatch failed for ${data.source_id}: ${String(err)}`);
|
|
57986
|
-
}
|
|
57987
|
-
} else if (data.event_type === "approval_decided") {
|
|
57988
|
-
if (!data.source_id)
|
|
57989
|
-
return;
|
|
57990
|
-
try {
|
|
57991
|
-
await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleApprovalDecided(data.source_id, data.actor_id, data.chat_id ?? null, dispatchEventId), {
|
|
57992
|
-
legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
|
|
57993
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(data)
|
|
57994
|
-
});
|
|
57995
|
-
} catch (err) {
|
|
57996
|
-
this.opts.log?.error(`approval decided dispatch failed for ${data.source_id}: ${String(err)}`);
|
|
57997
|
-
}
|
|
57998
|
-
} else if (data.event_type === "message" && this.laneLedger && data.source_id && data.chat_id) {
|
|
57999
|
-
try {
|
|
58000
|
-
await this.handleMessageRedrive(data);
|
|
58001
|
-
} catch (err) {
|
|
58002
|
-
this.opts.log?.error(`message re-drive failed for ${data.source_id}: ${String(err)}`);
|
|
58003
|
-
}
|
|
58004
|
-
} else if (data.event_type !== "message") {
|
|
58005
|
-
this.opts.log?.info(`dispatch.new with unhandled event_type=${String(data.event_type)} (id=${data.id}) \u2014 no-op`);
|
|
57798
|
+
this.opts.log?.error(`dispatch ${data.id} (${String(data.event_type)}) failed: ${String(err)}`);
|
|
58006
57799
|
}
|
|
58007
57800
|
});
|
|
58008
57801
|
this.opts.log?.info(`connecting to ${this.opts.connectionLabel ?? "Parall WS"}...`);
|
|
@@ -58187,44 +57980,6 @@ var ParallAgentGateway = class {
|
|
|
58187
57980
|
isTypedEventBuffered(event) {
|
|
58188
57981
|
return this.isBufferedTypedWorkItem(event.dispatchEventId);
|
|
58189
57982
|
}
|
|
58190
|
-
// PARITY: this switch and gateway-lane-flow's clearTypedDedupeForEvent must
|
|
58191
|
-
// handle the same typed source families — extend BOTH when adding a typed
|
|
58192
|
-
// event type (same dedupe entries, keyed from different event shapes).
|
|
58193
|
-
clearTypedDispatchDedupe(item) {
|
|
58194
|
-
switch (item.event_type) {
|
|
58195
|
-
case "task_assign":
|
|
58196
|
-
case "task_update":
|
|
58197
|
-
if (item.task_id) {
|
|
58198
|
-
const prefix = `${item.task_id}:`;
|
|
58199
|
-
for (const key of this.dispatchedTasks) {
|
|
58200
|
-
if (key.startsWith(prefix))
|
|
58201
|
-
this.dispatchedTasks.delete(key);
|
|
58202
|
-
}
|
|
58203
|
-
}
|
|
58204
|
-
break;
|
|
58205
|
-
case "task_comment":
|
|
58206
|
-
case "wiki_comment":
|
|
58207
|
-
if (item.source_id)
|
|
58208
|
-
this.dispatchedTasks.delete(`comment:${item.source_id}`);
|
|
58209
|
-
break;
|
|
58210
|
-
case "schedule.fire":
|
|
58211
|
-
if (item.source_id)
|
|
58212
|
-
this.dispatchedTasks.delete(`schedule_run:${item.source_id}`);
|
|
58213
|
-
break;
|
|
58214
|
-
case "external_trigger":
|
|
58215
|
-
if (item.source_id)
|
|
58216
|
-
this.dispatchedTasks.delete(`external_trigger_run:${item.source_id}`);
|
|
58217
|
-
break;
|
|
58218
|
-
case "channel_message":
|
|
58219
|
-
if (item.source_id)
|
|
58220
|
-
this.dispatchedMessages.delete(`channel_message:${item.source_id}`);
|
|
58221
|
-
break;
|
|
58222
|
-
case "approval_decided":
|
|
58223
|
-
if (item.source_id)
|
|
58224
|
-
this.dispatchedTasks.delete(`approval:${item.source_id}`);
|
|
58225
|
-
break;
|
|
58226
|
-
}
|
|
58227
|
-
}
|
|
58228
57983
|
buildDispatchContext(event, sessionKey) {
|
|
58229
57984
|
const binding = this.sessionBindings.get(sessionKey);
|
|
58230
57985
|
return {
|
|
@@ -58237,7 +57992,7 @@ var ParallAgentGateway = class {
|
|
|
58237
57992
|
runtimeKey: this.opts.runtimeKey,
|
|
58238
57993
|
sessionId: binding?.agentSessionId,
|
|
58239
57994
|
chatId: event.type === "message" || event.type === "approval" ? event.targetId : void 0,
|
|
58240
|
-
triggerMessageId: event.messageId,
|
|
57995
|
+
triggerMessageId: splitChangeSource(event.messageId).messageId,
|
|
58241
57996
|
noReply: event.noReply ?? false,
|
|
58242
57997
|
contextFilePath: this.opts.contextFilePathForSession?.(sessionKey),
|
|
58243
57998
|
stepIdFilePath: this.opts.stepIdFilePathForSession?.(sessionKey),
|
|
@@ -58251,35 +58006,24 @@ var ParallAgentGateway = class {
|
|
|
58251
58006
|
}
|
|
58252
58007
|
async createInputStep(sessionId, event) {
|
|
58253
58008
|
const target = resolveStepTarget(event);
|
|
58009
|
+
const input = event.input;
|
|
58254
58010
|
await this.stepPersister.persist(sessionId, "input", {
|
|
58255
58011
|
step_type: "input",
|
|
58256
58012
|
target_type: target.target_type,
|
|
58257
58013
|
target_id: target.target_id,
|
|
58258
58014
|
idempotency_key: inputStepIdempotencyKey(event),
|
|
58259
58015
|
content: {
|
|
58260
|
-
|
|
58261
|
-
|
|
58262
|
-
|
|
58263
|
-
|
|
58264
|
-
|
|
58265
|
-
|
|
58266
|
-
|
|
58267
|
-
conversation_id: event.targetId,
|
|
58268
|
-
channel_message_id: event.messageId,
|
|
58269
|
-
provider: event.channelProvider,
|
|
58270
|
-
external_conversation_id: event.channelExternalConversationId
|
|
58271
|
-
} : event.type === "approval" ? { approval_id: event.messageId } : {
|
|
58272
|
-
message_id: event.messageId,
|
|
58273
|
-
// Thread context for the session→chat backlink:
|
|
58274
|
-
// a thread reply can only be navigated to with
|
|
58275
|
-
// its thread root (the chat surface rejects
|
|
58276
|
-
// bare thread-message targets).
|
|
58277
|
-
...event.threadRootId ? { thread_root_id: event.threadRootId } : {}
|
|
58278
|
-
},
|
|
58016
|
+
// What the server said about the wake (claim `input`), plus the
|
|
58017
|
+
// source pointer and the anchor the web needs to link a chat
|
|
58018
|
+
// message or a task to this session.
|
|
58019
|
+
trigger_type: input?.trigger_type ?? inputTriggerTypeFor(event.type),
|
|
58020
|
+
trigger_ref: inputTriggerRef(event),
|
|
58021
|
+
source_type: event.ackSourceType,
|
|
58022
|
+
source_id: event.ackSourceId ?? event.messageId,
|
|
58279
58023
|
sender_id: event.senderId,
|
|
58280
|
-
sender_name:
|
|
58281
|
-
summary: event.
|
|
58282
|
-
...
|
|
58024
|
+
...input?.sender_name ? { sender_name: input.sender_name } : {},
|
|
58025
|
+
summary: (input?.summary ?? eventBody(event)).substring(0, 200),
|
|
58026
|
+
...input?.sent_at ? { sent_at: input.sent_at } : {}
|
|
58283
58027
|
}
|
|
58284
58028
|
});
|
|
58285
58029
|
}
|
|
@@ -58791,13 +58535,14 @@ var ParallAgentGateway = class {
|
|
|
58791
58535
|
retainForkContinuationRetries(this.forkContinuationRetries, events, fork.continuationPrefix);
|
|
58792
58536
|
try {
|
|
58793
58537
|
const batchText = [];
|
|
58794
|
-
const
|
|
58538
|
+
const bodyPrefix = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last);
|
|
58539
|
+
const body = bodyPrefix + eventBody(last);
|
|
58795
58540
|
let dispatched;
|
|
58796
58541
|
if (this.usesLaneLedger(last)) {
|
|
58797
58542
|
const outcome = await this.dispatchLaneGroup({
|
|
58798
58543
|
events,
|
|
58799
58544
|
sessionKey: fork.fork.sessionKey,
|
|
58800
|
-
|
|
58545
|
+
bodyPrefix,
|
|
58801
58546
|
earlier,
|
|
58802
58547
|
captureText: batchText,
|
|
58803
58548
|
// Per-LANE residue check (parity with the main-buffer path):
|
|
@@ -58872,9 +58617,9 @@ var ParallAgentGateway = class {
|
|
|
58872
58617
|
sourceEvent: {
|
|
58873
58618
|
type: first.type,
|
|
58874
58619
|
targetId: fork.targetId,
|
|
58875
|
-
summary: fork.processedEvents.length === 1 ? `${first.type}
|
|
58620
|
+
summary: fork.processedEvents.length === 1 ? `${first.type} in ${fork.targetId}` : `${fork.processedEvents.length} events in ${fork.targetId}`
|
|
58876
58621
|
},
|
|
58877
|
-
eventBodies: fork.processedEvents.map((e) =>
|
|
58622
|
+
eventBodies: fork.processedEvents.map((e) => forkResultBody(e)),
|
|
58878
58623
|
actions: [],
|
|
58879
58624
|
agentSummary,
|
|
58880
58625
|
historyPath
|
|
@@ -58945,7 +58690,7 @@ var ParallAgentGateway = class {
|
|
|
58945
58690
|
outcome = await this.dispatchLaneGroup({
|
|
58946
58691
|
events,
|
|
58947
58692
|
sessionKey: this.opts.runtimeKey,
|
|
58948
|
-
|
|
58693
|
+
bodyPrefix: forkPrefix,
|
|
58949
58694
|
earlier,
|
|
58950
58695
|
hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === groupKey)
|
|
58951
58696
|
});
|
|
@@ -58987,16 +58732,14 @@ var ParallAgentGateway = class {
|
|
|
58987
58732
|
}
|
|
58988
58733
|
}
|
|
58989
58734
|
const isTypedGroup = events.every((ev) => ev.type !== "message");
|
|
58990
|
-
const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) =>
|
|
58735
|
+
const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => eventBody(ev)).join("\n\n") : eventBody(event);
|
|
58991
58736
|
let dispatched;
|
|
58992
58737
|
try {
|
|
58993
58738
|
dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + body, earlier);
|
|
58994
58739
|
} catch (err) {
|
|
58995
58740
|
if (!isTypedGroup)
|
|
58996
58741
|
throw err;
|
|
58997
|
-
this.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}
|
|
58998
|
-
for (const ev of events)
|
|
58999
|
-
clearTypedDedupeForEvent(this.laneFlowHost(), ev);
|
|
58742
|
+
this.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}): ${String(err)}`);
|
|
59000
58743
|
this.dispatchState.pendingForkResults.unshift(...pendingFork);
|
|
59001
58744
|
continue;
|
|
59002
58745
|
}
|
|
@@ -59017,7 +58760,6 @@ var ParallAgentGateway = class {
|
|
|
59017
58760
|
source_id: sourceId
|
|
59018
58761
|
}).catch(() => {
|
|
59019
58762
|
});
|
|
59020
|
-
clearTypedDedupeForEvent(this.laneFlowHost(), bufferedEvent);
|
|
59021
58763
|
}
|
|
59022
58764
|
} finally {
|
|
59023
58765
|
for (const id of drainingIds)
|
|
@@ -59060,7 +58802,7 @@ var ParallAgentGateway = class {
|
|
|
59060
58802
|
outcome = await this.dispatchLaneGroup({
|
|
59061
58803
|
events: [event],
|
|
59062
58804
|
sessionKey: this.opts.runtimeKey,
|
|
59063
|
-
|
|
58805
|
+
bodyPrefix: forkPrefix,
|
|
59064
58806
|
earlier: [],
|
|
59065
58807
|
hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === this.dispatchGroupKey(event))
|
|
59066
58808
|
});
|
|
@@ -59092,7 +58834,7 @@ var ParallAgentGateway = class {
|
|
|
59092
58834
|
}
|
|
59093
58835
|
let dispatched = false;
|
|
59094
58836
|
try {
|
|
59095
|
-
dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix +
|
|
58837
|
+
dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + eventBody(event));
|
|
59096
58838
|
if (dispatched && typedRefs && this.consumeTurnError(this.opts.runtimeKey)) {
|
|
59097
58839
|
this.opts.log?.info(`typed dispatch turn for ${event.messageId} surfaced a runtime error \u2014 releasing for retry`);
|
|
59098
58840
|
dispatched = false;
|
|
@@ -59126,7 +58868,7 @@ var ParallAgentGateway = class {
|
|
|
59126
58868
|
// the WorkItem stays live, and every re-drive injects it AGAIN (the
|
|
59127
58869
|
// 7/16 watcher duplicate-delivery loop, #1149). Typed events stay
|
|
59128
58870
|
// buffered; the drain claims them as their own turn.
|
|
59129
|
-
event.type === "message" && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey,
|
|
58871
|
+
event.type === "message" && event.frame != null && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, eventBody(event))
|
|
59130
58872
|
) {
|
|
59131
58873
|
this.opts.log?.info(`steer injected for ${event.messageId} (will drain for bookkeeping)`);
|
|
59132
58874
|
}
|
|
@@ -59187,605 +58929,75 @@ var ParallAgentGateway = class {
|
|
|
59187
58929
|
}
|
|
59188
58930
|
}
|
|
59189
58931
|
}
|
|
59190
|
-
|
|
59191
|
-
|
|
59192
|
-
|
|
59193
|
-
|
|
59194
|
-
|
|
59195
|
-
|
|
59196
|
-
|
|
59197
|
-
|
|
59198
|
-
|
|
59199
|
-
|
|
59200
|
-
};
|
|
59201
|
-
this.chatInfoMap.set(chatId, chatInfo);
|
|
59202
|
-
return chatInfo;
|
|
59203
|
-
} catch (err) {
|
|
59204
|
-
this.opts.log?.warn(`failed to resolve chat ${chatId}: ${String(err)}`);
|
|
59205
|
-
return null;
|
|
59206
|
-
}
|
|
59207
|
-
}
|
|
59208
|
-
async buildMessageDispatchDecision(chatId, message) {
|
|
59209
|
-
if (message.message_type !== "text") {
|
|
59210
|
-
return { action: "skip" };
|
|
59211
|
-
}
|
|
59212
|
-
const chatInfo = await this.getOrFetchChatInfo(chatId);
|
|
59213
|
-
if (!chatInfo)
|
|
59214
|
-
return { action: "retry" };
|
|
59215
|
-
const content = message.content;
|
|
59216
|
-
const body = content.text?.trim() ?? "";
|
|
59217
|
-
const hasAttachments = message.attachments?.length;
|
|
59218
|
-
if (!body && !hasAttachments)
|
|
59219
|
-
return { action: "skip" };
|
|
59220
|
-
const mentions = content.mentions ?? [];
|
|
59221
|
-
const isMentioned = mentions.some((mention) => mentionTargetsUser(mention.user_id, this.opts.agentUserId, "agent"));
|
|
59222
|
-
let deliveryReason;
|
|
59223
|
-
if (message.thread_root_id) {
|
|
59224
|
-
if (isMentioned) {
|
|
59225
|
-
deliveryReason = "mention";
|
|
59226
|
-
} else {
|
|
59227
|
-
let watching;
|
|
59228
|
-
try {
|
|
59229
|
-
watching = await this.opts.client.isWatchingThread(message.thread_root_id);
|
|
59230
|
-
} catch {
|
|
59231
|
-
return { action: "retry" };
|
|
59232
|
-
}
|
|
59233
|
-
if (!watching)
|
|
59234
|
-
return { action: "skip" };
|
|
59235
|
-
deliveryReason = "watcher";
|
|
59236
|
-
}
|
|
59237
|
-
} else if (chatInfo.type === "group") {
|
|
59238
|
-
if (chatInfo.agentRoutingMode !== "active" && !isMentioned)
|
|
59239
|
-
return { action: "skip" };
|
|
59240
|
-
if (isMentioned)
|
|
59241
|
-
deliveryReason = "mention";
|
|
59242
|
-
}
|
|
59243
|
-
const attachments = (message.attachments ?? []).map((a) => ({
|
|
59244
|
-
id: a.id,
|
|
59245
|
-
fileName: a.file_name,
|
|
59246
|
-
fileSize: a.file_size,
|
|
59247
|
-
mimeType: a.mime_type
|
|
59248
|
-
}));
|
|
59249
|
-
let unreadCount;
|
|
59250
|
-
let unreadSince;
|
|
59251
|
-
let threadReplyCount;
|
|
59252
|
-
let threadUnreadCount;
|
|
59253
|
-
let threadUnreadSince;
|
|
59254
|
-
const isPassiveOrSmart = chatInfo.type === "group" && chatInfo.agentRoutingMode !== "active";
|
|
59255
|
-
const unreadPromise = isPassiveOrSmart ? this.opts.client.getUnreadCounts(this.opts.config.org_id).catch(() => void 0) : Promise.resolve(void 0);
|
|
59256
|
-
const threadPromise = message.thread_root_id ? this.opts.client.getThreadUnread(this.opts.config.org_id, chatId, message.thread_root_id).catch(() => void 0) : Promise.resolve(void 0);
|
|
59257
|
-
const [counts, threadUnread] = await Promise.all([unreadPromise, threadPromise]);
|
|
59258
|
-
if (counts) {
|
|
59259
|
-
const entry = counts[chatId];
|
|
59260
|
-
if (entry && entry.count > 1) {
|
|
59261
|
-
unreadCount = entry.count;
|
|
59262
|
-
unreadSince = entry.since;
|
|
59263
|
-
}
|
|
59264
|
-
}
|
|
59265
|
-
if (threadUnread) {
|
|
59266
|
-
threadReplyCount = threadUnread.total;
|
|
59267
|
-
threadUnreadCount = threadUnread.unread > 0 ? threadUnread.unread : void 0;
|
|
59268
|
-
threadUnreadSince = threadUnread.since ?? void 0;
|
|
59269
|
-
}
|
|
59270
|
-
return {
|
|
59271
|
-
action: "dispatch",
|
|
59272
|
-
event: {
|
|
59273
|
-
type: "message",
|
|
59274
|
-
targetId: chatId,
|
|
59275
|
-
targetName: chatInfo.name ?? void 0,
|
|
59276
|
-
targetType: chatInfo.type,
|
|
59277
|
-
senderId: message.sender_id,
|
|
59278
|
-
senderName: message.sender?.display_name ?? message.sender_id,
|
|
59279
|
-
messageId: message.id,
|
|
59280
|
-
body: body || "[attachment]",
|
|
59281
|
-
threadRootId: message.thread_root_id ?? void 0,
|
|
59282
|
-
deliveryReason,
|
|
59283
|
-
noReply: message.hints?.no_reply ?? false,
|
|
59284
|
-
attachments: attachments.length > 0 ? attachments : void 0,
|
|
59285
|
-
sentAt: message.created_at,
|
|
59286
|
-
ackSourceType: "message",
|
|
59287
|
-
ackSourceId: message.id,
|
|
59288
|
-
unreadCount,
|
|
59289
|
-
unreadSince,
|
|
59290
|
-
threadReplyCount,
|
|
59291
|
-
threadUnreadCount,
|
|
59292
|
-
threadUnreadSince
|
|
59293
|
-
}
|
|
59294
|
-
};
|
|
59295
|
-
}
|
|
59296
|
-
async handleMessage(data) {
|
|
58932
|
+
/**
|
|
58933
|
+
* One WorkItem the server pushed (dispatch.new) or a catch-up page
|
|
58934
|
+
* listed: messages ride their (chat, thread) lane; every other family
|
|
58935
|
+
* rides its own dsp lane, claimed, run on the server frame, resolved by
|
|
58936
|
+
* id. A typed WorkItem whose event copy is already buffered for the
|
|
58937
|
+
* drain is left to the drain (re-claiming it would race the drain's
|
|
58938
|
+
* fence-less settlement).
|
|
58939
|
+
*/
|
|
58940
|
+
async consumeWorkItem(item) {
|
|
58941
|
+
await this.contractReady;
|
|
59297
58942
|
if (this.shuttingDown)
|
|
59298
58943
|
return;
|
|
59299
|
-
|
|
59300
|
-
|
|
59301
|
-
|
|
59302
|
-
|
|
59303
|
-
|
|
59304
|
-
|
|
59305
|
-
|
|
59306
|
-
|
|
59307
|
-
|
|
59308
|
-
|
|
58944
|
+
if (item.event_type === "message") {
|
|
58945
|
+
if (!item.chat_id || !item.source_id)
|
|
58946
|
+
return;
|
|
58947
|
+
await this.consumeMessageWorkItem({
|
|
58948
|
+
id: item.id,
|
|
58949
|
+
source_id: item.source_id,
|
|
58950
|
+
chat_id: item.chat_id,
|
|
58951
|
+
actor_id: item.actor_id,
|
|
58952
|
+
thread_root_id: item.thread_root_id,
|
|
58953
|
+
delivery_reason: item.delivery_reason
|
|
58954
|
+
});
|
|
59309
58955
|
return;
|
|
59310
58956
|
}
|
|
59311
|
-
|
|
59312
|
-
|
|
59313
|
-
const dispatched = await this.handleInboundEvent(event);
|
|
59314
|
-
if (dispatched) {
|
|
59315
|
-
if (!this.usesLaneLedger(event)) {
|
|
59316
|
-
this.opts.client.ackDispatch(this.opts.config.org_id, { source_type: "message", source_id: data.id }).catch(() => {
|
|
59317
|
-
});
|
|
59318
|
-
}
|
|
59319
|
-
} else {
|
|
59320
|
-
this.dispatchedMessages.delete(data.id);
|
|
59321
|
-
}
|
|
59322
|
-
} catch (err) {
|
|
59323
|
-
this.opts.log?.error(`event dispatch failed for ${data.id}: ${String(err)}`);
|
|
59324
|
-
this.dispatchedMessages.delete(data.id);
|
|
59325
|
-
}
|
|
59326
|
-
}
|
|
59327
|
-
// Ledger re-drive consumption: dispatch.new message hints re-enter the
|
|
59328
|
-
// shared WorkItem consumption path (same protocol as catch-up).
|
|
59329
|
-
async handleMessageRedrive(item) {
|
|
59330
|
-
if (!item.chat_id || !item.source_id)
|
|
58957
|
+
if (!TYPED_EVENT_KINDS[item.event_type]) {
|
|
58958
|
+
this.opts.log?.info(`dispatch with unhandled event_type=${String(item.event_type)} (id=${item.id}) \u2014 no-op`);
|
|
59331
58959
|
return;
|
|
59332
|
-
|
|
59333
|
-
|
|
59334
|
-
|
|
59335
|
-
chat_id: item.chat_id
|
|
59336
|
-
});
|
|
59337
|
-
}
|
|
59338
|
-
// A task assignment's first delivery rides task.assigned, but a typed lane
|
|
59339
|
-
// released without an effect is re-driven as dispatch.new. Reuse the exact
|
|
59340
|
-
// typed claim path used by catch-up so that recovery does not require a
|
|
59341
|
-
// runtime reconnect.
|
|
59342
|
-
async handleTaskAssignmentRedrive(item) {
|
|
59343
|
-
if (!item.task_id)
|
|
58960
|
+
}
|
|
58961
|
+
if (this.isBufferedTypedWorkItem(item.id)) {
|
|
58962
|
+
this.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping re-claim`);
|
|
59344
58963
|
return;
|
|
59345
|
-
|
|
59346
|
-
|
|
59347
|
-
}), {
|
|
59348
|
-
legacyAck: (dispatchEventId) => this.ackDispatchEvent(dispatchEventId ?? item.id, () => this.clearTypedDispatchDedupe(item)),
|
|
59349
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(item)
|
|
59350
|
-
});
|
|
58964
|
+
}
|
|
58965
|
+
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (lane) => this.runTypedFrame(item, lane), { legacyAck: () => this.ackDispatchEvent(item.id) });
|
|
59351
58966
|
}
|
|
59352
58967
|
consumeMessageWorkItem(item) {
|
|
59353
58968
|
return consumeMessageWorkItem(this.laneFlowHost(), item);
|
|
59354
58969
|
}
|
|
59355
|
-
async handleTaskAssignment(task, ackSourceId, dispatchEventId) {
|
|
59356
|
-
if (this.shuttingDown)
|
|
59357
|
-
return false;
|
|
59358
|
-
const dedupeKey = `${task.id}:${task.updated_at}`;
|
|
59359
|
-
if (this.dispatchedTasks.has(dedupeKey)) {
|
|
59360
|
-
this.opts.log?.info(`skipping already-dispatched task ${task.identifier ?? task.id}`);
|
|
59361
|
-
return false;
|
|
59362
|
-
}
|
|
59363
|
-
this.dispatchedTasks.add(dedupeKey);
|
|
59364
|
-
this.opts.log?.info(`task assigned: ${task.identifier ?? task.id} "${task.title}"`);
|
|
59365
|
-
const parts = [`Title: ${task.title}`];
|
|
59366
|
-
parts.push(`Status: ${task.status}`, `Priority: ${task.priority}`);
|
|
59367
|
-
if (task.project_id)
|
|
59368
|
-
parts.push(`Project: prll://${task.project_id}`);
|
|
59369
|
-
if (task.parent_id)
|
|
59370
|
-
parts.push(`Parent: prll://${task.parent_id}`);
|
|
59371
|
-
if (task.description)
|
|
59372
|
-
parts.push("", task.description);
|
|
59373
|
-
const event = {
|
|
59374
|
-
type: "task",
|
|
59375
|
-
targetId: task.id,
|
|
59376
|
-
targetName: task.identifier ?? void 0,
|
|
59377
|
-
targetType: "task",
|
|
59378
|
-
senderId: task.creator_id,
|
|
59379
|
-
senderName: "system",
|
|
59380
|
-
messageId: task.id,
|
|
59381
|
-
body: parts.join("\n"),
|
|
59382
|
-
sentAt: task.updated_at ?? task.created_at,
|
|
59383
|
-
ackSourceType: "task_activity",
|
|
59384
|
-
ackSourceId,
|
|
59385
|
-
dispatchEventId
|
|
59386
|
-
};
|
|
59387
|
-
const dispatched = await this.handleInboundEvent(event);
|
|
59388
|
-
if (!dispatched && !this.isTypedEventBuffered(event)) {
|
|
59389
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59390
|
-
}
|
|
59391
|
-
return dispatched;
|
|
59392
|
-
}
|
|
59393
|
-
async handleTaskDispatch(taskId, ackSourceId, opts = {}) {
|
|
59394
|
-
let task = null;
|
|
59395
|
-
try {
|
|
59396
|
-
task = await this.opts.client.getTask(this.opts.config.org_id, taskId);
|
|
59397
|
-
} catch (err) {
|
|
59398
|
-
const status = err?.status;
|
|
59399
|
-
if (status === 404)
|
|
59400
|
-
return true;
|
|
59401
|
-
throw err;
|
|
59402
|
-
}
|
|
59403
|
-
const isAssignee = task.assignee_id === this.opts.agentUserId;
|
|
59404
|
-
const isCreatorUpdate = opts.allowCreator === true && task.creator_id === this.opts.agentUserId;
|
|
59405
|
-
if (!isAssignee && !isCreatorUpdate) {
|
|
59406
|
-
this.opts.log?.info(`skipping stale task dispatch ${ackSourceId ?? taskId} \u2014 assigned to ${task.assignee_id}, creator ${task.creator_id}`);
|
|
59407
|
-
return true;
|
|
59408
|
-
}
|
|
59409
|
-
return this.handleTaskAssignment(task, ackSourceId, opts.dispatchEventId);
|
|
59410
|
-
}
|
|
59411
|
-
async handleTaskComment(commentId, taskId, actorId, deliveryReason, dispatchEventId) {
|
|
59412
|
-
if (this.shuttingDown)
|
|
59413
|
-
return false;
|
|
59414
|
-
const dedupeKey = `comment:${commentId}`;
|
|
59415
|
-
if (this.dispatchedTasks.has(dedupeKey))
|
|
59416
|
-
return false;
|
|
59417
|
-
this.dispatchedTasks.add(dedupeKey);
|
|
59418
|
-
let comment = null;
|
|
59419
|
-
try {
|
|
59420
|
-
comment = await this.opts.client.getComment(this.opts.config.org_id, commentId);
|
|
59421
|
-
} catch (err) {
|
|
59422
|
-
const status = err?.status;
|
|
59423
|
-
if (status === 404) {
|
|
59424
|
-
this.opts.log?.info(`skipping deleted comment ${commentId}, acking stale dispatch`);
|
|
59425
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59426
|
-
return true;
|
|
59427
|
-
}
|
|
59428
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59429
|
-
return false;
|
|
59430
|
-
}
|
|
59431
|
-
if (!comment) {
|
|
59432
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59433
|
-
return true;
|
|
59434
|
-
}
|
|
59435
|
-
if (comment.hints?.no_reply) {
|
|
59436
|
-
this.opts.log?.info(`skipping no_reply task comment ${commentId}, acking stale dispatch`);
|
|
59437
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59438
|
-
return true;
|
|
59439
|
-
}
|
|
59440
|
-
let task = null;
|
|
59441
|
-
try {
|
|
59442
|
-
task = await this.opts.client.getTask(this.opts.config.org_id, taskId);
|
|
59443
|
-
} catch {
|
|
59444
|
-
}
|
|
59445
|
-
const taskLabel = task ? `${task.identifier ?? task.id} "${task.title}"` : taskId;
|
|
59446
|
-
this.opts.log?.info(`task comment on ${taskLabel} by ${actorId ?? "unknown"}`);
|
|
59447
|
-
const parts = [];
|
|
59448
|
-
if (task) {
|
|
59449
|
-
parts.push(`Task: ${task.title} (prll://${task.id})`);
|
|
59450
|
-
parts.push(`Status: ${task.status}`, `Priority: ${task.priority}`);
|
|
59451
|
-
} else {
|
|
59452
|
-
parts.push(`Task: prll://${taskId}`);
|
|
59453
|
-
}
|
|
59454
|
-
parts.push(`Comment by: ${comment.author?.display_name ?? actorId ?? "unknown"} (prll://${comment.author_id})`);
|
|
59455
|
-
parts.push("", comment.body);
|
|
59456
|
-
const event = {
|
|
59457
|
-
type: "task_comment",
|
|
59458
|
-
targetId: taskId,
|
|
59459
|
-
targetName: task?.identifier ?? void 0,
|
|
59460
|
-
targetType: "task",
|
|
59461
|
-
senderId: comment.author_id,
|
|
59462
|
-
senderName: comment.author?.display_name ?? actorId ?? "unknown",
|
|
59463
|
-
messageId: commentId,
|
|
59464
|
-
body: parts.join("\n"),
|
|
59465
|
-
deliveryReason: deliveryReason ?? void 0,
|
|
59466
|
-
ackSourceType: "comment",
|
|
59467
|
-
ackSourceId: commentId,
|
|
59468
|
-
dispatchEventId
|
|
59469
|
-
};
|
|
59470
|
-
let dispatched;
|
|
59471
|
-
try {
|
|
59472
|
-
dispatched = await this.handleInboundEvent(event);
|
|
59473
|
-
} catch (err) {
|
|
59474
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59475
|
-
throw err;
|
|
59476
|
-
}
|
|
59477
|
-
if (!dispatched && !this.isTypedEventBuffered(event)) {
|
|
59478
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59479
|
-
}
|
|
59480
|
-
return dispatched;
|
|
59481
|
-
}
|
|
59482
|
-
async handleWikiComment(commentId, actorId, deliveryReason, dispatchEventId) {
|
|
59483
|
-
if (this.shuttingDown)
|
|
59484
|
-
return false;
|
|
59485
|
-
const dedupeKey = `comment:${commentId}`;
|
|
59486
|
-
if (this.dispatchedTasks.has(dedupeKey))
|
|
59487
|
-
return false;
|
|
59488
|
-
this.dispatchedTasks.add(dedupeKey);
|
|
59489
|
-
let comment = null;
|
|
59490
|
-
try {
|
|
59491
|
-
comment = await this.opts.client.getComment(this.opts.config.org_id, commentId);
|
|
59492
|
-
} catch (err) {
|
|
59493
|
-
const status = err?.status;
|
|
59494
|
-
if (status === 404 || status === 403) {
|
|
59495
|
-
this.opts.log?.info(`skipping inaccessible wiki comment ${commentId} (status ${status}), acking stale dispatch`);
|
|
59496
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59497
|
-
return true;
|
|
59498
|
-
}
|
|
59499
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59500
|
-
return false;
|
|
59501
|
-
}
|
|
59502
|
-
if (!comment) {
|
|
59503
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59504
|
-
return true;
|
|
59505
|
-
}
|
|
59506
|
-
if (comment.hints?.no_reply) {
|
|
59507
|
-
this.opts.log?.info(`skipping no_reply wiki comment ${commentId}, acking stale dispatch`);
|
|
59508
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59509
|
-
return true;
|
|
59510
|
-
}
|
|
59511
|
-
const target = parseWikiCommentTarget(comment.target_uri);
|
|
59512
|
-
this.opts.log?.info(`wiki comment on ${target.label} by ${actorId ?? "unknown"}`);
|
|
59513
|
-
const event = {
|
|
59514
|
-
type: "wiki_comment",
|
|
59515
|
-
// Full target_uri (scheme-stripped) is the routing key so different
|
|
59516
|
-
// pages / inline anchors / changesets in the same wiki don't collide on
|
|
59517
|
-
// one gateway lane. replyTargetUri keeps the canonical prll:// form.
|
|
59518
|
-
targetId: target.routingKey,
|
|
59519
|
-
targetName: target.label,
|
|
59520
|
-
targetType: target.targetType,
|
|
59521
|
-
senderId: comment.author_id,
|
|
59522
|
-
senderName: comment.author?.display_name ?? actorId ?? "unknown",
|
|
59523
|
-
messageId: commentId,
|
|
59524
|
-
body: comment.body,
|
|
59525
|
-
deliveryReason: deliveryReason ?? void 0,
|
|
59526
|
-
replyTargetUri: comment.target_uri,
|
|
59527
|
-
ackSourceType: "comment",
|
|
59528
|
-
ackSourceId: commentId,
|
|
59529
|
-
dispatchEventId
|
|
59530
|
-
};
|
|
59531
|
-
let dispatched;
|
|
59532
|
-
try {
|
|
59533
|
-
dispatched = await this.handleInboundEvent(event);
|
|
59534
|
-
} catch (err) {
|
|
59535
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59536
|
-
throw err;
|
|
59537
|
-
}
|
|
59538
|
-
if (!dispatched && !this.isTypedEventBuffered(event)) {
|
|
59539
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59540
|
-
}
|
|
59541
|
-
return dispatched;
|
|
59542
|
-
}
|
|
59543
58970
|
/**
|
|
59544
|
-
*
|
|
59545
|
-
*
|
|
59546
|
-
*
|
|
59547
|
-
*
|
|
59548
|
-
*
|
|
59549
|
-
* or retry forever in that case.
|
|
58971
|
+
* Run one claimed typed WorkItem on the frame the claim returned. The
|
|
58972
|
+
* event is addressing only: the routing target the server named
|
|
58973
|
+
* (`input.subject` — the task, the wiki target, the schedule, the
|
|
58974
|
+
* conversation, the chat an approval belongs to), the ids the ledger
|
|
58975
|
+
* keys on, and the input-step metadata. No frame means nothing to run.
|
|
59550
58976
|
*/
|
|
59551
|
-
async
|
|
59552
|
-
let run = null;
|
|
59553
|
-
try {
|
|
59554
|
-
run = await this.opts.client.getScheduleRun(this.opts.config.org_id, runId);
|
|
59555
|
-
} catch (err) {
|
|
59556
|
-
const status = err?.status;
|
|
59557
|
-
if (status === 404) {
|
|
59558
|
-
this.opts.log?.warn(`schedule run ${runId} not accessible (404), acking stale dispatch`);
|
|
59559
|
-
return true;
|
|
59560
|
-
}
|
|
59561
|
-
this.opts.log?.warn(`schedule run fetch failed for ${runId}, leaving pending: ${String(err)}`);
|
|
59562
|
-
return false;
|
|
59563
|
-
}
|
|
59564
|
-
if (!run)
|
|
59565
|
-
return true;
|
|
59566
|
-
return this.handleScheduleFire(run, actorId, dispatchEventId);
|
|
59567
|
-
}
|
|
59568
|
-
async handleScheduleFire(run, actorId, dispatchEventId) {
|
|
58977
|
+
async runTypedFrame(item, lane) {
|
|
59569
58978
|
if (this.shuttingDown)
|
|
59570
58979
|
return false;
|
|
59571
|
-
const
|
|
59572
|
-
if (
|
|
58980
|
+
const wake = this.laneLedger?.takeFrame(lane);
|
|
58981
|
+
if (!wake?.frame) {
|
|
58982
|
+
this.opts.log?.warn(`typed dispatch ${item.id} (${String(item.event_type)}) claimed without a frame \u2014 leaving it pending`);
|
|
59573
58983
|
return false;
|
|
59574
|
-
this.dispatchedTasks.add(dedupeKey);
|
|
59575
|
-
this.opts.log?.info(`schedule fired: ${run.id} (schedule ${run.schedule_id})`);
|
|
59576
|
-
const event = {
|
|
59577
|
-
type: "schedule",
|
|
59578
|
-
// Route by schedule_id (not attached chat_id) so concurrent fires of
|
|
59579
|
-
// different schedules can fork independently — matches the PR1 primitive
|
|
59580
|
-
// design where "schedule triggers; target decides response" and fire
|
|
59581
|
-
// semantics are independent of any attached conversation.
|
|
59582
|
-
targetId: run.schedule_id,
|
|
59583
|
-
targetType: "schedule",
|
|
59584
|
-
senderId: actorId ?? "system",
|
|
59585
|
-
senderName: "schedule",
|
|
59586
|
-
messageId: run.id,
|
|
59587
|
-
body: run.fired_description ?? "",
|
|
59588
|
-
scheduledFireAt: run.scheduled_fire_at,
|
|
59589
|
-
attachedUri: run.fired_attached_uri ?? void 0,
|
|
59590
|
-
ackSourceType: "schedule_run",
|
|
59591
|
-
ackSourceId: run.id,
|
|
59592
|
-
dispatchEventId
|
|
59593
|
-
};
|
|
59594
|
-
let dispatched;
|
|
59595
|
-
try {
|
|
59596
|
-
dispatched = await this.handleInboundEvent(event);
|
|
59597
|
-
} catch (err) {
|
|
59598
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59599
|
-
throw err;
|
|
59600
58984
|
}
|
|
59601
|
-
|
|
59602
|
-
|
|
59603
|
-
}
|
|
59604
|
-
return dispatched;
|
|
59605
|
-
}
|
|
59606
|
-
async fetchAndHandleExternalTriggerRun(runId, dispatchEventId) {
|
|
59607
|
-
let run = null;
|
|
59608
|
-
try {
|
|
59609
|
-
run = await this.opts.client.getExternalTriggerRun(this.opts.config.org_id, runId);
|
|
59610
|
-
} catch (err) {
|
|
59611
|
-
const status = err?.status;
|
|
59612
|
-
if (status === 404) {
|
|
59613
|
-
this.opts.log?.warn(`external trigger run ${runId} not accessible (404), acking stale dispatch`);
|
|
59614
|
-
return true;
|
|
59615
|
-
}
|
|
59616
|
-
this.opts.log?.warn(`external trigger run fetch failed for ${runId}, leaving pending: ${String(err)}`);
|
|
59617
|
-
return false;
|
|
59618
|
-
}
|
|
59619
|
-
if (!run)
|
|
59620
|
-
return true;
|
|
59621
|
-
return this.handleExternalTriggerRun(run, dispatchEventId);
|
|
59622
|
-
}
|
|
59623
|
-
// fetchAndHandleChannelMessage resolves a channel_message dispatch to its
|
|
59624
|
-
// durable ChannelMessage + conversation and hands it to the inbound
|
|
59625
|
-
// pipeline. targetId = the ChannelConversation id, so per-conversation
|
|
59626
|
-
// multi-turn continuity rides the same per-target session mechanics as
|
|
59627
|
-
// chats. Design: docs/engineering-design/external-im-channel-design.md.
|
|
59628
|
-
async fetchAndHandleChannelMessage(messageId, dispatchEventId) {
|
|
59629
|
-
if (this.shuttingDown)
|
|
59630
|
-
return false;
|
|
59631
|
-
const claimKey = `channel_message:${messageId}`;
|
|
59632
|
-
if (!this.tryClaimMessage(claimKey))
|
|
59633
|
-
return false;
|
|
59634
|
-
let msg = null;
|
|
59635
|
-
let conv = null;
|
|
59636
|
-
try {
|
|
59637
|
-
msg = await this.opts.client.getChannelMessage(this.opts.config.org_id, messageId);
|
|
59638
|
-
conv = await this.opts.client.getChannelConversation(this.opts.config.org_id, msg.conversation_id);
|
|
59639
|
-
} catch (err) {
|
|
59640
|
-
const status = err?.status;
|
|
59641
|
-
if (status === 404) {
|
|
59642
|
-
this.opts.log?.warn(`channel message ${messageId} not accessible (404), acking stale dispatch`);
|
|
59643
|
-
return true;
|
|
59644
|
-
}
|
|
59645
|
-
this.dispatchedMessages.delete(claimKey);
|
|
59646
|
-
this.opts.log?.warn(`channel message fetch failed for ${messageId}, leaving pending: ${String(err)}`);
|
|
59647
|
-
return false;
|
|
59648
|
-
}
|
|
59649
|
-
if (!msg || !conv) {
|
|
59650
|
-
return true;
|
|
59651
|
-
}
|
|
59652
|
-
this.opts.log?.info(`channel message: ${msg.id} (conversation ${conv.id})`);
|
|
59653
|
-
let provider = this.channelConnectionProviders.get(conv.connection_id);
|
|
59654
|
-
if (!provider) {
|
|
59655
|
-
try {
|
|
59656
|
-
const connection = await this.opts.client.getChannelConnection(this.opts.config.org_id, conv.connection_id);
|
|
59657
|
-
provider = connection.provider;
|
|
59658
|
-
this.channelConnectionProviders.set(conv.connection_id, provider);
|
|
59659
|
-
} catch {
|
|
59660
|
-
provider = void 0;
|
|
59661
|
-
}
|
|
59662
|
-
}
|
|
59663
|
-
const keys = this.opts.getCapabilityKeys?.() ?? [];
|
|
59664
|
-
const cliCapable = provider ? keys.includes(channelCapabilityKeyFor(provider)) : keys.some((k) => k.endsWith("-cli") || k === CAPABILITY_SLACK_SEND || k === CAPABILITY_WECHAT_SEND);
|
|
59665
|
-
const event = {
|
|
59666
|
-
type: "channel_message",
|
|
59667
|
-
targetId: conv.id,
|
|
59668
|
-
targetName: conv.external_conversation_name || conv.external_user_name || conv.external_conversation_id,
|
|
59669
|
-
targetType: "channel_conversation",
|
|
59670
|
-
senderId: msg.external_user_id || "external",
|
|
59671
|
-
senderName: msg.external_user_name || msg.external_user_id || "external user",
|
|
59672
|
-
messageId: msg.id,
|
|
59673
|
-
body: msg.text,
|
|
59674
|
-
sentAt: msg.received_at,
|
|
59675
|
-
channelProvider: provider,
|
|
59676
|
-
channelConversationType: conv.conversation_type || void 0,
|
|
59677
|
-
channelExternalConversationId: conv.external_conversation_id,
|
|
59678
|
-
channelExternalConversationName: conv.external_conversation_name || void 0,
|
|
59679
|
-
channelExternalMessageId: msg.external_message_id,
|
|
59680
|
-
channelCliCapable: cliCapable,
|
|
59681
|
-
ackSourceType: "channel_message",
|
|
59682
|
-
ackSourceId: msg.id,
|
|
59683
|
-
dispatchEventId
|
|
59684
|
-
};
|
|
59685
|
-
let dispatched;
|
|
59686
|
-
try {
|
|
59687
|
-
dispatched = await this.handleInboundEvent(event);
|
|
59688
|
-
} catch (err) {
|
|
59689
|
-
this.dispatchedMessages.delete(claimKey);
|
|
59690
|
-
throw err;
|
|
59691
|
-
}
|
|
59692
|
-
if (!dispatched && !this.isTypedEventBuffered(event)) {
|
|
59693
|
-
this.dispatchedMessages.delete(claimKey);
|
|
59694
|
-
}
|
|
59695
|
-
return dispatched;
|
|
59696
|
-
}
|
|
59697
|
-
async handleExternalTriggerRun(run, dispatchEventId) {
|
|
59698
|
-
if (this.shuttingDown)
|
|
59699
|
-
return false;
|
|
59700
|
-
const dedupeKey = `external_trigger_run:${run.id}`;
|
|
59701
|
-
if (this.dispatchedTasks.has(dedupeKey))
|
|
59702
|
-
return false;
|
|
59703
|
-
this.dispatchedTasks.add(dedupeKey);
|
|
59704
|
-
this.opts.log?.info(`external trigger fired: ${run.id} (trigger ${run.trigger_id})`);
|
|
59705
|
-
const attachedUri = typeof run.trigger_snapshot?.attached_to_uri === "string" ? run.trigger_snapshot.attached_to_uri : void 0;
|
|
58985
|
+
const kind = TYPED_EVENT_KINDS[item.event_type];
|
|
58986
|
+
const targetId = wake.input?.subject || item.task_id || item.chat_id || item.source_id || item.id;
|
|
59706
58987
|
const event = {
|
|
59707
|
-
type:
|
|
59708
|
-
targetId
|
|
59709
|
-
|
|
59710
|
-
|
|
59711
|
-
|
|
59712
|
-
|
|
59713
|
-
|
|
59714
|
-
|
|
59715
|
-
|
|
59716
|
-
|
|
59717
|
-
|
|
59718
|
-
|
|
59719
|
-
|
|
59720
|
-
attachedUri,
|
|
59721
|
-
ackSourceType: "external_trigger_run",
|
|
59722
|
-
ackSourceId: run.id,
|
|
59723
|
-
dispatchEventId
|
|
59724
|
-
};
|
|
59725
|
-
let dispatched;
|
|
59726
|
-
try {
|
|
59727
|
-
dispatched = await this.handleInboundEvent(event);
|
|
59728
|
-
} catch (err) {
|
|
59729
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59730
|
-
throw err;
|
|
59731
|
-
}
|
|
59732
|
-
if (!dispatched && !this.isTypedEventBuffered(event)) {
|
|
59733
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59734
|
-
}
|
|
59735
|
-
return dispatched;
|
|
59736
|
-
}
|
|
59737
|
-
async fetchAndHandleApprovalDecided(approvalId, actorId, chatId, dispatchEventId) {
|
|
59738
|
-
let approval = null;
|
|
59739
|
-
try {
|
|
59740
|
-
approval = await this.opts.client.getApproval(approvalId);
|
|
59741
|
-
} catch (err) {
|
|
59742
|
-
const status = err?.status;
|
|
59743
|
-
if (status === 404 || status === 403) {
|
|
59744
|
-
this.opts.log?.warn(`approval ${approvalId} not accessible (${status}), acking stale dispatch`);
|
|
59745
|
-
return true;
|
|
59746
|
-
}
|
|
59747
|
-
this.opts.log?.warn(`approval fetch failed for ${approvalId}, leaving pending: ${String(err)}`);
|
|
59748
|
-
return false;
|
|
59749
|
-
}
|
|
59750
|
-
if (!approval)
|
|
59751
|
-
return true;
|
|
59752
|
-
if (this.shuttingDown)
|
|
59753
|
-
return false;
|
|
59754
|
-
const dedupeKey = `approval:${approval.id}`;
|
|
59755
|
-
if (this.dispatchedTasks.has(dedupeKey))
|
|
59756
|
-
return false;
|
|
59757
|
-
this.dispatchedTasks.add(dedupeKey);
|
|
59758
|
-
this.opts.log?.info(`approval decided: ${approval.id} (${approval.status})`);
|
|
59759
|
-
const statusLabel = approval.status === "approved" ? "Approved" : "Rejected";
|
|
59760
|
-
const execInfo = approval.execution_status ? ` | execution: ${approval.execution_status}` : "";
|
|
59761
|
-
const reasonLine = formatApprovalDecisionReason(approval.status, approval.decision_reason);
|
|
59762
|
-
const reasonInfo = reasonLine ? `
|
|
59763
|
-
${reasonLine}` : "";
|
|
59764
|
-
const body = `${statusLabel}: ${approval.title}${execInfo}${reasonInfo}`;
|
|
59765
|
-
const event = {
|
|
59766
|
-
type: "approval",
|
|
59767
|
-
targetId: chatId ?? approval.chat_id,
|
|
59768
|
-
senderId: actorId ?? approval.decided_by ?? "system",
|
|
59769
|
-
senderName: "approver",
|
|
59770
|
-
messageId: approval.id,
|
|
59771
|
-
body,
|
|
59772
|
-
// The WorkItem's real source pair. Without it the legacy fallback
|
|
59773
|
-
// guessed ('message', approval_id) — a pair no row matches.
|
|
59774
|
-
ackSourceType: "approval",
|
|
59775
|
-
ackSourceId: approval.id,
|
|
59776
|
-
dispatchEventId
|
|
59777
|
-
};
|
|
59778
|
-
let dispatched;
|
|
59779
|
-
try {
|
|
59780
|
-
dispatched = await this.handleInboundEvent(event);
|
|
59781
|
-
} catch (err) {
|
|
59782
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59783
|
-
throw err;
|
|
59784
|
-
}
|
|
59785
|
-
if (!dispatched && !this.isTypedEventBuffered(event)) {
|
|
59786
|
-
this.dispatchedTasks.delete(dedupeKey);
|
|
59787
|
-
}
|
|
59788
|
-
return dispatched;
|
|
58988
|
+
type: kind.type,
|
|
58989
|
+
targetId,
|
|
58990
|
+
targetType: wake.input?.step_target?.type,
|
|
58991
|
+
senderId: wake.input?.sender_id ?? item.actor_id ?? "system",
|
|
58992
|
+
messageId: item.source_id,
|
|
58993
|
+
deliveryReason: item.delivery_reason ?? void 0,
|
|
58994
|
+
ackSourceType: kind.ackSourceType,
|
|
58995
|
+
ackSourceId: item.source_id,
|
|
58996
|
+
dispatchEventId: item.id
|
|
58997
|
+
};
|
|
58998
|
+
applyWake(event, wake);
|
|
58999
|
+
this.opts.log?.info(`${String(item.event_type)} ${item.source_id} \u2192 ${targetId}`);
|
|
59000
|
+
return this.handleInboundEvent(event);
|
|
59789
59001
|
}
|
|
59790
59002
|
async catchUpFromDispatch() {
|
|
59791
59003
|
const OVERFLOW_THRESHOLD = 500;
|
|
@@ -59839,54 +59051,9 @@ ${reasonLine}` : "";
|
|
|
59839
59051
|
}
|
|
59840
59052
|
continue;
|
|
59841
59053
|
}
|
|
59842
|
-
if (item.event_type !== "message" && this.isBufferedTypedWorkItem(item.id)) {
|
|
59843
|
-
this.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping catch-up claim`);
|
|
59844
|
-
continue;
|
|
59845
|
-
}
|
|
59846
59054
|
processed++;
|
|
59847
59055
|
try {
|
|
59848
|
-
|
|
59849
|
-
legacyAck: () => this.ackDispatchEvent(item.id, () => this.clearTypedDispatchDedupe(item)),
|
|
59850
|
-
clearDedupe: () => this.clearTypedDispatchDedupe(item)
|
|
59851
|
-
};
|
|
59852
|
-
if (item.event_type === "task_assign" && item.task_id) {
|
|
59853
|
-
try {
|
|
59854
|
-
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
|
|
59855
|
-
dispatchEventId
|
|
59856
|
-
}), typedHooks);
|
|
59857
|
-
} catch (err) {
|
|
59858
|
-
this.opts.log?.warn(`catch-up task fetch failed for ${item.task_id}, leaving pending: ${String(err)}`);
|
|
59859
|
-
continue;
|
|
59860
|
-
}
|
|
59861
|
-
} else if (item.event_type === "task_update" && item.task_id) {
|
|
59862
|
-
try {
|
|
59863
|
-
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
|
|
59864
|
-
allowCreator: true,
|
|
59865
|
-
dispatchEventId
|
|
59866
|
-
}), typedHooks);
|
|
59867
|
-
} catch (err) {
|
|
59868
|
-
this.opts.log?.warn(`catch-up task fetch failed for ${item.task_id}, leaving pending: ${String(err)}`);
|
|
59869
|
-
continue;
|
|
59870
|
-
}
|
|
59871
|
-
} else if (item.event_type === "task_comment" && item.source_id && item.task_id) {
|
|
59872
|
-
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskComment(item.source_id, item.task_id ?? "", item.actor_id, item.delivery_reason, dispatchEventId), typedHooks);
|
|
59873
|
-
} else if (item.event_type === "wiki_comment" && item.source_id) {
|
|
59874
|
-
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleWikiComment(item.source_id, item.actor_id, item.delivery_reason, dispatchEventId), typedHooks);
|
|
59875
|
-
} else if (item.event_type === "schedule.fire" && item.source_id) {
|
|
59876
|
-
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleScheduleFire(item.source_id, item.actor_id, dispatchEventId), typedHooks);
|
|
59877
|
-
} else if (item.event_type === "external_trigger" && item.source_id) {
|
|
59878
|
-
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleExternalTriggerRun(item.source_id, dispatchEventId), typedHooks);
|
|
59879
|
-
} else if (item.event_type === "channel_message" && item.source_id) {
|
|
59880
|
-
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleChannelMessage(item.source_id, dispatchEventId), typedHooks);
|
|
59881
|
-
} else if (item.event_type === "approval_decided" && item.source_id) {
|
|
59882
|
-
await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleApprovalDecided(item.source_id, item.actor_id, item.chat_id ?? null, dispatchEventId), typedHooks);
|
|
59883
|
-
} else if (item.event_type === "message" && item.source_id && item.chat_id) {
|
|
59884
|
-
await this.consumeMessageWorkItem({
|
|
59885
|
-
id: item.id,
|
|
59886
|
-
source_id: item.source_id,
|
|
59887
|
-
chat_id: item.chat_id
|
|
59888
|
-
});
|
|
59889
|
-
}
|
|
59056
|
+
await this.consumeWorkItem(item);
|
|
59890
59057
|
} catch (err) {
|
|
59891
59058
|
this.opts.log?.warn(`catch-up dispatch ${item.id} (${item.event_type}) failed: ${String(err)}`);
|
|
59892
59059
|
}
|
|
@@ -59959,9 +59126,18 @@ ${fullSummary}` : fullSummary;
|
|
|
59959
59126
|
this.ledgerDisabled = false;
|
|
59960
59127
|
}
|
|
59961
59128
|
const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
|
|
59129
|
+
let openFence = () => {
|
|
59130
|
+
};
|
|
59131
|
+
this.contractReady = new Promise((resolve3) => {
|
|
59132
|
+
openFence = resolve3;
|
|
59133
|
+
});
|
|
59962
59134
|
try {
|
|
59963
|
-
|
|
59964
|
-
|
|
59135
|
+
log?.info("WebSocket connected");
|
|
59136
|
+
try {
|
|
59137
|
+
await this.declareRuntimeContract();
|
|
59138
|
+
} finally {
|
|
59139
|
+
openFence();
|
|
59140
|
+
}
|
|
59965
59141
|
await this.opts.onSessionReady?.({
|
|
59966
59142
|
activeSessionId: this.activeSessionId,
|
|
59967
59143
|
ws: this.opts.ws,
|
|
@@ -59995,6 +59171,44 @@ ${fullSummary}` : fullSummary;
|
|
|
59995
59171
|
log?.error(`failed to fetch chats: ${String(err)}`);
|
|
59996
59172
|
}
|
|
59997
59173
|
}
|
|
59174
|
+
/**
|
|
59175
|
+
* Declare the runtime contract for this connection: the server decides
|
|
59176
|
+
* who runs and renders the wake frame; this runtime only runs. Bound to
|
|
59177
|
+
* the WS session id, so it repeats on every hello. Retried with backoff
|
|
59178
|
+
* until it lands — WorkItems wait behind the fence meanwhile, nothing is
|
|
59179
|
+
* claimed without a frame. A server without the endpoint renders no
|
|
59180
|
+
* frames: the runtime runs nothing and WorkItems stay pending. A
|
|
59181
|
+
* stale-session 409 means a newer connection already declared.
|
|
59182
|
+
*/
|
|
59183
|
+
async declareRuntimeContract() {
|
|
59184
|
+
const session = this.sessionId;
|
|
59185
|
+
if (!session)
|
|
59186
|
+
return;
|
|
59187
|
+
for (let attempt = 0; ; attempt++) {
|
|
59188
|
+
try {
|
|
59189
|
+
await this.opts.client.declareReplyPolicyCapability(this.opts.config.org_id, session);
|
|
59190
|
+
this.opts.log?.info("runtime contract declared (server-rendered frames)");
|
|
59191
|
+
return;
|
|
59192
|
+
} catch (err) {
|
|
59193
|
+
if (err instanceof ApiError && err.status === 404) {
|
|
59194
|
+
this.opts.log?.warn("server predates the runtime contract \u2014 it renders no wake frames; WorkItems stay pending");
|
|
59195
|
+
return;
|
|
59196
|
+
}
|
|
59197
|
+
if (err instanceof ApiError && err.status === 409) {
|
|
59198
|
+
this.opts.log?.info("runtime contract already declared by a newer connection");
|
|
59199
|
+
return;
|
|
59200
|
+
}
|
|
59201
|
+
const delayMs = Math.min(3e4, 2e3 * 2 ** Math.min(attempt, 4));
|
|
59202
|
+
this.opts.log?.warn(`runtime contract declaration failed (retry in ${delayMs / 1e3}s): ${String(err)}`);
|
|
59203
|
+
await new Promise((resolve3) => {
|
|
59204
|
+
const timer = setTimeout(resolve3, delayMs);
|
|
59205
|
+
timer.unref?.();
|
|
59206
|
+
});
|
|
59207
|
+
if (this.shuttingDown || this.sessionId !== session)
|
|
59208
|
+
return;
|
|
59209
|
+
}
|
|
59210
|
+
}
|
|
59211
|
+
}
|
|
59998
59212
|
// Resolves when in-flight dispatches hit 0 or the deadline elapses.
|
|
59999
59213
|
// Deadline arming the resolver rather than rejecting keeps shutdown() linear
|
|
60000
59214
|
// — callers don't need to try/catch.
|
|
@@ -61457,11 +60671,12 @@ async function getAgentMeWithLegacyFallback(client, orgId) {
|
|
|
61457
60671
|
}
|
|
61458
60672
|
function buildInboundCtx(core, accountId, event, sessionKey, bodyForAgent, earlierEvents = []) {
|
|
61459
60673
|
const inboundHistory = earlierEvents.length > 0 ? buildInboundHistory(earlierEvents) : void 0;
|
|
60674
|
+
const body = event.frame ?? "";
|
|
61460
60675
|
return core.channel.reply.finalizeInboundContext({
|
|
61461
|
-
Body:
|
|
60676
|
+
Body: body,
|
|
61462
60677
|
BodyForAgent: bodyForAgent,
|
|
61463
|
-
RawBody:
|
|
61464
|
-
CommandBody:
|
|
60678
|
+
RawBody: body,
|
|
60679
|
+
CommandBody: body,
|
|
61465
60680
|
// Attachment metadata is now in event.attachments (structured), not mediaFields
|
|
61466
60681
|
...inboundHistory?.length ? { InboundHistory: inboundHistory } : {},
|
|
61467
60682
|
From: `parall:${event.senderId}`,
|
|
@@ -61469,7 +60684,7 @@ function buildInboundCtx(core, accountId, event, sessionKey, bodyForAgent, earli
|
|
|
61469
60684
|
SessionKey: sessionKey,
|
|
61470
60685
|
AccountId: accountId,
|
|
61471
60686
|
ChatType: event.targetType ?? "unknown",
|
|
61472
|
-
SenderName: event.
|
|
60687
|
+
SenderName: event.senderId,
|
|
61473
60688
|
SenderId: event.senderId,
|
|
61474
60689
|
Provider: "parall",
|
|
61475
60690
|
Surface: "parall",
|
|
@@ -61481,25 +60696,7 @@ function buildInboundCtx(core, accountId, event, sessionKey, bodyForAgent, earli
|
|
|
61481
60696
|
});
|
|
61482
60697
|
}
|
|
61483
60698
|
function buildInboundHistory(events) {
|
|
61484
|
-
return events.map((event) => {
|
|
61485
|
-
const meta2 = [];
|
|
61486
|
-
meta2.push(`[Message ID: ${event.messageId}]`);
|
|
61487
|
-
if (event.noReply)
|
|
61488
|
-
meta2.push(`[Hint: no_reply]`);
|
|
61489
|
-
if (event.threadRootId)
|
|
61490
|
-
meta2.push(`[Thread: ${event.threadRootId}]`);
|
|
61491
|
-
if (event.attachments?.length) {
|
|
61492
|
-
for (const att of event.attachments) {
|
|
61493
|
-
const safeMime = att.mimeType.replace(/[\r\n[\]|]/g, " ").trim();
|
|
61494
|
-
meta2.push(`[Attachment: prll://${att.id} | ${safeMime}]`);
|
|
61495
|
-
}
|
|
61496
|
-
}
|
|
61497
|
-
return {
|
|
61498
|
-
sender: event.senderName,
|
|
61499
|
-
body: meta2.length > 0 ? `${meta2.join(" ")}
|
|
61500
|
-
${event.body}` : event.body
|
|
61501
|
-
};
|
|
61502
|
-
});
|
|
60699
|
+
return events.map((event) => ({ sender: event.senderId, body: event.frame ?? "" }));
|
|
61503
60700
|
}
|
|
61504
60701
|
var OC_AUTH_TEXT = /unauthorized|401|403|invalid api key|authentication/i;
|
|
61505
60702
|
var OC_CONTEXT_TEXT = /context (window|length)|prompt is too long|request too large|413/i;
|