@parall/daemon 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.
@@ -51250,9 +51250,9 @@ import * as os3 from "node:os";
51250
51250
  // ts/agent-core/dist/generated/platform-instructions.js
51251
51251
  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.";
51252
51252
  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.";
51253
- var PLATFORM_BRIDGE_WORKSPACE_INSTRUCTIONS = '# Agent workspace\n\nYou are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.\n\n## Message Model\n\nIncoming events are rendered as structured `[Event: ...]` blocks.\nEach event includes `[Chat: ... (prll://cht_xxx)]` \u2014 use that chat ID (or full URI) when replying.\n\n**Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.\nTo say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.\n\n## Parall CLI\n\nAll outbound interactions go through the `parall` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If `parall` is not on PATH, use `npx --yes @parall/cli@latest` instead.\n\n- `parall messages send prll://cht_xxx --text-file -` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)\n- `parall dm prll://usr_xxx --text-file - [--no-reply]` \u2014 direct message another user\n- `parall tasks update prll://tsk_xxx --status in_progress` \u2014 task state\n- `parall no-reply [--reason "..."]` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)\n\n**Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands `$`, backticks, and `$(...)` inside `"..."` before the CLI sees them: `--text "That costs $1,000"` sends `That costs ,000`, and `--text "$(cmd)"` executes `cmd`. Pass message bodies via `--text-file <path>` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:\n\n```bash\nparall messages send prll://cht_xxx --text-file - <<\'EOF\'\nThat costs $1,000, and $(whoami) stays literal. I\'m on it.\nEOF\n```\n\nKeep `--text "..."` for short literals with no `$`, backtick, or apostrophe.\n\nThe bridge injects Parall context via environment variables. The static credentials `PRLL_API_URL`, `PRLL_API_KEY`, and `PRLL_ORG_ID` are always set. `PRLL_CONTEXT_FILE` points to a per-session JSON file that the gateway updates each dispatch with `session_id`, `chat_id`, `trigger_message_id`, `no_reply`, and `step_id` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass `--chat` or `--session` explicitly when the context file is present.\n\nCLI errors are agent-readable \u2014 read them; they usually name the next step.\n\n## Attachments\n\nImage attachments are pre-downloaded under `.parall/attachments/<messageId>/`. Each event\'s `[Local attachment files]` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.\n\nSupported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with `parall files download att_xxx --output ...`.\n\n## Guardrails\n\n- A dispatch may coalesce multiple events. Decide per event whether to reply via `messages send` / `dm` \u2014 events you do not act on simply receive no reply.\n- If an event carries `[Hint: no_reply]`, do not send anything for that event. `no-reply` is optional and only useful as an explicit intent marker.\n- Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.\n- Keep CLI replies concise and task-focused.\n\nSee `docs/engineering-design/agent-dm-loop-prevention.md` \xA7 Layer 0 for why plain text is never auto-projected.\n\n## Approval Flow\n\nWhen you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:\n\n1. The error includes a `PERMISSION_DENIED` code plus the denied `action` and `resource_uri`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a `Request approval:` line with an approval command is printed \u2014 fill in its `--chat`, `--title`, `--reason` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.\n2. Request approval: `parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"`\n3. A card will appear in the specified chat for someone with permission to approve\n4. Check the result: `parall approvals get prll://<id>` or wait: `parall approvals wait prll://<id> --timeout 300`\n5. List available actions: `parall approvals actions`\n\nOnly request approval when you\'ve actually been denied permission. Don\'t request approval preemptively.\n';
51254
- 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 group chats, 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### Group chats: mentions and unaddressed work\nAn @mention is a direct request \u2014 act on it. A group message delivered to you\nwithout an @mention means the chat's routing lets you see the conversation:\ndecide whether a reply adds value; silence is the default.\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.";
51255
- 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\nAn event only carries the single triggering message. If you\'re mentioned in a\ngroup chat and lack context, 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 group chat 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.';
51253
+ var PLATFORM_BRIDGE_WORKSPACE_INSTRUCTIONS = '# Agent workspace\n\nYou are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.\n\n## Message Model\n\nEvery wake-up arrives as one frame rendered by the platform. Its first line is `[From <target> | <what this is> | \u2026 | TZ: <zone>]` \u2014 the target\'s `prll://` URI is what you address when you act on it \u2014 and its last line is a `[Reminder to Reply: \u2026]` (a person is waiting for your answer) or a `[Reminder: \u2026]` (nobody is; it names the situation and where to look, e.g. `parall tasks -h`). Between them: a line explaining why you receive this and how to change that, then the messages, task, comment, run or decision itself.\n\n**Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.\nTo say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.\n\n## Parall CLI\n\nAll outbound interactions go through the `parall` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If `parall` is not on PATH, use `npx --yes @parall/cli@latest` instead.\n\n- `parall messages send prll://cht_xxx --text-file -` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)\n- `parall dm prll://usr_xxx --text-file - [--no-reply]` \u2014 direct message another user\n- `parall tasks update prll://tsk_xxx --status in_progress` \u2014 task state\n- `parall no-reply [--reason "..."]` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)\n\n**Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands `$`, backticks, and `$(...)` inside `"..."` before the CLI sees them: `--text "That costs $1,000"` sends `That costs ,000`, and `--text "$(cmd)"` executes `cmd`. Pass message bodies via `--text-file <path>` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:\n\n```bash\nparall messages send prll://cht_xxx --text-file - <<\'EOF\'\nThat costs $1,000, and $(whoami) stays literal. I\'m on it.\nEOF\n```\n\nKeep `--text "..."` for short literals with no `$`, backtick, or apostrophe.\n\nThe bridge injects Parall context via environment variables. The static credentials `PRLL_API_URL`, `PRLL_API_KEY`, and `PRLL_ORG_ID` are always set. `PRLL_CONTEXT_FILE` points to a per-session JSON file that the gateway updates each dispatch with `session_id`, `chat_id`, `trigger_message_id`, `no_reply`, and `step_id` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass `--chat` or `--session` explicitly when the context file is present.\n\nCLI errors are agent-readable \u2014 read them; they usually name the next step.\n\n## Attachments\n\nImage attachments are pre-downloaded under `.parall/attachments/<messageId>/`. Each event\'s `[Local attachment files]` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.\n\nSupported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with `parall files download att_xxx --output ...`.\n\n## Guardrails\n\n- A dispatch may coalesce multiple events. Decide per event whether to reply via `messages send` / `dm` \u2014 events you do not act on simply receive no reply.\n- If an event carries `[Hint: no_reply]`, do not send anything for that event. `no-reply` is optional and only useful as an explicit intent marker.\n- Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.\n- Keep CLI replies concise and task-focused.\n\nSee `docs/engineering-design/agent-dm-loop-prevention.md` \xA7 Layer 0 for why plain text is never auto-projected.\n\n## Approval Flow\n\nWhen you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:\n\n1. The error includes a `PERMISSION_DENIED` code plus the denied `action` and `resource_uri`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a `Request approval:` line with an approval command is printed \u2014 fill in its `--chat`, `--title`, `--reason` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.\n2. Request approval: `parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"`\n3. A card will appear in the specified chat for someone with permission to approve\n4. Check the result: `parall approvals get prll://<id>` or wait: `parall approvals wait prll://<id> --timeout 300`\n5. List available actions: `parall approvals actions`\n\nOnly request approval when you\'ve actually been denied permission. Don\'t request approval preemptively.\n';
51254
+ 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.";
51255
+ 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.';
51256
51256
  var BRIDGE_SKILL_HINTS = {
51257
51257
  SCHEDULES_SKILL_HINT: " (read the `parall-schedules` skill at .parall/skills/parall-schedules.md).",
51258
51258
  TASKS_SKILL_HINT: "\nDetails: read the `parall-tasks` skill at .parall/skills/parall-tasks.md and follow it.",
@@ -51379,15 +51379,6 @@ import * as fs from "node:fs";
51379
51379
  import * as path from "node:path";
51380
51380
  import { fileURLToPath } from "node:url";
51381
51381
  var CAPABILITY_FEISHU_CLI = "feishu-cli";
51382
- var CAPABILITY_SLACK_SEND = "slack-send";
51383
- var CAPABILITY_WECHAT_SEND = "wechat-send";
51384
- function channelCapabilityKeyFor(provider) {
51385
- if (provider === "slack")
51386
- return CAPABILITY_SLACK_SEND;
51387
- if (provider === "wechat")
51388
- return CAPABILITY_WECHAT_SEND;
51389
- return `${provider}-cli`;
51390
- }
51391
51382
  var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
51392
51383
  function capabilityBinDir(stateDir) {
51393
51384
  return path.join(stateDir, "bin");
@@ -51468,213 +51459,18 @@ function buildErrorStepContent(message) {
51468
51459
  return { text: message, suppressed: false, status: "error" };
51469
51460
  }
51470
51461
 
51471
- // ts/agent-core/dist/event-format.js
51472
- var MESSAGE_REF_URI = "prll:\\/\\/msg_[A-Za-z0-9_-]+(?:\\/content\\?v=[1-9][0-9]{0,8}#t=[0-9]+-[0-9]+)?";
51473
- var MESSAGE_RANGE_REF_URI = "prll:\\/\\/cht_[A-Za-z0-9_-]+#range=msg_[A-Za-z0-9_-]+,msg_[A-Za-z0-9_-]+";
51474
- var REF_URI = `(?:${MESSAGE_REF_URI}|${MESSAGE_RANGE_REF_URI})`;
51475
- var REF_TOKEN = `(?:${REF_URI}|\\[(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*\\]\\(${REF_URI}\\)|<${REF_URI}>)`;
51476
- var FORWARDED_REF_LINE = new RegExp(`^${REF_TOKEN}(?:\\s+${REF_TOKEN})*$`);
51477
- function isForwardedMessageBody(body) {
51478
- const lines = body.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
51479
- return lines.length > 0 && lines.every((line) => FORWARDED_REF_LINE.test(line));
51480
- }
51462
+ // ts/agent-core/dist/fork-prefix.js
51481
51463
  function sanitizeMeta(value) {
51482
51464
  return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
51483
51465
  }
51484
- function formatApprovalDecisionReason(status, reason) {
51485
- const normalized = reason?.trim();
51486
- if (status !== "rejected" || !normalized)
51487
- return "";
51488
- return `Reason (JSON): ${JSON.stringify(normalized)}`;
51489
- }
51490
- function threadWatcherHint(threadRootId) {
51491
- 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.]`;
51492
- }
51493
- function buildEventBody(event) {
51494
- const lines = [];
51495
- if (event.type === "message") {
51496
- lines.push(`[Event: message.new]`);
51497
- const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
51498
- lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
51499
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51500
- lines.push(`[Message ID: prll://${event.messageId}]`);
51501
- if (event.threadRootId) {
51502
- const threadMeta = [
51503
- `prll://${event.threadRootId}`,
51504
- event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
51505
- event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
51506
- event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
51507
- ].filter(Boolean).join(" | ");
51508
- lines.push(`[Thread: ${threadMeta}]`);
51509
- }
51510
- if (event.deliveryReason)
51511
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51512
- if (event.deliveryReason === "watcher" && event.threadRootId) {
51513
- lines.push(threadWatcherHint(sanitizeMeta(event.threadRootId)));
51514
- }
51515
- if (event.unreadCount != null && event.unreadCount > 1) {
51516
- const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
51517
- const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
51518
- let line = `[Unread: ${countStr} messages${sinceStr}]`;
51519
- if (event.unreadCount > 50)
51520
- line += ` \u2014 fetch recent context with --limit, not all`;
51521
- lines.push(line);
51522
- }
51523
- if (event.noReply)
51524
- lines.push(`[Hint: no_reply]`);
51525
- if (isForwardedMessageBody(event.body)) {
51526
- 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.]`);
51527
- }
51528
- if (event.attachments?.length) {
51529
- for (const att of event.attachments) {
51530
- const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
51531
- lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
51532
- }
51533
- }
51534
- lines.push("", event.body);
51535
- } else if (event.type === "task_comment") {
51536
- lines.push(`[Event: task.comment.created]`);
51537
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
51538
- lines.push(`[Task: ${taskLabel}]`);
51539
- if (event.deliveryReason)
51540
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51541
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51542
- lines.push(`[Comment ID: prll://${event.messageId}]`);
51543
- lines.push("", event.body);
51544
- } else if (event.type === "wiki_comment") {
51545
- lines.push(`[Event: wiki.comment.created]`);
51546
- const target = event.replyTargetUri ?? `prll://${event.targetId}`;
51547
- if (event.targetType === "changeset") {
51548
- lines.push(`[Wiki Changeset: ${target}]`);
51549
- } else {
51550
- lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
51551
- }
51552
- if (event.deliveryReason)
51553
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51554
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51555
- lines.push(`[Comment ID: prll://${event.messageId}]`);
51556
- lines.push("", event.body);
51557
- } else if (event.type === "approval") {
51558
- lines.push(`[Event: approval.decided]`);
51559
- lines.push(`[Approval: prll://${event.messageId}]`);
51560
- lines.push(`[Chat: prll://${event.targetId}]`);
51561
- lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
51562
- lines.push("", event.body);
51563
- } else if (event.type === "schedule") {
51564
- lines.push(`[Event: schedule.fired]`);
51565
- lines.push(`[Schedule: prll://${event.targetId}]`);
51566
- lines.push(`[Run: prll://${event.messageId}]`);
51567
- if (event.scheduledFireAt)
51568
- lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
51569
- if (event.attachedUri)
51570
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
51571
- lines.push("", event.body);
51572
- } else if (event.type === "channel_message") {
51573
- lines.push(`[Event: channel.message]`);
51574
- const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
51575
- const convType = sanitizeMeta(event.channelConversationType ?? "conversation");
51576
- const convId = event.channelExternalConversationId ? sanitizeMeta(event.channelExternalConversationId) : void 0;
51577
- const convName = event.channelExternalConversationName ? sanitizeMeta(event.channelExternalConversationName) : void 0;
51578
- const convLabel = convName ? `${convName} (${convId ? `${convId}, ` : ""}${convType})` : convId ? `${convId} (${convType})` : convType;
51579
- lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
51580
- lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
51581
- if (event.channelExternalMessageId) {
51582
- lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
51583
- }
51584
- 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.]`);
51585
- lines.push("", event.body);
51586
- } else if (event.type === "external_trigger") {
51587
- lines.push(`[Event: external.trigger]`);
51588
- lines.push(`[Trigger: prll://${event.targetId}]`);
51589
- lines.push(`[Run: prll://${event.messageId}]`);
51590
- if (event.externalConnectionId) {
51591
- const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
51592
- lines.push(`[Connection: ${label}]`);
51593
- }
51594
- if (event.externalIngressEventId)
51595
- lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
51596
- if (event.attachedUri)
51597
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
51598
- if (event.externalConnectionSourceType) {
51599
- lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
51600
- }
51601
- if (event.externalIngressEventType) {
51602
- lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
51603
- }
51604
- lines.push("", event.body);
51605
- } else {
51606
- lines.push(`[Event: task.assigned]`);
51607
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
51608
- lines.push(`[Task: ${taskLabel}]`);
51609
- lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
51610
- lines.push("", event.body);
51611
- }
51612
- return lines.join("\n") + buildSendMessageHint(event);
51613
- }
51614
- function buildEventBodyForForkResult(event) {
51615
- return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
51466
+ function eventBody(event) {
51467
+ return event.frame ?? "";
51616
51468
  }
51617
- function buildSendMessageHint(event) {
51618
- if (event.noReply)
51619
- return "";
51620
- if (event.type === "wiki_comment" && event.replyTargetUri) {
51621
- const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
51622
- return `
51623
- <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>`;
51624
- }
51625
- if (event.targetId.startsWith("cht_")) {
51626
- if (event.threadRootId) {
51627
- return `
51628
- <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>`;
51629
- }
51630
- return `
51631
- <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>`;
51632
- }
51633
- if (event.targetId.startsWith("tsk_")) {
51634
- return `
51635
- <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>`;
51636
- }
51637
- if (event.targetId.startsWith("sch_")) {
51638
- return `
51639
- <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
51640
- }
51641
- if (event.type === "channel_message") {
51642
- if (event.channelCliCapable) {
51643
- if (event.channelProvider === "slack") {
51644
- const channelArg = event.channelExternalConversationId ? ` --channel "${event.channelExternalConversationId}"` : " --channel <conversation id from this event>";
51645
- const replyTo = event.channelExternalMessageId ? ` --reply-to "${event.channelExternalMessageId}"` : "";
51646
- return `
51647
- <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>`;
51648
- }
51649
- if (event.channelProvider === "wechat") {
51650
- const toArg = event.channelExternalConversationId ? ` --to "${event.channelExternalConversationId}"` : " --to <wxid from this event>";
51651
- const atArg = event.channelConversationType === "group" ? event.senderId && event.senderId !== "external" ? ` --at "${event.senderId}"` : " --at <wxid of the person you are answering>" : "";
51652
- const historyArg = event.channelExternalConversationId ? ` --conversation "${event.channelExternalConversationId}"` : " --conversation <wxid from this event>";
51653
- return `
51654
- <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>`;
51655
- }
51656
- if (!event.channelProvider) {
51657
- return `
51658
- <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>`;
51659
- }
51660
- const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
51661
- const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
51662
- return `
51663
- <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>`;
51664
- }
51665
- const platform = event.channelProvider ?? "the external platform";
51666
- return `
51667
- <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>`;
51668
- }
51669
- if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
51670
- return `
51671
- <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>`;
51672
- }
51673
- return "";
51469
+ function forkResultBody(event) {
51470
+ return eventBody(event).replace(/\n\[Reminder[^\n]*\]$/, "");
51674
51471
  }
51675
51472
  function buildForkScopePrefix(event) {
51676
- const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
51677
- 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.
51473
+ 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.
51678
51474
 
51679
51475
  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.
51680
51476
 
@@ -51703,6 +51499,26 @@ function buildForkResultPrefix(results) {
51703
51499
 
51704
51500
  // ts/agent-core/dist/gateway-base.js
51705
51501
  import * as os from "node:os";
51502
+
51503
+ // ts/agent-core/dist/change-source.js
51504
+ var CHANGE_REASONS = /* @__PURE__ */ new Set([
51505
+ "edited",
51506
+ "deleted",
51507
+ "unmentioned",
51508
+ "mention",
51509
+ "reaction"
51510
+ ]);
51511
+ function splitChangeSource(sourceId) {
51512
+ const i = sourceId.indexOf("~");
51513
+ if (i <= 0)
51514
+ return { messageId: sourceId };
51515
+ const [reason] = sourceId.slice(i + 1).split("~");
51516
+ if (!reason || !CHANGE_REASONS.has(reason))
51517
+ return { messageId: sourceId };
51518
+ return { messageId: sourceId.slice(0, i), reason };
51519
+ }
51520
+
51521
+ // ts/agent-core/dist/gateway-base.js
51706
51522
  import * as fs3 from "node:fs";
51707
51523
  import * as path3 from "node:path";
51708
51524
  import { randomUUID } from "node:crypto";
@@ -51817,6 +51633,8 @@ var ENDPOINTS = {
51817
51633
  MESSAGE_WATCH: (id) => `${API_BASE}/messages/${id}/watch`,
51818
51634
  MESSAGE_WATCHERS: (id) => `${API_BASE}/messages/${id}/watchers`,
51819
51635
  MESSAGE_WATCHING: (id) => `${API_BASE}/messages/${id}/watching`,
51636
+ /** Caller's attention levels across chats / threads / tasks. */
51637
+ WATCHES: (orgId) => `${API_BASE}/orgs/${orgId}/watches`,
51820
51638
  MESSAGE_REACTIONS: (id) => `${API_BASE}/messages/${id}/reactions`,
51821
51639
  MESSAGE_REACTION: (id, emoji) => `${API_BASE}/messages/${id}/reactions/${encodeURIComponent(emoji)}`,
51822
51640
  // Upload (org-scoped)
@@ -51839,6 +51657,7 @@ var ENDPOINTS = {
51839
51657
  AGENT_ACTIVITY: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/activity`,
51840
51658
  AGENT_MONITOR: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/monitor`,
51841
51659
  AGENT_ME: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me`,
51660
+ AGENT_REPLY_POLICY_CAPABILITY: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/reply-policy-capability`,
51842
51661
  AGENT_NEW_SESSION: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/new-session`,
51843
51662
  AGENT_DEEP_RESET: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/deep-reset`,
51844
51663
  AGENT_SESSIONS: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/sessions`,
@@ -51875,6 +51694,7 @@ var ENDPOINTS = {
51875
51694
  MACHINE_AGENT_WORKSPACE_SETUP: (orgId, machineId, agentId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/agents/${agentId}/workspace/setup`,
51876
51695
  MACHINE_LLM_SOURCE: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/llm-source`,
51877
51696
  MACHINE_PROVIDER_ENABLED: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/provider-enabled`,
51697
+ MACHINE_MANAGED_BY: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/managed-by`,
51878
51698
  MACHINE_CAPABILITIES: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/capabilities`,
51879
51699
  MACHINE_RUNTIME_AUTH: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/runtime-auth`,
51880
51700
  MACHINE_KEYS: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/keys`,
@@ -52355,8 +52175,22 @@ var ProjectTaskClient = class {
52355
52175
  async unsubscribeTaskMember(orgId, taskId, userId) {
52356
52176
  return this.request("DELETE", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52357
52177
  }
52358
- async watchThread(threadRootId) {
52359
- return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52178
+ async watchThread(threadRootId, body) {
52179
+ return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId), body);
52180
+ }
52181
+ // ---- Attention settings (agent-attention-design.md §4) ----
52182
+ /** The caller's watch rows: the setting per chat / thread. */
52183
+ async listWatches(orgId) {
52184
+ const res = await this.request("GET", ENDPOINTS.WATCHES(orgId));
52185
+ return res.data;
52186
+ }
52187
+ /**
52188
+ * Set the caller's setting on one target (prll://cht_ / msg_ root).
52189
+ * Threads are watched first when not yet; chats require membership (404
52190
+ * NOT_A_MEMBER otherwise). Tasks carry no setting (watch / unwatch only).
52191
+ */
52192
+ async setWatchLevel(orgId, body) {
52193
+ return this.request("PUT", ENDPOINTS.WATCHES(orgId), body);
52360
52194
  }
52361
52195
  async unwatchThread(threadRootId) {
52362
52196
  return this.request("DELETE", ENDPOINTS.MESSAGE_WATCH(threadRootId));
@@ -53405,6 +53239,15 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53405
53239
  const res = await this.request("GET", ENDPOINTS.APPROVALS_ACTIONS);
53406
53240
  return res.data;
53407
53241
  }
53242
+ /**
53243
+ * Action names plus the payload contract each documented action publishes
53244
+ * (field names, types, and where a CAS base like expected_version is read
53245
+ * from). Additive over getApprovableActions(): older servers omit
53246
+ * `contracts`.
53247
+ */
53248
+ async getApprovableActionCatalog() {
53249
+ return this.request("GET", ENDPOINTS.APPROVALS_ACTIONS);
53250
+ }
53408
53251
  // ---- Agents (org-scoped) ----
53409
53252
  async createAgent(orgId, req, opts) {
53410
53253
  return this.request("POST", ENDPOINTS.AGENTS(orgId), req, void 0, false, opts);
@@ -53629,6 +53472,19 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53629
53472
  provider_enabled: providerEnabled
53630
53473
  });
53631
53474
  }
53475
+ /**
53476
+ * Convert a member's personal device into an organization machine
53477
+ * (PATCH /machines/{id}/managed-by). One-way and idempotent; org admins only
53478
+ * (an admin-role agent qualifies). After conversion every org admin manages
53479
+ * the machine and the registrant is just a member. 'member' is rejected —
53480
+ * an org machine cannot become a personal device again. See
53481
+ * docs/engineering-design/org-machine-assets-design.md §4.
53482
+ */
53483
+ async convertMachineToOrgManaged(orgId, machineId) {
53484
+ return this.request("PATCH", ENDPOINTS.MACHINE_MANAGED_BY(orgId, machineId), {
53485
+ managed_by: "org"
53486
+ });
53487
+ }
53632
53488
  /**
53633
53489
  * Replace the machine's capability set (admin). Primary use: healing a
53634
53490
  * machine that registered without `browser_provider` during the capability
@@ -53878,6 +53734,18 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53878
53734
  async steerDispatch(orgId, req) {
53879
53735
  return this.request("POST", ENDPOINTS.DISPATCH_STEER(orgId), req);
53880
53736
  }
53737
+ /**
53738
+ * Declare the runtime contract for this WS connection: the runtime runs
53739
+ * what the server decides and takes the server-rendered wake frame from
53740
+ * claim / steer responses instead of filtering and rendering locally.
53741
+ * Bound to the connection's session id; re-declare on every hello.
53742
+ * 409 STALE_WS_SESSION when the id is not the agent's current connection.
53743
+ */
53744
+ async declareReplyPolicyCapability(orgId, wsSessionId) {
53745
+ await this.request("PUT", ENDPOINTS.AGENT_REPLY_POLICY_CAPABILITY(orgId), {
53746
+ ws_session_id: wsSessionId
53747
+ });
53748
+ }
53881
53749
  /** Advance exact runtime-input lifecycle for members of an explicit lane. */
53882
53750
  async updateDispatchInputState(orgId, req) {
53883
53751
  return this.request("POST", ENDPOINTS.DISPATCH_INPUT_STATE(orgId), req);
@@ -55209,20 +55077,6 @@ function buildApiError(res, rawErrorBody) {
55209
55077
  return apiError;
55210
55078
  }
55211
55079
 
55212
- // ts/sdk/dist/types.js
55213
- var MENTION_ALL_USER_ID = "all";
55214
- var MENTION_ALL_HUMANS_USER_ID = "allhuman";
55215
- var MENTION_ALL_AGENTS_USER_ID = "allagent";
55216
- function mentionTargetsUser(mentionUserId, userId, userType) {
55217
- if (mentionUserId === userId || mentionUserId === MENTION_ALL_USER_ID)
55218
- return true;
55219
- if (mentionUserId === MENTION_ALL_HUMANS_USER_ID)
55220
- return userType === "human";
55221
- if (mentionUserId === MENTION_ALL_AGENTS_USER_ID)
55222
- return userType === "agent";
55223
- return false;
55224
- }
55225
-
55226
55080
  // ts/sdk/dist/ws.js
55227
55081
  function isRetryableNetworkError(err) {
55228
55082
  return err instanceof Error && err.name === "ApiError" && "status" in err && err.status === 0;
@@ -55654,7 +55508,7 @@ var LaneLedger = class {
55654
55508
  get contextDir() {
55655
55509
  return this.opts.contextDir;
55656
55510
  }
55657
- /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
55511
+ /** Chat message events ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
55658
55512
  handles(event) {
55659
55513
  return event.type === "message" && event.targetId.startsWith("cht_");
55660
55514
  }
@@ -55670,6 +55524,75 @@ var LaneLedger = class {
55670
55524
  laneContextPath(lane) {
55671
55525
  return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
55672
55526
  }
55527
+ /**
55528
+ * Whether the server already rendered this message into a frame the model
55529
+ * saw on its live lane. The row is folded there and resolves with that
55530
+ * lane's turn — a local copy has nothing left to deliver.
55531
+ */
55532
+ seenInFrame(targetId, threadRootId, messageId) {
55533
+ const lane = this.lanes.get(laneKeyForTarget(`prll://${targetId}`, threadRootId));
55534
+ return lane?.seen.has(messageId) ?? false;
55535
+ }
55536
+ /**
55537
+ * Hand the pending frame to the caller (once) with the members it covers
55538
+ * and what the claim said about the wake, and record those members as
55539
+ * seen. Absent frame ⇒ nothing new to render (every member already seen).
55540
+ */
55541
+ takeFrame(lane) {
55542
+ const frame = lane.frame;
55543
+ const ids = lane.framed;
55544
+ for (const id of ids)
55545
+ lane.seen.add(id);
55546
+ lane.frame = void 0;
55547
+ lane.framed = [];
55548
+ const { input, noReply, attachments } = lane;
55549
+ lane.input = void 0;
55550
+ lane.noReply = void 0;
55551
+ lane.attachments = void 0;
55552
+ return { frame, ids, input, noReply, attachments };
55553
+ }
55554
+ /** Record what the claim response said about the wake alongside its frame. */
55555
+ recordWake(lane, res) {
55556
+ if (res.input)
55557
+ lane.input = res.input;
55558
+ if (res.no_reply != null)
55559
+ lane.noReply = res.no_reply;
55560
+ if (res.attachments?.length) {
55561
+ lane.attachments = res.attachments.map((a) => ({
55562
+ id: a.id,
55563
+ fileName: a.file_name ?? "",
55564
+ fileSize: a.file_size ?? 0,
55565
+ mimeType: a.mime_type ?? ""
55566
+ }));
55567
+ }
55568
+ }
55569
+ /** The injection landed: the model has seen these members. */
55570
+ markSeen(event, ids) {
55571
+ const lane = this.lanes.get(this.laneKeyFor(event));
55572
+ if (!lane)
55573
+ return;
55574
+ for (const id of ids)
55575
+ lane.seen.add(id);
55576
+ }
55577
+ /**
55578
+ * The injection did not land (turn already over, process gone): keep the
55579
+ * server's increment as the lane's pending frame so the buffered copy's
55580
+ * drain renders it as its own turn instead of skipping it as seen.
55581
+ */
55582
+ deferFrame(event, frame, ids) {
55583
+ const lane = this.lanes.get(this.laneKeyFor(event));
55584
+ if (!lane)
55585
+ return;
55586
+ this.recordFrame(lane, frame, ids);
55587
+ }
55588
+ recordFrame(lane, frame, ids) {
55589
+ if (!frame)
55590
+ return;
55591
+ lane.frame = lane.frame ? `${lane.frame}
55592
+
55593
+ ${frame}` : frame;
55594
+ lane.framed.push(...ids);
55595
+ }
55673
55596
  /**
55674
55597
  * Claim (or reuse) the lane for a group of same-lane message events and
55675
55598
  * fold every group member into it. Returns 'foreign' when a healthy
@@ -55719,11 +55642,15 @@ var LaneLedger = class {
55719
55642
  threadRootId: trigger.threadRootId,
55720
55643
  coverageMode: actualCoverage,
55721
55644
  folded: /* @__PURE__ */ new Map(),
55645
+ framed: [],
55646
+ seen: /* @__PURE__ */ new Set(),
55722
55647
  ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
55723
55648
  };
55724
55649
  for (const ev of res.events ?? []) {
55725
55650
  lane.folded.set(ev.source_id, ev.id);
55726
55651
  }
55652
+ this.recordFrame(lane, res.frame, (res.events ?? []).map((ev) => ev.source_id));
55653
+ this.recordWake(lane, res);
55727
55654
  this.lanes.set(laneKey, lane);
55728
55655
  }
55729
55656
  for (const ev of events) {
@@ -55737,6 +55664,7 @@ var LaneLedger = class {
55737
55664
  ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
55738
55665
  });
55739
55666
  lane.folded.set(ev.messageId, res.dispatch_event_id);
55667
+ this.recordFrame(lane, res.frame, [ev.messageId]);
55740
55668
  } catch (err) {
55741
55669
  if (isStaleLane(err)) {
55742
55670
  this.lanes.delete(laneKey);
@@ -55760,8 +55688,13 @@ var LaneLedger = class {
55760
55688
  const lane = this.lanes.get(laneKey);
55761
55689
  if (!lane)
55762
55690
  return null;
55691
+ if (lane.seen.has(event.messageId))
55692
+ return null;
55763
55693
  if (lane.folded.has(event.messageId)) {
55764
- return { inputLifecycle: this.inputLifecycle(lane, [event]) };
55694
+ return {
55695
+ inputLifecycle: this.inputLifecycleFor(lane, [event.messageId]),
55696
+ covered: [event.messageId]
55697
+ };
55765
55698
  }
55766
55699
  try {
55767
55700
  const res = await this.opts.client.steerDispatch(this.opts.orgId, {
@@ -55771,7 +55704,12 @@ var LaneLedger = class {
55771
55704
  ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
55772
55705
  });
55773
55706
  lane.folded.set(event.messageId, res.dispatch_event_id);
55774
- return { inputLifecycle: this.inputLifecycle(lane, [event]) };
55707
+ const covered = [event.messageId];
55708
+ return {
55709
+ inputLifecycle: this.inputLifecycleFor(lane, covered),
55710
+ frame: res.frame,
55711
+ covered
55712
+ };
55775
55713
  } catch (err) {
55776
55714
  if (isStaleLane(err)) {
55777
55715
  this.lanes.delete(laneKey);
@@ -55786,10 +55724,18 @@ var LaneLedger = class {
55786
55724
  * batched prompt covers every WorkItem represented in that single frame.
55787
55725
  */
55788
55726
  inputLifecycle(lane, events) {
55727
+ return this.inputLifecycleFor(lane, events.map((event) => event.messageId));
55728
+ }
55729
+ /**
55730
+ * Exact lifecycle over a set of folded members by message id — the set a
55731
+ * prompt or injection actually delivers (frame coverage ∪ buffered group).
55732
+ */
55733
+ inputLifecycleFor(lane, messageIds) {
55789
55734
  if (lane.coverageMode !== "explicit")
55790
55735
  return void 0;
55791
- const dispatchEventIds = events.map((event) => lane.folded.get(event.messageId)).filter((id) => Boolean(id));
55792
- if (dispatchEventIds.length !== events.length) {
55736
+ const unique = [...new Set(messageIds)];
55737
+ const dispatchEventIds = unique.map((messageId) => lane.folded.get(messageId)).filter((id) => Boolean(id));
55738
+ if (dispatchEventIds.length !== unique.length) {
55793
55739
  throw new Error(`explicit lane ${lane.lane} is missing a folded WorkItem mapping`);
55794
55740
  }
55795
55741
  return {
@@ -55987,10 +55933,12 @@ var LaneLedger = class {
55987
55933
  return this.lanes.size;
55988
55934
  }
55989
55935
  /**
55990
- * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
55991
- * by WorkItem id or by source identity (the live task.assigned event has no
55992
- * WorkItem id). Returns null when a healthy incumbent (another pod) holds
55993
- * it or the WorkItem is already resolved the caller must skip processing.
55936
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>)
55937
+ * by WorkItem id. The server renders the wake frame on claim (or resolves
55938
+ * the item as stale and answers `claimed: false, reason: "stale"`).
55939
+ * Returns null when a healthy incumbent (another pod) holds it, the
55940
+ * WorkItem is already resolved, or the server found nothing to wake for
55941
+ * — the caller must skip processing.
55994
55942
  */
55995
55943
  async claimTyped(ref) {
55996
55944
  let res;
@@ -56005,8 +55953,15 @@ var LaneLedger = class {
56005
55953
  throw new LedgerUnsupportedError("claim endpoint unavailable");
56006
55954
  throw err;
56007
55955
  }
56008
- if (!res.claimed || !res.lane || !res.events?.length)
55956
+ if (!res.claimed || !res.lane || !res.events?.length) {
55957
+ if (res.reason === "stale") {
55958
+ this.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} resolved by the server as stale (${res.stale_reason ?? "unspecified"})`);
55959
+ } else if (res.claimed && res.lane) {
55960
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, res.lane).catch(() => {
55961
+ });
55962
+ }
56009
55963
  return null;
55964
+ }
56010
55965
  const workItem = res.events[0];
56011
55966
  const targetUri = `dsp:${workItem.id}`;
56012
55967
  const leaseUntilMs = Date.parse(res.lease_until ?? "");
@@ -56016,9 +55971,13 @@ var LaneLedger = class {
56016
55971
  targetUri,
56017
55972
  coverageMode: "implicit",
56018
55973
  folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
55974
+ framed: [],
55975
+ seen: /* @__PURE__ */ new Set(),
56019
55976
  typedDispatchEventId: workItem.id,
56020
55977
  ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
56021
55978
  };
55979
+ this.recordFrame(lane, res.frame, [workItem.source_id]);
55980
+ this.recordWake(lane, res);
56022
55981
  this.lanes.set(lane.laneKey, lane);
56023
55982
  return lane;
56024
55983
  }
@@ -56061,6 +56020,19 @@ function shiftMainBufferGroup(host, groupKey, preserveInjectedFrameBoundary) {
56061
56020
  }
56062
56021
  return events;
56063
56022
  }
56023
+ function applyWake(event, wake) {
56024
+ if (wake.frame)
56025
+ event.frame = wake.frame;
56026
+ if (wake.input) {
56027
+ event.input = wake.input;
56028
+ if (wake.input.sender_id)
56029
+ event.senderId = wake.input.sender_id;
56030
+ }
56031
+ if (wake.noReply != null)
56032
+ event.noReply = wake.noReply;
56033
+ if (wake.attachments?.length)
56034
+ event.attachments = wake.attachments;
56035
+ }
56064
56036
  function hasUninjectedSameLaneEventAhead(host, event) {
56065
56037
  const eventIndex = host.dispatchState.mainBuffer.lastIndexOf(event);
56066
56038
  if (eventIndex <= 0)
@@ -56078,10 +56050,17 @@ async function steerLaneMessage(host, event) {
56078
56050
  const folded = await ledger.steerLive(event);
56079
56051
  if (!folded)
56080
56052
  return;
56081
- const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, buildEventBody(event), folded.inputLifecycle);
56053
+ if (!folded.frame)
56054
+ return;
56055
+ event.frame = folded.frame;
56056
+ const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, eventBody(event), folded.inputLifecycle);
56082
56057
  if (injected) {
56083
56058
  host.injectedMainBufferEvents.add(event);
56059
+ ledger.markSeen(event, folded.covered);
56084
56060
  opts.log?.info(`steer folded+injected for ${event.messageId} (will drain for bookkeeping)`);
56061
+ } else if (folded.frame) {
56062
+ ledger.deferFrame(event, folded.frame, folded.covered);
56063
+ opts.log?.info(`steer folded but not injected for ${event.messageId} \u2014 frame deferred to the drain`);
56085
56064
  }
56086
56065
  }
56087
56066
  async function dispatchLaneGroup(host, opts) {
@@ -56094,18 +56073,9 @@ async function dispatchLaneGroup(host, opts) {
56094
56073
  if (!(err instanceof LedgerUnsupportedError))
56095
56074
  throw err;
56096
56075
  host.disableLedger("claim endpoint missing");
56097
- await host.emitDispatchReceived(event);
56098
- const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
56099
- if (!dispatched2)
56100
- return "shutdown";
56101
- for (const ev of opts.events) {
56102
- host.opts.client.ackDispatch(host.opts.config.org_id, {
56103
- source_type: ev.ackSourceType ?? "message",
56104
- source_id: ev.ackSourceId ?? ev.messageId
56105
- }).catch(() => {
56106
- });
56107
- }
56108
- return "dispatched";
56076
+ for (const ev of opts.events)
56077
+ host.dispatchedMessages.delete(ev.messageId);
56078
+ return "foreign";
56109
56079
  }
56110
56080
  if (!lane) {
56111
56081
  for (const ev of opts.events) {
@@ -56113,11 +56083,32 @@ async function dispatchLaneGroup(host, opts) {
56113
56083
  }
56114
56084
  return "foreign";
56115
56085
  }
56086
+ const pending = ledger.takeFrame(lane);
56087
+ const frame = pending.frame;
56088
+ if (!frame && opts.events.every((ev) => lane.seen.has(ev.messageId))) {
56089
+ host.opts.log?.info(`lane group for ${event.messageId} already rendered by the server frame \u2014 no turn`);
56090
+ const pendingInjections2 = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
56091
+ await ledger.completeIfIdle(lane.laneKey, pendingInjections2 || opts.hasMoreLocal());
56092
+ return "dispatched";
56093
+ }
56094
+ if (!frame) {
56095
+ host.opts.log?.warn(`lane group for ${event.messageId} claimed without a frame \u2014 releasing the members instead of running`);
56096
+ for (const ev of opts.events)
56097
+ host.dispatchedMessages.delete(ev.messageId);
56098
+ await ledger.release(lane.laneKey).catch(() => {
56099
+ });
56100
+ return "foreign";
56101
+ }
56102
+ applyWake(event, pending);
56116
56103
  host.noteSessionLane(opts.sessionKey, lane.laneKey);
56117
56104
  let dispatched = false;
56118
56105
  try {
56119
- const inputLifecycle = ledger.inputLifecycle(lane, [...opts.earlier, event]);
56120
- dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText, inputLifecycle);
56106
+ const inputLifecycle = ledger.inputLifecycleFor(lane, [
56107
+ ...opts.earlier.map((ev) => ev.messageId),
56108
+ event.messageId,
56109
+ ...frame ? pending.ids : []
56110
+ ]);
56111
+ dispatched = await host.runDispatch(event, opts.sessionKey, opts.bodyPrefix + eventBody(event), opts.earlier, opts.captureText, inputLifecycle);
56121
56112
  } catch (err) {
56122
56113
  host.noteSessionLane(opts.sessionKey, null);
56123
56114
  await ledger.release(lane.laneKey).catch(() => {
@@ -56185,50 +56176,16 @@ async function resolveDispatchByID(host, dispatchEventId, lane) {
56185
56176
  return "failed";
56186
56177
  }
56187
56178
  }
56188
- function clearTypedDedupeForEvent(host, event) {
56189
- const sourceId = event.ackSourceId;
56190
- if (!sourceId)
56191
- return;
56192
- switch (event.ackSourceType) {
56193
- case "task_activity": {
56194
- const prefix = `${event.targetId}:`;
56195
- for (const key of host.dispatchedTasks) {
56196
- if (key.startsWith(prefix))
56197
- host.dispatchedTasks.delete(key);
56198
- }
56199
- break;
56200
- }
56201
- case "comment":
56202
- host.dispatchedTasks.delete(`comment:${sourceId}`);
56203
- break;
56204
- case "schedule_run":
56205
- host.dispatchedTasks.delete(`schedule_run:${sourceId}`);
56206
- break;
56207
- case "external_trigger_run":
56208
- host.dispatchedTasks.delete(`external_trigger_run:${sourceId}`);
56209
- break;
56210
- case "channel_message":
56211
- host.dispatchedMessages.delete(`channel_message:${sourceId}`);
56212
- break;
56213
- case "approval":
56214
- host.dispatchedTasks.delete(`approval:${sourceId}`);
56215
- break;
56216
- }
56217
- }
56218
56179
  async function settleDrainedTypedGroup(host, events, ids, turnErrored) {
56219
56180
  if (turnErrored) {
56220
56181
  host.opts.log?.info(`buffered typed turn for ${events[events.length - 1]?.messageId} surfaced a runtime error \u2014 leaving for re-drive`);
56221
- for (const event of events)
56222
- clearTypedDedupeForEvent(host, event);
56223
56182
  return;
56224
56183
  }
56225
56184
  const legacyAckFrom = async (start) => {
56226
- for (const [j, id] of ids.slice(start).entries()) {
56185
+ for (const id of ids.slice(start)) {
56227
56186
  try {
56228
56187
  await host.opts.client.ackDispatchByID(host.opts.config.org_id, id);
56229
56188
  } catch {
56230
- } finally {
56231
- clearTypedDedupeForEvent(host, events[start + j]);
56232
56189
  }
56233
56190
  }
56234
56191
  };
@@ -56244,7 +56201,6 @@ async function settleDrainedTypedGroup(host, events, ids, turnErrored) {
56244
56201
  await legacyAckFrom(i);
56245
56202
  return;
56246
56203
  }
56247
- clearTypedDedupeForEvent(host, events[i]);
56248
56204
  }
56249
56205
  }
56250
56206
  var TYPED_BACKOFF_BASE_MS = 2e3;
@@ -56280,18 +56236,8 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56280
56236
  }
56281
56237
  host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
56282
56238
  };
56283
- const runLegacy = async () => {
56284
- let acked = false;
56285
- try {
56286
- if (await run(ref.dispatchEventId)) {
56287
- acked = settleAck(await hooks.legacyAck(ref.dispatchEventId));
56288
- }
56289
- } finally {
56290
- settle(acked);
56291
- }
56292
- };
56293
56239
  if (!host.laneLedger || host.ledgerDisabled) {
56294
- await runLegacy();
56240
+ host.opts.log?.info(`typed dispatch ${backoffKey} skipped \u2014 the server renders no wake frame`);
56295
56241
  return;
56296
56242
  }
56297
56243
  let lane;
@@ -56300,7 +56246,6 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56300
56246
  } catch (err) {
56301
56247
  if (err instanceof LedgerUnsupportedError) {
56302
56248
  host.disableLedger("claim endpoint missing");
56303
- await runLegacy();
56304
56249
  return;
56305
56250
  }
56306
56251
  throw err;
@@ -56312,7 +56257,7 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56312
56257
  let resolved = false;
56313
56258
  let viaLegacyAck = false;
56314
56259
  try {
56315
- if (await run(lane.typedDispatchEventId)) {
56260
+ if (await run(lane)) {
56316
56261
  if (host.typedByIdCompleteUnsupported || !lane.typedDispatchEventId) {
56317
56262
  viaLegacyAck = true;
56318
56263
  resolved = settleAck(await hooks.legacyAck(lane.typedDispatchEventId));
@@ -56324,13 +56269,9 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56324
56269
  viaLegacyAck = true;
56325
56270
  resolved = settleAck(await hooks.legacyAck(lane.typedDispatchEventId));
56326
56271
  } else if (outcome === "stale") {
56327
- hooks.clearDedupe?.();
56328
56272
  resolved = true;
56329
56273
  } else {
56330
56274
  resolved = outcome === "ok";
56331
- if (!resolved) {
56332
- hooks.clearDedupe?.();
56333
- }
56334
56275
  }
56335
56276
  }
56336
56277
  }
@@ -56349,56 +56290,27 @@ async function consumeMessageWorkItem(host, item) {
56349
56290
  return;
56350
56291
  if (!host.tryClaimMessage(item.source_id))
56351
56292
  return;
56352
- if (host.dispatchState.mainBuffer.some((event) => event.messageId === item.source_id))
56293
+ if (host.dispatchState.mainBuffer.some((event2) => event2.messageId === item.source_id))
56353
56294
  return;
56354
- const ackItem = () => {
56355
- if (host.laneLedger && !host.ledgerDisabled && !host.typedByIdCompleteUnsupported) {
56356
- void resolveDispatchByID(host, item.id).then((outcome) => {
56357
- if (outcome === "unsupported") {
56358
- host.typedByIdCompleteUnsupported = true;
56359
- host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
56360
- });
56361
- }
56362
- });
56363
- return;
56364
- }
56365
- host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
56366
- });
56367
- };
56368
- let msg = null;
56369
- try {
56370
- msg = await host.opts.client.getMessage(item.source_id);
56371
- } catch (err) {
56372
- const status = err?.status;
56373
- if (status !== 404) {
56374
- host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
56375
- host.dispatchedMessages.delete(item.source_id);
56376
- return;
56377
- }
56378
- }
56379
- if (!msg || msg.sender_id === host.opts.agentUserId) {
56380
- host.dispatchedMessages.delete(item.source_id);
56381
- ackItem();
56382
- return;
56383
- }
56384
- const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
56385
- if (decision.action === "retry") {
56386
- host.dispatchedMessages.delete(item.source_id);
56387
- return;
56388
- }
56389
- if (decision.action === "skip") {
56390
- host.dispatchedMessages.delete(item.source_id);
56391
- ackItem();
56295
+ if (host.laneLedger && !host.ledgerDisabled && host.laneLedger.seenInFrame(item.chat_id, item.thread_root_id ?? void 0, item.source_id)) {
56392
56296
  return;
56393
56297
  }
56394
- decision.event.dispatchEventId = item.id;
56395
- const laneResolved = host.usesLaneLedger(decision.event);
56298
+ const change = splitChangeSource(item.source_id);
56299
+ const event = {
56300
+ type: "message",
56301
+ targetId: item.chat_id,
56302
+ targetType: "chat",
56303
+ senderId: item.actor_id ?? "",
56304
+ messageId: item.source_id,
56305
+ threadRootId: item.thread_root_id ?? void 0,
56306
+ deliveryReason: item.delivery_reason ?? change.reason ?? void 0,
56307
+ ackSourceType: "message",
56308
+ ackSourceId: item.source_id,
56309
+ dispatchEventId: item.id
56310
+ };
56396
56311
  try {
56397
- const dispatched = await host.handleInboundEvent(decision.event);
56398
- if (dispatched) {
56399
- if (!laneResolved)
56400
- ackItem();
56401
- } else {
56312
+ const dispatched = await host.handleInboundEvent(event);
56313
+ if (!dispatched) {
56402
56314
  host.dispatchedMessages.delete(item.source_id);
56403
56315
  }
56404
56316
  } catch (err) {
@@ -57587,6 +57499,16 @@ function createOtelLogger(layer, prefix) {
57587
57499
 
57588
57500
  // ts/agent-core/dist/gateway-base.js
57589
57501
  var LIVE_SESSION_STATUSES = /* @__PURE__ */ new Set(["open", "active", "idle"]);
57502
+ var TYPED_EVENT_KINDS = {
57503
+ task_assign: { type: "task", ackSourceType: "task_activity" },
57504
+ task_update: { type: "task", ackSourceType: "task_activity" },
57505
+ task_comment: { type: "task_comment", ackSourceType: "comment" },
57506
+ wiki_comment: { type: "wiki_comment", ackSourceType: "comment" },
57507
+ "schedule.fire": { type: "schedule", ackSourceType: "schedule_run" },
57508
+ external_trigger: { type: "external_trigger", ackSourceType: "external_trigger_run" },
57509
+ channel_message: { type: "channel_message", ackSourceType: "channel_message" },
57510
+ approval_decided: { type: "approval", ackSourceType: "approval" }
57511
+ };
57590
57512
  function parseShutdownDeadlineMs(raw) {
57591
57513
  if (!raw)
57592
57514
  return void 0;
@@ -57620,6 +57542,9 @@ function inputStepIdempotencyKey(event) {
57620
57542
  return randomUUID();
57621
57543
  }
57622
57544
  function resolveStepTarget(event) {
57545
+ if (event.input?.step_target) {
57546
+ return { target_type: event.input.step_target.type, target_id: event.input.step_target.id };
57547
+ }
57623
57548
  if (event.type === "task" || event.targetId.startsWith("tsk_")) {
57624
57549
  return { target_type: "task", target_id: event.targetId };
57625
57550
  }
@@ -57640,48 +57565,63 @@ function resolveStepTarget(event) {
57640
57565
  }
57641
57566
  return { target_type: "", target_id: event.targetId || void 0 };
57642
57567
  }
57643
- function parseWikiCommentTarget(targetUri) {
57644
- const routingKey = targetUri.replace(/^prll:\/\//, "");
57645
- const entityId = routingKey.match(/^([^/?#]+)/)?.[1] ?? routingKey;
57646
- const targetType = entityId.startsWith("wcs_") ? "changeset" : "wiki";
57647
- let label = entityId;
57648
- if (targetType === "wiki") {
57649
- const pathMatch = routingKey.slice(entityId.length).match(/^\/([^?#]+)/);
57650
- if (pathMatch) {
57651
- try {
57652
- label = decodeURIComponent(pathMatch[1]);
57653
- } catch {
57654
- label = pathMatch[1];
57655
- }
57656
- }
57568
+ function inputTriggerTypeFor(type) {
57569
+ switch (type) {
57570
+ case "task":
57571
+ return "task_assign";
57572
+ case "task_comment":
57573
+ return "task_comment";
57574
+ case "wiki_comment":
57575
+ return "wiki_comment";
57576
+ case "schedule":
57577
+ return "schedule_fire";
57578
+ case "external_trigger":
57579
+ return "external_trigger";
57580
+ case "channel_message":
57581
+ return "channel_message";
57582
+ case "approval":
57583
+ return "approval_decided";
57584
+ default:
57585
+ return "mention";
57586
+ }
57587
+ }
57588
+ function inputTriggerRef(event) {
57589
+ const sourceId = event.ackSourceId ?? event.messageId;
57590
+ switch (event.type) {
57591
+ case "task":
57592
+ return { task_id: event.targetId };
57593
+ case "task_comment":
57594
+ return { comment_id: sourceId, task_id: event.targetId };
57595
+ case "wiki_comment":
57596
+ return { comment_id: sourceId, target_uri: `prll://${event.targetId}` };
57597
+ case "schedule":
57598
+ return { schedule_id: event.targetId, run_id: sourceId };
57599
+ case "external_trigger":
57600
+ return { trigger_id: event.targetId, run_id: sourceId };
57601
+ case "channel_message":
57602
+ return { conversation_id: event.targetId, channel_message_id: sourceId };
57603
+ case "approval":
57604
+ return { approval_id: sourceId };
57605
+ default:
57606
+ return {
57607
+ message_id: splitChangeSource(event.messageId).messageId,
57608
+ // Thread context for the session→chat backlink: a thread reply can
57609
+ // only be navigated to with its thread root.
57610
+ ...event.threadRootId ? { thread_root_id: event.threadRootId } : {}
57611
+ };
57657
57612
  }
57658
- return { routingKey, label, targetType };
57659
- }
57660
- async function fetchAllChats(client, orgId, chatInfoMap) {
57661
- let cursor;
57662
- let total = 0;
57663
- do {
57664
- const res = await client.getChats(orgId, { limit: 100, cursor });
57665
- for (const chat of res.data) {
57666
- chatInfoMap.set(chat.id, {
57667
- type: chat.type,
57668
- name: chat.name ?? null,
57669
- agentRoutingMode: chat.agent_routing_mode
57670
- });
57671
- }
57672
- total += res.data.length;
57673
- cursor = res.has_more ? res.next_cursor : void 0;
57674
- } while (cursor);
57675
- return total;
57676
57613
  }
57677
57614
  var ParallAgentGateway = class {
57678
57615
  opts;
57679
- chatInfoMap = /* @__PURE__ */ new Map();
57680
- dispatchedTasks = /* @__PURE__ */ new Set();
57681
- // connection id → provider alias, for channel_message prompt labeling
57682
- // (stable mapping; avoids one connection fetch per inbound message).
57683
- channelConnectionProviders = /* @__PURE__ */ new Map();
57616
+ // In-process in-flight guard for message WorkItems (see LaneFlowHost).
57684
57617
  dispatchedMessages = /* @__PURE__ */ new Set();
57618
+ /**
57619
+ * Consumption fence: no WorkItem is claimed before this connection's
57620
+ * runtime contract is declared (handleHello). A claim made before the
57621
+ * declaration would get no frame — and a frameless claim has nothing to
57622
+ * run. Open until the first hello starts a declaration.
57623
+ */
57624
+ contractReady = Promise.resolve();
57685
57625
  injectedMainBufferEvents = /* @__PURE__ */ new WeakSet();
57686
57626
  // Per-WorkItem failure backoff for typed dispatch consumption — see
57687
57627
  // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
@@ -57793,29 +57733,6 @@ var ParallAgentGateway = class {
57793
57733
  ws.on("hello", async (data) => {
57794
57734
  await this.handleHello(data);
57795
57735
  });
57796
- ws.on("chat.update", (data) => {
57797
- const changes = data.changes;
57798
- if (!changes)
57799
- return;
57800
- const existing = this.chatInfoMap.get(data.chat_id);
57801
- if (existing) {
57802
- this.chatInfoMap.set(data.chat_id, {
57803
- ...existing,
57804
- ...typeof changes.type === "string" ? { type: changes.type } : {},
57805
- ...typeof changes.name === "string" ? { name: changes.name } : {},
57806
- ...typeof changes.agent_routing_mode === "string" ? { agentRoutingMode: changes.agent_routing_mode } : {}
57807
- });
57808
- } else if (typeof changes.type === "string") {
57809
- this.chatInfoMap.set(data.chat_id, {
57810
- type: changes.type,
57811
- name: typeof changes.name === "string" ? changes.name : null,
57812
- agentRoutingMode: typeof changes.agent_routing_mode === "string" ? changes.agent_routing_mode : "passive"
57813
- });
57814
- }
57815
- });
57816
- ws.on("message.new", async (data) => {
57817
- await this.handleMessage(data);
57818
- });
57819
57736
  ws.on("agent_config.update", async (data) => {
57820
57737
  this.opts.log?.info(`config update notification (version=${data.version})`);
57821
57738
  try {
@@ -57843,135 +57760,11 @@ var ParallAgentGateway = class {
57843
57760
  this.opts.log?.warn(`recovery.overflow \u2014 triggering full catch-up`);
57844
57761
  this.catchUpFromDispatch().catch((err) => this.opts.log?.warn(`overflow catch-up failed: ${String(err)}`));
57845
57762
  });
57846
- ws.on("task.assigned", async (data) => {
57847
- if (data.assignee_id !== this.opts.agentUserId)
57848
- return;
57849
- if (data.status !== "todo" && data.status !== "in_progress")
57850
- return;
57763
+ ws.on("dispatch.new", async (data) => {
57851
57764
  try {
57852
- await this.consumeTypedDispatch(data.dispatch_event_id ? { dispatchEventId: data.dispatch_event_id } : { sourceType: "task_activity", sourceId: data.id }, (dispatchEventId) => this.handleTaskAssignment(data, data.id, dispatchEventId), {
57853
- legacyAck: (dispatchEventId) => {
57854
- if (dispatchEventId) {
57855
- return this.ackDispatchEvent(dispatchEventId, () => {
57856
- this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
57857
- });
57858
- }
57859
- return this.opts.client.ackDispatch(this.opts.config.org_id, {
57860
- source_type: "task_activity",
57861
- source_id: data.id
57862
- }).then(() => true, (err) => {
57863
- this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
57864
- this.opts.log?.warn(`dispatch ack failed for task ${data.id}, releasing for re-drive: ${String(err)}`);
57865
- return false;
57866
- });
57867
- },
57868
- clearDedupe: () => this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`)
57869
- });
57765
+ await this.consumeWorkItem(data);
57870
57766
  } catch (err) {
57871
- this.opts.log?.error(`task dispatch failed for ${data.id}: ${String(err)}`);
57872
- }
57873
- });
57874
- ws.on("dispatch.new", async (data) => {
57875
- if (data.event_type !== "message" && this.isBufferedTypedWorkItem(data.id)) {
57876
- this.opts.log?.info(`typed dispatch ${data.id} already buffered for the drain \u2014 skipping re-claim`);
57877
- return;
57878
- }
57879
- if (data.event_type === "task_assign") {
57880
- if (!data.task_id)
57881
- return;
57882
- try {
57883
- await this.handleTaskAssignmentRedrive(data);
57884
- } catch (err) {
57885
- this.opts.log?.error(`task assignment re-drive failed for ${data.task_id}: ${String(err)}`);
57886
- }
57887
- } else if (data.event_type === "task_comment") {
57888
- if (!data.source_id || !data.task_id)
57889
- return;
57890
- try {
57891
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleTaskComment(data.source_id, data.task_id ?? "", data.actor_id, data.delivery_reason, dispatchEventId), {
57892
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57893
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57894
- });
57895
- } catch (err) {
57896
- this.opts.log?.error(`task comment dispatch failed for ${data.source_id}: ${String(err)}`);
57897
- }
57898
- } else if (data.event_type === "wiki_comment") {
57899
- if (!data.source_id)
57900
- return;
57901
- try {
57902
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleWikiComment(data.source_id, data.actor_id, data.delivery_reason, dispatchEventId), {
57903
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57904
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57905
- });
57906
- } catch (err) {
57907
- this.opts.log?.error(`wiki comment dispatch failed for ${data.source_id}: ${String(err)}`);
57908
- }
57909
- } else if (data.event_type === "task_update") {
57910
- if (!data.task_id)
57911
- return;
57912
- try {
57913
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleTaskDispatch(data.task_id ?? "", data.source_id ?? data.task_id ?? "", {
57914
- allowCreator: true,
57915
- dispatchEventId
57916
- }), {
57917
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57918
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57919
- });
57920
- } catch (err) {
57921
- this.opts.log?.error(`task update dispatch failed for ${data.task_id}: ${String(err)}`);
57922
- }
57923
- } else if (data.event_type === "schedule.fire") {
57924
- if (!data.source_id)
57925
- return;
57926
- try {
57927
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleScheduleFire(data.source_id, data.actor_id, dispatchEventId), {
57928
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57929
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57930
- });
57931
- } catch (err) {
57932
- this.opts.log?.error(`schedule fire dispatch failed for ${data.source_id}: ${String(err)}`);
57933
- }
57934
- } else if (data.event_type === "external_trigger") {
57935
- if (!data.source_id)
57936
- return;
57937
- try {
57938
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleExternalTriggerRun(data.source_id, dispatchEventId), {
57939
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57940
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57941
- });
57942
- } catch (err) {
57943
- this.opts.log?.error(`external trigger dispatch failed for ${data.source_id}: ${String(err)}`);
57944
- }
57945
- } else if (data.event_type === "channel_message") {
57946
- if (!data.source_id)
57947
- return;
57948
- try {
57949
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleChannelMessage(data.source_id, dispatchEventId), {
57950
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57951
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57952
- });
57953
- } catch (err) {
57954
- this.opts.log?.error(`channel message dispatch failed for ${data.source_id}: ${String(err)}`);
57955
- }
57956
- } else if (data.event_type === "approval_decided") {
57957
- if (!data.source_id)
57958
- return;
57959
- try {
57960
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleApprovalDecided(data.source_id, data.actor_id, data.chat_id ?? null, dispatchEventId), {
57961
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57962
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57963
- });
57964
- } catch (err) {
57965
- this.opts.log?.error(`approval decided dispatch failed for ${data.source_id}: ${String(err)}`);
57966
- }
57967
- } else if (data.event_type === "message" && this.laneLedger && data.source_id && data.chat_id) {
57968
- try {
57969
- await this.handleMessageRedrive(data);
57970
- } catch (err) {
57971
- this.opts.log?.error(`message re-drive failed for ${data.source_id}: ${String(err)}`);
57972
- }
57973
- } else if (data.event_type !== "message") {
57974
- this.opts.log?.info(`dispatch.new with unhandled event_type=${String(data.event_type)} (id=${data.id}) \u2014 no-op`);
57767
+ this.opts.log?.error(`dispatch ${data.id} (${String(data.event_type)}) failed: ${String(err)}`);
57975
57768
  }
57976
57769
  });
57977
57770
  this.opts.log?.info(`connecting to ${this.opts.connectionLabel ?? "Parall WS"}...`);
@@ -58156,44 +57949,6 @@ var ParallAgentGateway = class {
58156
57949
  isTypedEventBuffered(event) {
58157
57950
  return this.isBufferedTypedWorkItem(event.dispatchEventId);
58158
57951
  }
58159
- // PARITY: this switch and gateway-lane-flow's clearTypedDedupeForEvent must
58160
- // handle the same typed source families — extend BOTH when adding a typed
58161
- // event type (same dedupe entries, keyed from different event shapes).
58162
- clearTypedDispatchDedupe(item) {
58163
- switch (item.event_type) {
58164
- case "task_assign":
58165
- case "task_update":
58166
- if (item.task_id) {
58167
- const prefix = `${item.task_id}:`;
58168
- for (const key of this.dispatchedTasks) {
58169
- if (key.startsWith(prefix))
58170
- this.dispatchedTasks.delete(key);
58171
- }
58172
- }
58173
- break;
58174
- case "task_comment":
58175
- case "wiki_comment":
58176
- if (item.source_id)
58177
- this.dispatchedTasks.delete(`comment:${item.source_id}`);
58178
- break;
58179
- case "schedule.fire":
58180
- if (item.source_id)
58181
- this.dispatchedTasks.delete(`schedule_run:${item.source_id}`);
58182
- break;
58183
- case "external_trigger":
58184
- if (item.source_id)
58185
- this.dispatchedTasks.delete(`external_trigger_run:${item.source_id}`);
58186
- break;
58187
- case "channel_message":
58188
- if (item.source_id)
58189
- this.dispatchedMessages.delete(`channel_message:${item.source_id}`);
58190
- break;
58191
- case "approval_decided":
58192
- if (item.source_id)
58193
- this.dispatchedTasks.delete(`approval:${item.source_id}`);
58194
- break;
58195
- }
58196
- }
58197
57952
  buildDispatchContext(event, sessionKey) {
58198
57953
  const binding = this.sessionBindings.get(sessionKey);
58199
57954
  return {
@@ -58206,7 +57961,7 @@ var ParallAgentGateway = class {
58206
57961
  runtimeKey: this.opts.runtimeKey,
58207
57962
  sessionId: binding?.agentSessionId,
58208
57963
  chatId: event.type === "message" || event.type === "approval" ? event.targetId : void 0,
58209
- triggerMessageId: event.messageId,
57964
+ triggerMessageId: splitChangeSource(event.messageId).messageId,
58210
57965
  noReply: event.noReply ?? false,
58211
57966
  contextFilePath: this.opts.contextFilePathForSession?.(sessionKey),
58212
57967
  stepIdFilePath: this.opts.stepIdFilePathForSession?.(sessionKey),
@@ -58220,35 +57975,24 @@ var ParallAgentGateway = class {
58220
57975
  }
58221
57976
  async createInputStep(sessionId, event) {
58222
57977
  const target = resolveStepTarget(event);
57978
+ const input = event.input;
58223
57979
  await this.stepPersister.persist(sessionId, "input", {
58224
57980
  step_type: "input",
58225
57981
  target_type: target.target_type,
58226
57982
  target_id: target.target_id,
58227
57983
  idempotency_key: inputStepIdempotencyKey(event),
58228
57984
  content: {
58229
- trigger_type: event.type === "task" ? "task_assign" : event.type === "task_comment" ? "task_comment" : event.type === "wiki_comment" ? "wiki_comment" : event.type === "schedule" ? "schedule_fire" : event.type === "external_trigger" ? "external_trigger" : event.type === "channel_message" ? "channel_message" : event.type === "approval" ? "approval_decided" : "mention",
58230
- trigger_ref: event.type === "task" ? { task_id: event.targetId } : event.type === "task_comment" ? { comment_id: event.messageId, task_id: event.targetId } : event.type === "wiki_comment" ? { comment_id: event.messageId, target_uri: event.replyTargetUri } : event.type === "schedule" ? { schedule_id: event.targetId, run_id: event.messageId } : event.type === "external_trigger" ? {
58231
- trigger_id: event.targetId,
58232
- run_id: event.messageId,
58233
- connection_id: event.externalConnectionId,
58234
- ingress_event_id: event.externalIngressEventId
58235
- } : event.type === "channel_message" ? {
58236
- conversation_id: event.targetId,
58237
- channel_message_id: event.messageId,
58238
- provider: event.channelProvider,
58239
- external_conversation_id: event.channelExternalConversationId
58240
- } : event.type === "approval" ? { approval_id: event.messageId } : {
58241
- message_id: event.messageId,
58242
- // Thread context for the session→chat backlink:
58243
- // a thread reply can only be navigated to with
58244
- // its thread root (the chat surface rejects
58245
- // bare thread-message targets).
58246
- ...event.threadRootId ? { thread_root_id: event.threadRootId } : {}
58247
- },
57985
+ // What the server said about the wake (claim `input`), plus the
57986
+ // source pointer and the anchor the web needs to link a chat
57987
+ // message or a task to this session.
57988
+ trigger_type: input?.trigger_type ?? inputTriggerTypeFor(event.type),
57989
+ trigger_ref: inputTriggerRef(event),
57990
+ source_type: event.ackSourceType,
57991
+ source_id: event.ackSourceId ?? event.messageId,
58248
57992
  sender_id: event.senderId,
58249
- sender_name: event.senderName,
58250
- summary: event.body.substring(0, 200),
58251
- ...event.sentAt ? { sent_at: event.sentAt } : {}
57993
+ ...input?.sender_name ? { sender_name: input.sender_name } : {},
57994
+ summary: (input?.summary ?? eventBody(event)).substring(0, 200),
57995
+ ...input?.sent_at ? { sent_at: input.sent_at } : {}
58252
57996
  }
58253
57997
  });
58254
57998
  }
@@ -58760,13 +58504,14 @@ var ParallAgentGateway = class {
58760
58504
  retainForkContinuationRetries(this.forkContinuationRetries, events, fork.continuationPrefix);
58761
58505
  try {
58762
58506
  const batchText = [];
58763
- const body = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last) + buildEventBody(last);
58507
+ const bodyPrefix = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last);
58508
+ const body = bodyPrefix + eventBody(last);
58764
58509
  let dispatched;
58765
58510
  if (this.usesLaneLedger(last)) {
58766
58511
  const outcome = await this.dispatchLaneGroup({
58767
58512
  events,
58768
58513
  sessionKey: fork.fork.sessionKey,
58769
- body,
58514
+ bodyPrefix,
58770
58515
  earlier,
58771
58516
  captureText: batchText,
58772
58517
  // Per-LANE residue check (parity with the main-buffer path):
@@ -58841,9 +58586,9 @@ var ParallAgentGateway = class {
58841
58586
  sourceEvent: {
58842
58587
  type: first.type,
58843
58588
  targetId: fork.targetId,
58844
- summary: fork.processedEvents.length === 1 ? `${first.type} from ${first.senderName} in ${first.targetName ?? fork.targetId}` : `${fork.processedEvents.length} events in ${first.targetName ?? fork.targetId}`
58589
+ summary: fork.processedEvents.length === 1 ? `${first.type} in ${fork.targetId}` : `${fork.processedEvents.length} events in ${fork.targetId}`
58845
58590
  },
58846
- eventBodies: fork.processedEvents.map((e) => buildEventBodyForForkResult(e)),
58591
+ eventBodies: fork.processedEvents.map((e) => forkResultBody(e)),
58847
58592
  actions: [],
58848
58593
  agentSummary,
58849
58594
  historyPath
@@ -58914,7 +58659,7 @@ var ParallAgentGateway = class {
58914
58659
  outcome = await this.dispatchLaneGroup({
58915
58660
  events,
58916
58661
  sessionKey: this.opts.runtimeKey,
58917
- body: forkPrefix + buildEventBody(event),
58662
+ bodyPrefix: forkPrefix,
58918
58663
  earlier,
58919
58664
  hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === groupKey)
58920
58665
  });
@@ -58956,16 +58701,14 @@ var ParallAgentGateway = class {
58956
58701
  }
58957
58702
  }
58958
58703
  const isTypedGroup = events.every((ev) => ev.type !== "message");
58959
- const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => buildEventBody(ev)).join("\n\n") : buildEventBody(event);
58704
+ const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => eventBody(ev)).join("\n\n") : eventBody(event);
58960
58705
  let dispatched;
58961
58706
  try {
58962
58707
  dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + body, earlier);
58963
58708
  } catch (err) {
58964
58709
  if (!isTypedGroup)
58965
58710
  throw err;
58966
- this.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}, claims freed for re-drive): ${String(err)}`);
58967
- for (const ev of events)
58968
- clearTypedDedupeForEvent(this.laneFlowHost(), ev);
58711
+ this.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}): ${String(err)}`);
58969
58712
  this.dispatchState.pendingForkResults.unshift(...pendingFork);
58970
58713
  continue;
58971
58714
  }
@@ -58986,7 +58729,6 @@ var ParallAgentGateway = class {
58986
58729
  source_id: sourceId
58987
58730
  }).catch(() => {
58988
58731
  });
58989
- clearTypedDedupeForEvent(this.laneFlowHost(), bufferedEvent);
58990
58732
  }
58991
58733
  } finally {
58992
58734
  for (const id of drainingIds)
@@ -59029,7 +58771,7 @@ var ParallAgentGateway = class {
59029
58771
  outcome = await this.dispatchLaneGroup({
59030
58772
  events: [event],
59031
58773
  sessionKey: this.opts.runtimeKey,
59032
- body: forkPrefix + buildEventBody(event),
58774
+ bodyPrefix: forkPrefix,
59033
58775
  earlier: [],
59034
58776
  hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === this.dispatchGroupKey(event))
59035
58777
  });
@@ -59061,7 +58803,7 @@ var ParallAgentGateway = class {
59061
58803
  }
59062
58804
  let dispatched = false;
59063
58805
  try {
59064
- dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + buildEventBody(event));
58806
+ dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + eventBody(event));
59065
58807
  if (dispatched && typedRefs && this.consumeTurnError(this.opts.runtimeKey)) {
59066
58808
  this.opts.log?.info(`typed dispatch turn for ${event.messageId} surfaced a runtime error \u2014 releasing for retry`);
59067
58809
  dispatched = false;
@@ -59095,7 +58837,7 @@ var ParallAgentGateway = class {
59095
58837
  // the WorkItem stays live, and every re-drive injects it AGAIN (the
59096
58838
  // 7/16 watcher duplicate-delivery loop, #1149). Typed events stay
59097
58839
  // buffered; the drain claims them as their own turn.
59098
- event.type === "message" && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, buildEventBody(event))
58840
+ event.type === "message" && event.frame != null && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, eventBody(event))
59099
58841
  ) {
59100
58842
  this.opts.log?.info(`steer injected for ${event.messageId} (will drain for bookkeeping)`);
59101
58843
  }
@@ -59156,605 +58898,75 @@ var ParallAgentGateway = class {
59156
58898
  }
59157
58899
  }
59158
58900
  }
59159
- async getOrFetchChatInfo(chatId) {
59160
- const cached = this.chatInfoMap.get(chatId);
59161
- if (cached)
59162
- return cached;
59163
- try {
59164
- const chat = await this.opts.client.getChat(this.opts.config.org_id, chatId);
59165
- const chatInfo = {
59166
- type: chat.type,
59167
- name: chat.name ?? null,
59168
- agentRoutingMode: chat.agent_routing_mode
59169
- };
59170
- this.chatInfoMap.set(chatId, chatInfo);
59171
- return chatInfo;
59172
- } catch (err) {
59173
- this.opts.log?.warn(`failed to resolve chat ${chatId}: ${String(err)}`);
59174
- return null;
59175
- }
59176
- }
59177
- async buildMessageDispatchDecision(chatId, message) {
59178
- if (message.message_type !== "text") {
59179
- return { action: "skip" };
59180
- }
59181
- const chatInfo = await this.getOrFetchChatInfo(chatId);
59182
- if (!chatInfo)
59183
- return { action: "retry" };
59184
- const content = message.content;
59185
- const body = content.text?.trim() ?? "";
59186
- const hasAttachments = message.attachments?.length;
59187
- if (!body && !hasAttachments)
59188
- return { action: "skip" };
59189
- const mentions = content.mentions ?? [];
59190
- const isMentioned = mentions.some((mention) => mentionTargetsUser(mention.user_id, this.opts.agentUserId, "agent"));
59191
- let deliveryReason;
59192
- if (message.thread_root_id) {
59193
- if (isMentioned) {
59194
- deliveryReason = "mention";
59195
- } else {
59196
- let watching;
59197
- try {
59198
- watching = await this.opts.client.isWatchingThread(message.thread_root_id);
59199
- } catch {
59200
- return { action: "retry" };
59201
- }
59202
- if (!watching)
59203
- return { action: "skip" };
59204
- deliveryReason = "watcher";
59205
- }
59206
- } else if (chatInfo.type === "group") {
59207
- if (chatInfo.agentRoutingMode !== "active" && !isMentioned)
59208
- return { action: "skip" };
59209
- if (isMentioned)
59210
- deliveryReason = "mention";
59211
- }
59212
- const attachments = (message.attachments ?? []).map((a) => ({
59213
- id: a.id,
59214
- fileName: a.file_name,
59215
- fileSize: a.file_size,
59216
- mimeType: a.mime_type
59217
- }));
59218
- let unreadCount;
59219
- let unreadSince;
59220
- let threadReplyCount;
59221
- let threadUnreadCount;
59222
- let threadUnreadSince;
59223
- const isPassiveOrSmart = chatInfo.type === "group" && chatInfo.agentRoutingMode !== "active";
59224
- const unreadPromise = isPassiveOrSmart ? this.opts.client.getUnreadCounts(this.opts.config.org_id).catch(() => void 0) : Promise.resolve(void 0);
59225
- 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);
59226
- const [counts, threadUnread] = await Promise.all([unreadPromise, threadPromise]);
59227
- if (counts) {
59228
- const entry = counts[chatId];
59229
- if (entry && entry.count > 1) {
59230
- unreadCount = entry.count;
59231
- unreadSince = entry.since;
59232
- }
59233
- }
59234
- if (threadUnread) {
59235
- threadReplyCount = threadUnread.total;
59236
- threadUnreadCount = threadUnread.unread > 0 ? threadUnread.unread : void 0;
59237
- threadUnreadSince = threadUnread.since ?? void 0;
59238
- }
59239
- return {
59240
- action: "dispatch",
59241
- event: {
59242
- type: "message",
59243
- targetId: chatId,
59244
- targetName: chatInfo.name ?? void 0,
59245
- targetType: chatInfo.type,
59246
- senderId: message.sender_id,
59247
- senderName: message.sender?.display_name ?? message.sender_id,
59248
- messageId: message.id,
59249
- body: body || "[attachment]",
59250
- threadRootId: message.thread_root_id ?? void 0,
59251
- deliveryReason,
59252
- noReply: message.hints?.no_reply ?? false,
59253
- attachments: attachments.length > 0 ? attachments : void 0,
59254
- sentAt: message.created_at,
59255
- ackSourceType: "message",
59256
- ackSourceId: message.id,
59257
- unreadCount,
59258
- unreadSince,
59259
- threadReplyCount,
59260
- threadUnreadCount,
59261
- threadUnreadSince
59262
- }
59263
- };
59264
- }
59265
- async handleMessage(data) {
58901
+ /**
58902
+ * One WorkItem the server pushed (dispatch.new) or a catch-up page
58903
+ * listed: messages ride their (chat, thread) lane; every other family
58904
+ * rides its own dsp lane, claimed, run on the server frame, resolved by
58905
+ * id. A typed WorkItem whose event copy is already buffered for the
58906
+ * drain is left to the drain (re-claiming it would race the drain's
58907
+ * fence-less settlement).
58908
+ */
58909
+ async consumeWorkItem(item) {
58910
+ await this.contractReady;
59266
58911
  if (this.shuttingDown)
59267
58912
  return;
59268
- const chatId = data.chat_id;
59269
- if (data.sender_id === this.opts.agentUserId)
59270
- return;
59271
- if (data.message_type !== "text")
59272
- return;
59273
- if (!this.tryClaimMessage(data.id))
59274
- return;
59275
- const decision = await this.buildMessageDispatchDecision(chatId, data);
59276
- if (decision.action !== "dispatch") {
59277
- this.dispatchedMessages.delete(data.id);
58913
+ if (item.event_type === "message") {
58914
+ if (!item.chat_id || !item.source_id)
58915
+ return;
58916
+ await this.consumeMessageWorkItem({
58917
+ id: item.id,
58918
+ source_id: item.source_id,
58919
+ chat_id: item.chat_id,
58920
+ actor_id: item.actor_id,
58921
+ thread_root_id: item.thread_root_id,
58922
+ delivery_reason: item.delivery_reason
58923
+ });
59278
58924
  return;
59279
58925
  }
59280
- const event = decision.event;
59281
- try {
59282
- const dispatched = await this.handleInboundEvent(event);
59283
- if (dispatched) {
59284
- if (!this.usesLaneLedger(event)) {
59285
- this.opts.client.ackDispatch(this.opts.config.org_id, { source_type: "message", source_id: data.id }).catch(() => {
59286
- });
59287
- }
59288
- } else {
59289
- this.dispatchedMessages.delete(data.id);
59290
- }
59291
- } catch (err) {
59292
- this.opts.log?.error(`event dispatch failed for ${data.id}: ${String(err)}`);
59293
- this.dispatchedMessages.delete(data.id);
59294
- }
59295
- }
59296
- // Ledger re-drive consumption: dispatch.new message hints re-enter the
59297
- // shared WorkItem consumption path (same protocol as catch-up).
59298
- async handleMessageRedrive(item) {
59299
- if (!item.chat_id || !item.source_id)
58926
+ if (!TYPED_EVENT_KINDS[item.event_type]) {
58927
+ this.opts.log?.info(`dispatch with unhandled event_type=${String(item.event_type)} (id=${item.id}) \u2014 no-op`);
59300
58928
  return;
59301
- await this.consumeMessageWorkItem({
59302
- id: item.id,
59303
- source_id: item.source_id,
59304
- chat_id: item.chat_id
59305
- });
59306
- }
59307
- // A task assignment's first delivery rides task.assigned, but a typed lane
59308
- // released without an effect is re-driven as dispatch.new. Reuse the exact
59309
- // typed claim path used by catch-up so that recovery does not require a
59310
- // runtime reconnect.
59311
- async handleTaskAssignmentRedrive(item) {
59312
- if (!item.task_id)
58929
+ }
58930
+ if (this.isBufferedTypedWorkItem(item.id)) {
58931
+ this.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping re-claim`);
59313
58932
  return;
59314
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
59315
- dispatchEventId
59316
- }), {
59317
- legacyAck: (dispatchEventId) => this.ackDispatchEvent(dispatchEventId ?? item.id, () => this.clearTypedDispatchDedupe(item)),
59318
- clearDedupe: () => this.clearTypedDispatchDedupe(item)
59319
- });
58933
+ }
58934
+ await this.consumeTypedDispatch({ dispatchEventId: item.id }, (lane) => this.runTypedFrame(item, lane), { legacyAck: () => this.ackDispatchEvent(item.id) });
59320
58935
  }
59321
58936
  consumeMessageWorkItem(item) {
59322
58937
  return consumeMessageWorkItem(this.laneFlowHost(), item);
59323
58938
  }
59324
- async handleTaskAssignment(task, ackSourceId, dispatchEventId) {
59325
- if (this.shuttingDown)
59326
- return false;
59327
- const dedupeKey = `${task.id}:${task.updated_at}`;
59328
- if (this.dispatchedTasks.has(dedupeKey)) {
59329
- this.opts.log?.info(`skipping already-dispatched task ${task.identifier ?? task.id}`);
59330
- return false;
59331
- }
59332
- this.dispatchedTasks.add(dedupeKey);
59333
- this.opts.log?.info(`task assigned: ${task.identifier ?? task.id} "${task.title}"`);
59334
- const parts = [`Title: ${task.title}`];
59335
- parts.push(`Status: ${task.status}`, `Priority: ${task.priority}`);
59336
- if (task.project_id)
59337
- parts.push(`Project: prll://${task.project_id}`);
59338
- if (task.parent_id)
59339
- parts.push(`Parent: prll://${task.parent_id}`);
59340
- if (task.description)
59341
- parts.push("", task.description);
59342
- const event = {
59343
- type: "task",
59344
- targetId: task.id,
59345
- targetName: task.identifier ?? void 0,
59346
- targetType: "task",
59347
- senderId: task.creator_id,
59348
- senderName: "system",
59349
- messageId: task.id,
59350
- body: parts.join("\n"),
59351
- sentAt: task.updated_at ?? task.created_at,
59352
- ackSourceType: "task_activity",
59353
- ackSourceId,
59354
- dispatchEventId
59355
- };
59356
- const dispatched = await this.handleInboundEvent(event);
59357
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59358
- this.dispatchedTasks.delete(dedupeKey);
59359
- }
59360
- return dispatched;
59361
- }
59362
- async handleTaskDispatch(taskId, ackSourceId, opts = {}) {
59363
- let task = null;
59364
- try {
59365
- task = await this.opts.client.getTask(this.opts.config.org_id, taskId);
59366
- } catch (err) {
59367
- const status = err?.status;
59368
- if (status === 404)
59369
- return true;
59370
- throw err;
59371
- }
59372
- const isAssignee = task.assignee_id === this.opts.agentUserId;
59373
- const isCreatorUpdate = opts.allowCreator === true && task.creator_id === this.opts.agentUserId;
59374
- if (!isAssignee && !isCreatorUpdate) {
59375
- this.opts.log?.info(`skipping stale task dispatch ${ackSourceId ?? taskId} \u2014 assigned to ${task.assignee_id}, creator ${task.creator_id}`);
59376
- return true;
59377
- }
59378
- return this.handleTaskAssignment(task, ackSourceId, opts.dispatchEventId);
59379
- }
59380
- async handleTaskComment(commentId, taskId, actorId, deliveryReason, dispatchEventId) {
59381
- if (this.shuttingDown)
59382
- return false;
59383
- const dedupeKey = `comment:${commentId}`;
59384
- if (this.dispatchedTasks.has(dedupeKey))
59385
- return false;
59386
- this.dispatchedTasks.add(dedupeKey);
59387
- let comment = null;
59388
- try {
59389
- comment = await this.opts.client.getComment(this.opts.config.org_id, commentId);
59390
- } catch (err) {
59391
- const status = err?.status;
59392
- if (status === 404) {
59393
- this.opts.log?.info(`skipping deleted comment ${commentId}, acking stale dispatch`);
59394
- this.dispatchedTasks.delete(dedupeKey);
59395
- return true;
59396
- }
59397
- this.dispatchedTasks.delete(dedupeKey);
59398
- return false;
59399
- }
59400
- if (!comment) {
59401
- this.dispatchedTasks.delete(dedupeKey);
59402
- return true;
59403
- }
59404
- if (comment.hints?.no_reply) {
59405
- this.opts.log?.info(`skipping no_reply task comment ${commentId}, acking stale dispatch`);
59406
- this.dispatchedTasks.delete(dedupeKey);
59407
- return true;
59408
- }
59409
- let task = null;
59410
- try {
59411
- task = await this.opts.client.getTask(this.opts.config.org_id, taskId);
59412
- } catch {
59413
- }
59414
- const taskLabel = task ? `${task.identifier ?? task.id} "${task.title}"` : taskId;
59415
- this.opts.log?.info(`task comment on ${taskLabel} by ${actorId ?? "unknown"}`);
59416
- const parts = [];
59417
- if (task) {
59418
- parts.push(`Task: ${task.title} (prll://${task.id})`);
59419
- parts.push(`Status: ${task.status}`, `Priority: ${task.priority}`);
59420
- } else {
59421
- parts.push(`Task: prll://${taskId}`);
59422
- }
59423
- parts.push(`Comment by: ${comment.author?.display_name ?? actorId ?? "unknown"} (prll://${comment.author_id})`);
59424
- parts.push("", comment.body);
59425
- const event = {
59426
- type: "task_comment",
59427
- targetId: taskId,
59428
- targetName: task?.identifier ?? void 0,
59429
- targetType: "task",
59430
- senderId: comment.author_id,
59431
- senderName: comment.author?.display_name ?? actorId ?? "unknown",
59432
- messageId: commentId,
59433
- body: parts.join("\n"),
59434
- deliveryReason: deliveryReason ?? void 0,
59435
- ackSourceType: "comment",
59436
- ackSourceId: commentId,
59437
- dispatchEventId
59438
- };
59439
- let dispatched;
59440
- try {
59441
- dispatched = await this.handleInboundEvent(event);
59442
- } catch (err) {
59443
- this.dispatchedTasks.delete(dedupeKey);
59444
- throw err;
59445
- }
59446
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59447
- this.dispatchedTasks.delete(dedupeKey);
59448
- }
59449
- return dispatched;
59450
- }
59451
- async handleWikiComment(commentId, actorId, deliveryReason, dispatchEventId) {
59452
- if (this.shuttingDown)
59453
- return false;
59454
- const dedupeKey = `comment:${commentId}`;
59455
- if (this.dispatchedTasks.has(dedupeKey))
59456
- return false;
59457
- this.dispatchedTasks.add(dedupeKey);
59458
- let comment = null;
59459
- try {
59460
- comment = await this.opts.client.getComment(this.opts.config.org_id, commentId);
59461
- } catch (err) {
59462
- const status = err?.status;
59463
- if (status === 404 || status === 403) {
59464
- this.opts.log?.info(`skipping inaccessible wiki comment ${commentId} (status ${status}), acking stale dispatch`);
59465
- this.dispatchedTasks.delete(dedupeKey);
59466
- return true;
59467
- }
59468
- this.dispatchedTasks.delete(dedupeKey);
59469
- return false;
59470
- }
59471
- if (!comment) {
59472
- this.dispatchedTasks.delete(dedupeKey);
59473
- return true;
59474
- }
59475
- if (comment.hints?.no_reply) {
59476
- this.opts.log?.info(`skipping no_reply wiki comment ${commentId}, acking stale dispatch`);
59477
- this.dispatchedTasks.delete(dedupeKey);
59478
- return true;
59479
- }
59480
- const target = parseWikiCommentTarget(comment.target_uri);
59481
- this.opts.log?.info(`wiki comment on ${target.label} by ${actorId ?? "unknown"}`);
59482
- const event = {
59483
- type: "wiki_comment",
59484
- // Full target_uri (scheme-stripped) is the routing key so different
59485
- // pages / inline anchors / changesets in the same wiki don't collide on
59486
- // one gateway lane. replyTargetUri keeps the canonical prll:// form.
59487
- targetId: target.routingKey,
59488
- targetName: target.label,
59489
- targetType: target.targetType,
59490
- senderId: comment.author_id,
59491
- senderName: comment.author?.display_name ?? actorId ?? "unknown",
59492
- messageId: commentId,
59493
- body: comment.body,
59494
- deliveryReason: deliveryReason ?? void 0,
59495
- replyTargetUri: comment.target_uri,
59496
- ackSourceType: "comment",
59497
- ackSourceId: commentId,
59498
- dispatchEventId
59499
- };
59500
- let dispatched;
59501
- try {
59502
- dispatched = await this.handleInboundEvent(event);
59503
- } catch (err) {
59504
- this.dispatchedTasks.delete(dedupeKey);
59505
- throw err;
59506
- }
59507
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59508
- this.dispatchedTasks.delete(dedupeKey);
59509
- }
59510
- return dispatched;
59511
- }
59512
58939
  /**
59513
- * Fetch the schedule_run snapshot, then feed it as an inbound event. 404 is
59514
- * tolerated and treated as "dispatched" so the caller can ack the stale
59515
- * deliverysee `docs/primitives/schedule.md` § "Snapshot 不变性: 内容 vs
59516
- * 可见性". A later PATCH on target_id / attached_to_uri legitimately revokes
59517
- * access to already-delivered run snapshots, and the runtime must not crash
59518
- * or retry forever in that case.
58940
+ * Run one claimed typed WorkItem on the frame the claim returned. The
58941
+ * event is addressing only: the routing target the server named
58942
+ * (`input.subject`the task, the wiki target, the schedule, the
58943
+ * conversation, the chat an approval belongs to), the ids the ledger
58944
+ * keys on, and the input-step metadata. No frame means nothing to run.
59519
58945
  */
59520
- async fetchAndHandleScheduleFire(runId, actorId, dispatchEventId) {
59521
- let run = null;
59522
- try {
59523
- run = await this.opts.client.getScheduleRun(this.opts.config.org_id, runId);
59524
- } catch (err) {
59525
- const status = err?.status;
59526
- if (status === 404) {
59527
- this.opts.log?.warn(`schedule run ${runId} not accessible (404), acking stale dispatch`);
59528
- return true;
59529
- }
59530
- this.opts.log?.warn(`schedule run fetch failed for ${runId}, leaving pending: ${String(err)}`);
59531
- return false;
59532
- }
59533
- if (!run)
59534
- return true;
59535
- return this.handleScheduleFire(run, actorId, dispatchEventId);
59536
- }
59537
- async handleScheduleFire(run, actorId, dispatchEventId) {
58946
+ async runTypedFrame(item, lane) {
59538
58947
  if (this.shuttingDown)
59539
58948
  return false;
59540
- const dedupeKey = `schedule_run:${run.id}`;
59541
- if (this.dispatchedTasks.has(dedupeKey))
59542
- return false;
59543
- this.dispatchedTasks.add(dedupeKey);
59544
- this.opts.log?.info(`schedule fired: ${run.id} (schedule ${run.schedule_id})`);
59545
- const event = {
59546
- type: "schedule",
59547
- // Route by schedule_id (not attached chat_id) so concurrent fires of
59548
- // different schedules can fork independently — matches the PR1 primitive
59549
- // design where "schedule triggers; target decides response" and fire
59550
- // semantics are independent of any attached conversation.
59551
- targetId: run.schedule_id,
59552
- targetType: "schedule",
59553
- senderId: actorId ?? "system",
59554
- senderName: "schedule",
59555
- messageId: run.id,
59556
- body: run.fired_description ?? "",
59557
- scheduledFireAt: run.scheduled_fire_at,
59558
- attachedUri: run.fired_attached_uri ?? void 0,
59559
- ackSourceType: "schedule_run",
59560
- ackSourceId: run.id,
59561
- dispatchEventId
59562
- };
59563
- let dispatched;
59564
- try {
59565
- dispatched = await this.handleInboundEvent(event);
59566
- } catch (err) {
59567
- this.dispatchedTasks.delete(dedupeKey);
59568
- throw err;
59569
- }
59570
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59571
- this.dispatchedTasks.delete(dedupeKey);
59572
- }
59573
- return dispatched;
59574
- }
59575
- async fetchAndHandleExternalTriggerRun(runId, dispatchEventId) {
59576
- let run = null;
59577
- try {
59578
- run = await this.opts.client.getExternalTriggerRun(this.opts.config.org_id, runId);
59579
- } catch (err) {
59580
- const status = err?.status;
59581
- if (status === 404) {
59582
- this.opts.log?.warn(`external trigger run ${runId} not accessible (404), acking stale dispatch`);
59583
- return true;
59584
- }
59585
- this.opts.log?.warn(`external trigger run fetch failed for ${runId}, leaving pending: ${String(err)}`);
59586
- return false;
59587
- }
59588
- if (!run)
59589
- return true;
59590
- return this.handleExternalTriggerRun(run, dispatchEventId);
59591
- }
59592
- // fetchAndHandleChannelMessage resolves a channel_message dispatch to its
59593
- // durable ChannelMessage + conversation and hands it to the inbound
59594
- // pipeline. targetId = the ChannelConversation id, so per-conversation
59595
- // multi-turn continuity rides the same per-target session mechanics as
59596
- // chats. Design: docs/engineering-design/external-im-channel-design.md.
59597
- async fetchAndHandleChannelMessage(messageId, dispatchEventId) {
59598
- if (this.shuttingDown)
59599
- return false;
59600
- const claimKey = `channel_message:${messageId}`;
59601
- if (!this.tryClaimMessage(claimKey))
59602
- return false;
59603
- let msg = null;
59604
- let conv = null;
59605
- try {
59606
- msg = await this.opts.client.getChannelMessage(this.opts.config.org_id, messageId);
59607
- conv = await this.opts.client.getChannelConversation(this.opts.config.org_id, msg.conversation_id);
59608
- } catch (err) {
59609
- const status = err?.status;
59610
- if (status === 404) {
59611
- this.opts.log?.warn(`channel message ${messageId} not accessible (404), acking stale dispatch`);
59612
- return true;
59613
- }
59614
- this.dispatchedMessages.delete(claimKey);
59615
- this.opts.log?.warn(`channel message fetch failed for ${messageId}, leaving pending: ${String(err)}`);
59616
- return false;
59617
- }
59618
- if (!msg || !conv) {
59619
- return true;
59620
- }
59621
- this.opts.log?.info(`channel message: ${msg.id} (conversation ${conv.id})`);
59622
- let provider = this.channelConnectionProviders.get(conv.connection_id);
59623
- if (!provider) {
59624
- try {
59625
- const connection = await this.opts.client.getChannelConnection(this.opts.config.org_id, conv.connection_id);
59626
- provider = connection.provider;
59627
- this.channelConnectionProviders.set(conv.connection_id, provider);
59628
- } catch {
59629
- provider = void 0;
59630
- }
59631
- }
59632
- const keys = this.opts.getCapabilityKeys?.() ?? [];
59633
- const cliCapable = provider ? keys.includes(channelCapabilityKeyFor(provider)) : keys.some((k) => k.endsWith("-cli") || k === CAPABILITY_SLACK_SEND || k === CAPABILITY_WECHAT_SEND);
59634
- const event = {
59635
- type: "channel_message",
59636
- targetId: conv.id,
59637
- targetName: conv.external_conversation_name || conv.external_user_name || conv.external_conversation_id,
59638
- targetType: "channel_conversation",
59639
- senderId: msg.external_user_id || "external",
59640
- senderName: msg.external_user_name || msg.external_user_id || "external user",
59641
- messageId: msg.id,
59642
- body: msg.text,
59643
- sentAt: msg.received_at,
59644
- channelProvider: provider,
59645
- channelConversationType: conv.conversation_type || void 0,
59646
- channelExternalConversationId: conv.external_conversation_id,
59647
- channelExternalConversationName: conv.external_conversation_name || void 0,
59648
- channelExternalMessageId: msg.external_message_id,
59649
- channelCliCapable: cliCapable,
59650
- ackSourceType: "channel_message",
59651
- ackSourceId: msg.id,
59652
- dispatchEventId
59653
- };
59654
- let dispatched;
59655
- try {
59656
- dispatched = await this.handleInboundEvent(event);
59657
- } catch (err) {
59658
- this.dispatchedMessages.delete(claimKey);
59659
- throw err;
59660
- }
59661
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59662
- this.dispatchedMessages.delete(claimKey);
59663
- }
59664
- return dispatched;
59665
- }
59666
- async handleExternalTriggerRun(run, dispatchEventId) {
59667
- if (this.shuttingDown)
59668
- return false;
59669
- const dedupeKey = `external_trigger_run:${run.id}`;
59670
- if (this.dispatchedTasks.has(dedupeKey))
59671
- return false;
59672
- this.dispatchedTasks.add(dedupeKey);
59673
- this.opts.log?.info(`external trigger fired: ${run.id} (trigger ${run.trigger_id})`);
59674
- const attachedUri = typeof run.trigger_snapshot?.attached_to_uri === "string" ? run.trigger_snapshot.attached_to_uri : void 0;
59675
- const event = {
59676
- type: "external_trigger",
59677
- targetId: run.trigger_id,
59678
- targetName: run.trigger_name || void 0,
59679
- targetType: "external_trigger",
59680
- senderId: "system",
59681
- senderName: "external",
59682
- messageId: run.id,
59683
- body: run.agent_input_body ?? "",
59684
- externalConnectionId: run.connection_id,
59685
- externalConnectionSourceType: run.connection_source_type || void 0,
59686
- externalConnectionDisplayName: run.connection_display_name || void 0,
59687
- externalIngressEventId: run.ingress_event_id,
59688
- externalIngressEventType: run.ingress_event_type || void 0,
59689
- attachedUri,
59690
- ackSourceType: "external_trigger_run",
59691
- ackSourceId: run.id,
59692
- dispatchEventId
59693
- };
59694
- let dispatched;
59695
- try {
59696
- dispatched = await this.handleInboundEvent(event);
59697
- } catch (err) {
59698
- this.dispatchedTasks.delete(dedupeKey);
59699
- throw err;
59700
- }
59701
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59702
- this.dispatchedTasks.delete(dedupeKey);
59703
- }
59704
- return dispatched;
59705
- }
59706
- async fetchAndHandleApprovalDecided(approvalId, actorId, chatId, dispatchEventId) {
59707
- let approval = null;
59708
- try {
59709
- approval = await this.opts.client.getApproval(approvalId);
59710
- } catch (err) {
59711
- const status = err?.status;
59712
- if (status === 404 || status === 403) {
59713
- this.opts.log?.warn(`approval ${approvalId} not accessible (${status}), acking stale dispatch`);
59714
- return true;
59715
- }
59716
- this.opts.log?.warn(`approval fetch failed for ${approvalId}, leaving pending: ${String(err)}`);
58949
+ const wake = this.laneLedger?.takeFrame(lane);
58950
+ if (!wake?.frame) {
58951
+ this.opts.log?.warn(`typed dispatch ${item.id} (${String(item.event_type)}) claimed without a frame \u2014 leaving it pending`);
59717
58952
  return false;
59718
58953
  }
59719
- if (!approval)
59720
- return true;
59721
- if (this.shuttingDown)
59722
- return false;
59723
- const dedupeKey = `approval:${approval.id}`;
59724
- if (this.dispatchedTasks.has(dedupeKey))
59725
- return false;
59726
- this.dispatchedTasks.add(dedupeKey);
59727
- this.opts.log?.info(`approval decided: ${approval.id} (${approval.status})`);
59728
- const statusLabel = approval.status === "approved" ? "Approved" : "Rejected";
59729
- const execInfo = approval.execution_status ? ` | execution: ${approval.execution_status}` : "";
59730
- const reasonLine = formatApprovalDecisionReason(approval.status, approval.decision_reason);
59731
- const reasonInfo = reasonLine ? `
59732
- ${reasonLine}` : "";
59733
- const body = `${statusLabel}: ${approval.title}${execInfo}${reasonInfo}`;
58954
+ const kind = TYPED_EVENT_KINDS[item.event_type];
58955
+ const targetId = wake.input?.subject || item.task_id || item.chat_id || item.source_id || item.id;
59734
58956
  const event = {
59735
- type: "approval",
59736
- targetId: chatId ?? approval.chat_id,
59737
- senderId: actorId ?? approval.decided_by ?? "system",
59738
- senderName: "approver",
59739
- messageId: approval.id,
59740
- body,
59741
- // The WorkItem's real source pair. Without it the legacy fallback
59742
- // guessed ('message', approval_id) — a pair no row matches.
59743
- ackSourceType: "approval",
59744
- ackSourceId: approval.id,
59745
- dispatchEventId
59746
- };
59747
- let dispatched;
59748
- try {
59749
- dispatched = await this.handleInboundEvent(event);
59750
- } catch (err) {
59751
- this.dispatchedTasks.delete(dedupeKey);
59752
- throw err;
59753
- }
59754
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59755
- this.dispatchedTasks.delete(dedupeKey);
59756
- }
59757
- return dispatched;
58957
+ type: kind.type,
58958
+ targetId,
58959
+ targetType: wake.input?.step_target?.type,
58960
+ senderId: wake.input?.sender_id ?? item.actor_id ?? "system",
58961
+ messageId: item.source_id,
58962
+ deliveryReason: item.delivery_reason ?? void 0,
58963
+ ackSourceType: kind.ackSourceType,
58964
+ ackSourceId: item.source_id,
58965
+ dispatchEventId: item.id
58966
+ };
58967
+ applyWake(event, wake);
58968
+ this.opts.log?.info(`${String(item.event_type)} ${item.source_id} \u2192 ${targetId}`);
58969
+ return this.handleInboundEvent(event);
59758
58970
  }
59759
58971
  async catchUpFromDispatch() {
59760
58972
  const OVERFLOW_THRESHOLD = 500;
@@ -59808,54 +59020,9 @@ ${reasonLine}` : "";
59808
59020
  }
59809
59021
  continue;
59810
59022
  }
59811
- if (item.event_type !== "message" && this.isBufferedTypedWorkItem(item.id)) {
59812
- this.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping catch-up claim`);
59813
- continue;
59814
- }
59815
59023
  processed++;
59816
59024
  try {
59817
- const typedHooks = {
59818
- legacyAck: () => this.ackDispatchEvent(item.id, () => this.clearTypedDispatchDedupe(item)),
59819
- clearDedupe: () => this.clearTypedDispatchDedupe(item)
59820
- };
59821
- if (item.event_type === "task_assign" && item.task_id) {
59822
- try {
59823
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
59824
- dispatchEventId
59825
- }), typedHooks);
59826
- } catch (err) {
59827
- this.opts.log?.warn(`catch-up task fetch failed for ${item.task_id}, leaving pending: ${String(err)}`);
59828
- continue;
59829
- }
59830
- } else if (item.event_type === "task_update" && item.task_id) {
59831
- try {
59832
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
59833
- allowCreator: true,
59834
- dispatchEventId
59835
- }), typedHooks);
59836
- } catch (err) {
59837
- this.opts.log?.warn(`catch-up task fetch failed for ${item.task_id}, leaving pending: ${String(err)}`);
59838
- continue;
59839
- }
59840
- } else if (item.event_type === "task_comment" && item.source_id && item.task_id) {
59841
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskComment(item.source_id, item.task_id ?? "", item.actor_id, item.delivery_reason, dispatchEventId), typedHooks);
59842
- } else if (item.event_type === "wiki_comment" && item.source_id) {
59843
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleWikiComment(item.source_id, item.actor_id, item.delivery_reason, dispatchEventId), typedHooks);
59844
- } else if (item.event_type === "schedule.fire" && item.source_id) {
59845
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleScheduleFire(item.source_id, item.actor_id, dispatchEventId), typedHooks);
59846
- } else if (item.event_type === "external_trigger" && item.source_id) {
59847
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleExternalTriggerRun(item.source_id, dispatchEventId), typedHooks);
59848
- } else if (item.event_type === "channel_message" && item.source_id) {
59849
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleChannelMessage(item.source_id, dispatchEventId), typedHooks);
59850
- } else if (item.event_type === "approval_decided" && item.source_id) {
59851
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleApprovalDecided(item.source_id, item.actor_id, item.chat_id ?? null, dispatchEventId), typedHooks);
59852
- } else if (item.event_type === "message" && item.source_id && item.chat_id) {
59853
- await this.consumeMessageWorkItem({
59854
- id: item.id,
59855
- source_id: item.source_id,
59856
- chat_id: item.chat_id
59857
- });
59858
- }
59025
+ await this.consumeWorkItem(item);
59859
59026
  } catch (err) {
59860
59027
  this.opts.log?.warn(`catch-up dispatch ${item.id} (${item.event_type}) failed: ${String(err)}`);
59861
59028
  }
@@ -59928,9 +59095,18 @@ ${fullSummary}` : fullSummary;
59928
59095
  this.ledgerDisabled = false;
59929
59096
  }
59930
59097
  const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
59098
+ let openFence = () => {
59099
+ };
59100
+ this.contractReady = new Promise((resolve4) => {
59101
+ openFence = resolve4;
59102
+ });
59931
59103
  try {
59932
- const count = await fetchAllChats(client, config.org_id, this.chatInfoMap);
59933
- log2?.info(`WebSocket connected, ${count} chats cached`);
59104
+ log2?.info("WebSocket connected");
59105
+ try {
59106
+ await this.declareRuntimeContract();
59107
+ } finally {
59108
+ openFence();
59109
+ }
59934
59110
  await this.opts.onSessionReady?.({
59935
59111
  activeSessionId: this.activeSessionId,
59936
59112
  ws: this.opts.ws,
@@ -59964,6 +59140,44 @@ ${fullSummary}` : fullSummary;
59964
59140
  log2?.error(`failed to fetch chats: ${String(err)}`);
59965
59141
  }
59966
59142
  }
59143
+ /**
59144
+ * Declare the runtime contract for this connection: the server decides
59145
+ * who runs and renders the wake frame; this runtime only runs. Bound to
59146
+ * the WS session id, so it repeats on every hello. Retried with backoff
59147
+ * until it lands — WorkItems wait behind the fence meanwhile, nothing is
59148
+ * claimed without a frame. A server without the endpoint renders no
59149
+ * frames: the runtime runs nothing and WorkItems stay pending. A
59150
+ * stale-session 409 means a newer connection already declared.
59151
+ */
59152
+ async declareRuntimeContract() {
59153
+ const session = this.sessionId;
59154
+ if (!session)
59155
+ return;
59156
+ for (let attempt = 0; ; attempt++) {
59157
+ try {
59158
+ await this.opts.client.declareReplyPolicyCapability(this.opts.config.org_id, session);
59159
+ this.opts.log?.info("runtime contract declared (server-rendered frames)");
59160
+ return;
59161
+ } catch (err) {
59162
+ if (err instanceof ApiError && err.status === 404) {
59163
+ this.opts.log?.warn("server predates the runtime contract \u2014 it renders no wake frames; WorkItems stay pending");
59164
+ return;
59165
+ }
59166
+ if (err instanceof ApiError && err.status === 409) {
59167
+ this.opts.log?.info("runtime contract already declared by a newer connection");
59168
+ return;
59169
+ }
59170
+ const delayMs = Math.min(3e4, 2e3 * 2 ** Math.min(attempt, 4));
59171
+ this.opts.log?.warn(`runtime contract declaration failed (retry in ${delayMs / 1e3}s): ${String(err)}`);
59172
+ await new Promise((resolve4) => {
59173
+ const timer = setTimeout(resolve4, delayMs);
59174
+ timer.unref?.();
59175
+ });
59176
+ if (this.shuttingDown || this.sessionId !== session)
59177
+ return;
59178
+ }
59179
+ }
59180
+ }
59967
59181
  // Resolves when in-flight dispatches hit 0 or the deadline elapses.
59968
59182
  // Deadline arming the resolver rather than rejecting keeps shutdown() linear
59969
59183
  // — callers don't need to try/catch.
@@ -60111,36 +59325,46 @@ function saveCache(stateDir, response) {
60111
59325
  fs4.writeFileSync(tmpPath, JSON.stringify(cached, null, 2), "utf-8");
60112
59326
  fs4.renameSync(tmpPath, filePath);
60113
59327
  }
60114
- function runtimeModelName(canonicalModel, runtimeType, config) {
59328
+ function runtimeModelConfig(canonicalModel, runtimeType, config) {
60115
59329
  const runtime = runtimeType?.trim();
60116
- if (!runtime || runtime === "openclaw" || runtime === "hermes")
60117
- return canonicalModel;
60118
59330
  const models = config.models ?? {};
60119
59331
  const providers = models.providers ?? {};
60120
59332
  const parall = providers.parall ?? {};
60121
59333
  const catalog = Array.isArray(parall.models) ? parall.models : [];
60122
59334
  const match = catalog.find((model) => model.id === canonicalModel);
60123
- if (!match)
60124
- return null;
59335
+ if (!match) {
59336
+ return !runtime || runtime === "openclaw" || runtime === "hermes" ? { model: canonicalModel, contextWindow: null } : null;
59337
+ }
59338
+ const contextWindow = typeof match.contextWindow === "number" && Number.isSafeInteger(match.contextWindow) && match.contextWindow > 0 ? match.contextWindow : null;
59339
+ if (!runtime || runtime === "openclaw" || runtime === "hermes") {
59340
+ return { model: canonicalModel, contextWindow };
59341
+ }
60125
59342
  const runtimeNames = match.runtime_names ?? {};
60126
59343
  const runtimeName = runtimeNames[runtime];
60127
- if (typeof runtimeName === "string" && runtimeName)
60128
- return runtimeName;
60129
- return canonicalModel;
59344
+ if (typeof runtimeName === "string" && runtimeName) {
59345
+ return {
59346
+ model: runtimeName,
59347
+ contextWindow: runtimeName === canonicalModel ? contextWindow : null
59348
+ };
59349
+ }
59350
+ return { model: canonicalModel, contextWindow };
60130
59351
  }
60131
59352
  function extractDefaults(config, runtimeType) {
60132
59353
  const agents = config.agents ?? {};
60133
59354
  const defaults = agents.defaults ?? {};
60134
59355
  let model = null;
59356
+ let contextWindow = null;
60135
59357
  if (typeof defaults.model === "string" && defaults.model) {
60136
59358
  const canonicalModel = defaults.model.replace(/^parall-anthropic\//, "").replace(/^parall\//, "");
60137
- model = runtimeModelName(canonicalModel, runtimeType, config);
59359
+ const resolved = runtimeModelConfig(canonicalModel, runtimeType, config);
59360
+ model = resolved?.model ?? null;
59361
+ contextWindow = resolved?.contextWindow ?? null;
60138
59362
  }
60139
59363
  let thinkingEffort = null;
60140
59364
  if (typeof defaults.thinking_effort === "string" && defaults.thinking_effort) {
60141
59365
  thinkingEffort = defaults.thinking_effort;
60142
59366
  }
60143
- return { model, thinkingEffort };
59367
+ return { model, thinkingEffort, contextWindow };
60144
59368
  }
60145
59369
  function createPlatformConfigManager(opts) {
60146
59370
  const { client, stateDir, runtimeType, log: log2 } = opts;
@@ -60148,6 +59372,7 @@ function createPlatformConfigManager(opts) {
60148
59372
  let currentDefaults = {
60149
59373
  model: null,
60150
59374
  thinkingEffort: null,
59375
+ contextWindow: null,
60151
59376
  modelIsPin: void 0
60152
59377
  };
60153
59378
  let currentRawConfig = null;
@@ -60425,7 +59650,9 @@ parall approvals wait prll://apr_xxx --timeout 300
60425
59650
  # List all your pending approvals
60426
59651
  parall approvals list
60427
59652
 
60428
- # List available approvable actions
59653
+ # List available approvable actions \u2014 the output includes each documented
59654
+ # action's payload contract (exact field names, and where a CAS base like
59655
+ # expected_version is read from). Check it before hand-writing a --payload.
60429
59656
  parall approvals actions
60430
59657
 
60431
59658
  # Cancel a pending request you made
@@ -60611,8 +59838,19 @@ parall tasks update prll://tsk_xxx --planned-start none
60611
59838
  # Move a task to the end of its status column
60612
59839
  parall tasks update prll://tsk_xxx --placement end
60613
59840
 
60614
- # Add a comment
60615
- parall tasks comments add prll://tsk_xxx --body "Progress update..."
59841
+ # Add a comment \u2014 same shell rules as messages: the body runs through a
59842
+ # shell, so pass real content via --body-file (a written file, or a quoted
59843
+ # heredoc into stdin with '-'). --body "..." only for short literals with
59844
+ # no $, backtick, or quote (single or double). A bare --body - is refused,
59845
+ # not stdin.
59846
+ parall tasks comments add prll://tsk_xxx --body-file - <<'PARALL_EOF'
59847
+ Progress update: fixed the $1,000 rounding bug, it's in review.
59848
+ PARALL_EOF
59849
+ parall tasks comments add prll://tsk_xxx --body-file /tmp/comment.md
59850
+ parall tasks comments add prll://tsk_xxx --body "On it"
59851
+
59852
+ # Long or multi-line description \u2192 same file / stdin channel
59853
+ parall tasks create --title "Write the runbook" --project-id prll://prj_xxx --description-file /tmp/description.md
60616
59854
  \`\`\`
60617
59855
 
60618
59856
  Ordering: to append a task to the end of a status column, always use
@@ -60689,7 +59927,7 @@ When you receive \`[Event: task.comment.created]\`, someone commented on a task
60689
59927
 
60690
59928
  1. Resolve the project and read its current description as described above
60691
59929
  2. Review the comment content and task context
60692
- 3. Reply via comment: \`tasks comments add prll://tsk_xxx --body "Response..."\`
59930
+ 3. Reply via comment: \`tasks comments add prll://tsk_xxx --body-file -\` with a quoted heredoc (\`--body "..."\` only for short literals with no \`$\`, backtick, or quote \u2014 single or double)
60693
59931
  4. If the comment requests status changes, update accordingly
60694
59932
 
60695
59933
  CLI success output is JSON; errors print a JSON line plus, on a \`PERMISSION_DENIED\`, an optional plain-text \`Request approval:\` line \u2014 read both.