@parall/daemon 1.57.2 → 1.58.1

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";
@@ -51728,6 +51544,18 @@ function attachmentEndpoints(apiBase) {
51728
51544
  };
51729
51545
  }
51730
51546
 
51547
+ // ts/sdk/dist/wechat-endpoints.js
51548
+ function wechatEndpoints(apiBase) {
51549
+ const agentBase = (orgId) => `${apiBase}/orgs/${orgId}/agents/me/wechat`;
51550
+ return {
51551
+ WECHAT_CONTACTS: (orgId) => `${agentBase(orgId)}/contacts`,
51552
+ WECHAT_HISTORY: (orgId) => `${agentBase(orgId)}/history`,
51553
+ WECHAT_MEDIA: (orgId) => `${agentBase(orgId)}/media`,
51554
+ WECHAT_PROFILE: (orgId) => `${agentBase(orgId)}/profile`,
51555
+ WECHAT_STATUS: (orgId) => `${agentBase(orgId)}/status`
51556
+ };
51557
+ }
51558
+
51731
51559
  // ts/sdk/dist/constants.js
51732
51560
  var API_BASE = "/api/v1";
51733
51561
  var WIKI_BASE = "/wiki/v1";
@@ -51817,6 +51645,8 @@ var ENDPOINTS = {
51817
51645
  MESSAGE_WATCH: (id) => `${API_BASE}/messages/${id}/watch`,
51818
51646
  MESSAGE_WATCHERS: (id) => `${API_BASE}/messages/${id}/watchers`,
51819
51647
  MESSAGE_WATCHING: (id) => `${API_BASE}/messages/${id}/watching`,
51648
+ /** Caller's attention levels across chats / threads / tasks. */
51649
+ WATCHES: (orgId) => `${API_BASE}/orgs/${orgId}/watches`,
51820
51650
  MESSAGE_REACTIONS: (id) => `${API_BASE}/messages/${id}/reactions`,
51821
51651
  MESSAGE_REACTION: (id, emoji) => `${API_BASE}/messages/${id}/reactions/${encodeURIComponent(emoji)}`,
51822
51652
  // Upload (org-scoped)
@@ -51839,6 +51669,7 @@ var ENDPOINTS = {
51839
51669
  AGENT_ACTIVITY: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/activity`,
51840
51670
  AGENT_MONITOR: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/monitor`,
51841
51671
  AGENT_ME: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me`,
51672
+ AGENT_REPLY_POLICY_CAPABILITY: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/reply-policy-capability`,
51842
51673
  AGENT_NEW_SESSION: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/new-session`,
51843
51674
  AGENT_DEEP_RESET: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/deep-reset`,
51844
51675
  AGENT_SESSIONS: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/sessions`,
@@ -51875,6 +51706,7 @@ var ENDPOINTS = {
51875
51706
  MACHINE_AGENT_WORKSPACE_SETUP: (orgId, machineId, agentId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/agents/${agentId}/workspace/setup`,
51876
51707
  MACHINE_LLM_SOURCE: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/llm-source`,
51877
51708
  MACHINE_PROVIDER_ENABLED: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/provider-enabled`,
51709
+ MACHINE_MANAGED_BY: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/managed-by`,
51878
51710
  MACHINE_CAPABILITIES: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/capabilities`,
51879
51711
  MACHINE_RUNTIME_AUTH: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/runtime-auth`,
51880
51712
  MACHINE_KEYS: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/keys`,
@@ -51977,10 +51809,7 @@ var ENDPOINTS = {
51977
51809
  SLACK_MEMBERS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/slack/members`,
51978
51810
  SLACK_STATUS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/slack/status`,
51979
51811
  // WeChat tier-B read verbs (agent-only; internal research preview).
51980
- WECHAT_CONTACTS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/contacts`,
51981
- WECHAT_HISTORY: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/history`,
51982
- WECHAT_PROFILE: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/profile`,
51983
- WECHAT_STATUS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/status`,
51812
+ ...wechatEndpoints(API_BASE),
51984
51813
  // Invitations (org-scoped, admin)
51985
51814
  ORG_INVITATIONS: (orgId) => `${API_BASE}/orgs/${orgId}/invitations`,
51986
51815
  ORG_INVITATION: (orgId, invId) => `${API_BASE}/orgs/${orgId}/invitations/${invId}`,
@@ -52355,8 +52184,22 @@ var ProjectTaskClient = class {
52355
52184
  async unsubscribeTaskMember(orgId, taskId, userId) {
52356
52185
  return this.request("DELETE", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52357
52186
  }
52358
- async watchThread(threadRootId) {
52359
- return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52187
+ async watchThread(threadRootId, body) {
52188
+ return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId), body);
52189
+ }
52190
+ // ---- Attention settings (agent-attention-design.md §4) ----
52191
+ /** The caller's watch rows: the setting per chat / thread. */
52192
+ async listWatches(orgId) {
52193
+ const res = await this.request("GET", ENDPOINTS.WATCHES(orgId));
52194
+ return res.data;
52195
+ }
52196
+ /**
52197
+ * Set the caller's setting on one target (prll://cht_ / msg_ root).
52198
+ * Threads are watched first when not yet; chats require membership (404
52199
+ * NOT_A_MEMBER otherwise). Tasks carry no setting (watch / unwatch only).
52200
+ */
52201
+ async setWatchLevel(orgId, body) {
52202
+ return this.request("PUT", ENDPOINTS.WATCHES(orgId), body);
52360
52203
  }
52361
52204
  async unwatchThread(threadRootId) {
52362
52205
  return this.request("DELETE", ENDPOINTS.MESSAGE_WATCH(threadRootId));
@@ -52526,6 +52369,10 @@ var WechatClient = class extends TaskLabelClient {
52526
52369
  params.set("limit", String(query.limit));
52527
52370
  return this.request("GET", `${ENDPOINTS.WECHAT_HISTORY(orgId)}?${params.toString()}`);
52528
52371
  }
52372
+ /** Fetch and cache one WeChat image or completed file on first explicit read. */
52373
+ async materializeWechatMedia(orgId, messageId) {
52374
+ return this.request("POST", ENDPOINTS.WECHAT_MEDIA(orgId), { message_id: messageId });
52375
+ }
52529
52376
  /** Connected WeChat account identity. */
52530
52377
  async wechatProfile(orgId) {
52531
52378
  return this.request("GET", ENDPOINTS.WECHAT_PROFILE(orgId));
@@ -53405,6 +53252,15 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53405
53252
  const res = await this.request("GET", ENDPOINTS.APPROVALS_ACTIONS);
53406
53253
  return res.data;
53407
53254
  }
53255
+ /**
53256
+ * Action names plus the payload contract each documented action publishes
53257
+ * (field names, types, and where a CAS base like expected_version is read
53258
+ * from). Additive over getApprovableActions(): older servers omit
53259
+ * `contracts`.
53260
+ */
53261
+ async getApprovableActionCatalog() {
53262
+ return this.request("GET", ENDPOINTS.APPROVALS_ACTIONS);
53263
+ }
53408
53264
  // ---- Agents (org-scoped) ----
53409
53265
  async createAgent(orgId, req, opts) {
53410
53266
  return this.request("POST", ENDPOINTS.AGENTS(orgId), req, void 0, false, opts);
@@ -53629,6 +53485,19 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53629
53485
  provider_enabled: providerEnabled
53630
53486
  });
53631
53487
  }
53488
+ /**
53489
+ * Convert a member's personal device into an organization machine
53490
+ * (PATCH /machines/{id}/managed-by). One-way and idempotent; org admins only
53491
+ * (an admin-role agent qualifies). After conversion every org admin manages
53492
+ * the machine and the registrant is just a member. 'member' is rejected —
53493
+ * an org machine cannot become a personal device again. See
53494
+ * docs/engineering-design/org-machine-assets-design.md §4.
53495
+ */
53496
+ async convertMachineToOrgManaged(orgId, machineId) {
53497
+ return this.request("PATCH", ENDPOINTS.MACHINE_MANAGED_BY(orgId, machineId), {
53498
+ managed_by: "org"
53499
+ });
53500
+ }
53632
53501
  /**
53633
53502
  * Replace the machine's capability set (admin). Primary use: healing a
53634
53503
  * machine that registered without `browser_provider` during the capability
@@ -53878,6 +53747,18 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53878
53747
  async steerDispatch(orgId, req) {
53879
53748
  return this.request("POST", ENDPOINTS.DISPATCH_STEER(orgId), req);
53880
53749
  }
53750
+ /**
53751
+ * Declare the runtime contract for this WS connection: the runtime runs
53752
+ * what the server decides and takes the server-rendered wake frame from
53753
+ * claim / steer responses instead of filtering and rendering locally.
53754
+ * Bound to the connection's session id; re-declare on every hello.
53755
+ * 409 STALE_WS_SESSION when the id is not the agent's current connection.
53756
+ */
53757
+ async declareReplyPolicyCapability(orgId, wsSessionId) {
53758
+ await this.request("PUT", ENDPOINTS.AGENT_REPLY_POLICY_CAPABILITY(orgId), {
53759
+ ws_session_id: wsSessionId
53760
+ });
53761
+ }
53881
53762
  /** Advance exact runtime-input lifecycle for members of an explicit lane. */
53882
53763
  async updateDispatchInputState(orgId, req) {
53883
53764
  return this.request("POST", ENDPOINTS.DISPATCH_INPUT_STATE(orgId), req);
@@ -55209,20 +55090,6 @@ function buildApiError(res, rawErrorBody) {
55209
55090
  return apiError;
55210
55091
  }
55211
55092
 
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
55093
  // ts/sdk/dist/ws.js
55227
55094
  function isRetryableNetworkError(err) {
55228
55095
  return err instanceof Error && err.name === "ApiError" && "status" in err && err.status === 0;
@@ -55654,7 +55521,7 @@ var LaneLedger = class {
55654
55521
  get contextDir() {
55655
55522
  return this.opts.contextDir;
55656
55523
  }
55657
- /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
55524
+ /** Chat message events ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
55658
55525
  handles(event) {
55659
55526
  return event.type === "message" && event.targetId.startsWith("cht_");
55660
55527
  }
@@ -55670,6 +55537,75 @@ var LaneLedger = class {
55670
55537
  laneContextPath(lane) {
55671
55538
  return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
55672
55539
  }
55540
+ /**
55541
+ * Whether the server already rendered this message into a frame the model
55542
+ * saw on its live lane. The row is folded there and resolves with that
55543
+ * lane's turn — a local copy has nothing left to deliver.
55544
+ */
55545
+ seenInFrame(targetId, threadRootId, messageId) {
55546
+ const lane = this.lanes.get(laneKeyForTarget(`prll://${targetId}`, threadRootId));
55547
+ return lane?.seen.has(messageId) ?? false;
55548
+ }
55549
+ /**
55550
+ * Hand the pending frame to the caller (once) with the members it covers
55551
+ * and what the claim said about the wake, and record those members as
55552
+ * seen. Absent frame ⇒ nothing new to render (every member already seen).
55553
+ */
55554
+ takeFrame(lane) {
55555
+ const frame = lane.frame;
55556
+ const ids = lane.framed;
55557
+ for (const id of ids)
55558
+ lane.seen.add(id);
55559
+ lane.frame = void 0;
55560
+ lane.framed = [];
55561
+ const { input, noReply, attachments } = lane;
55562
+ lane.input = void 0;
55563
+ lane.noReply = void 0;
55564
+ lane.attachments = void 0;
55565
+ return { frame, ids, input, noReply, attachments };
55566
+ }
55567
+ /** Record what the claim response said about the wake alongside its frame. */
55568
+ recordWake(lane, res) {
55569
+ if (res.input)
55570
+ lane.input = res.input;
55571
+ if (res.no_reply != null)
55572
+ lane.noReply = res.no_reply;
55573
+ if (res.attachments?.length) {
55574
+ lane.attachments = res.attachments.map((a) => ({
55575
+ id: a.id,
55576
+ fileName: a.file_name ?? "",
55577
+ fileSize: a.file_size ?? 0,
55578
+ mimeType: a.mime_type ?? ""
55579
+ }));
55580
+ }
55581
+ }
55582
+ /** The injection landed: the model has seen these members. */
55583
+ markSeen(event, ids) {
55584
+ const lane = this.lanes.get(this.laneKeyFor(event));
55585
+ if (!lane)
55586
+ return;
55587
+ for (const id of ids)
55588
+ lane.seen.add(id);
55589
+ }
55590
+ /**
55591
+ * The injection did not land (turn already over, process gone): keep the
55592
+ * server's increment as the lane's pending frame so the buffered copy's
55593
+ * drain renders it as its own turn instead of skipping it as seen.
55594
+ */
55595
+ deferFrame(event, frame, ids) {
55596
+ const lane = this.lanes.get(this.laneKeyFor(event));
55597
+ if (!lane)
55598
+ return;
55599
+ this.recordFrame(lane, frame, ids);
55600
+ }
55601
+ recordFrame(lane, frame, ids) {
55602
+ if (!frame)
55603
+ return;
55604
+ lane.frame = lane.frame ? `${lane.frame}
55605
+
55606
+ ${frame}` : frame;
55607
+ lane.framed.push(...ids);
55608
+ }
55673
55609
  /**
55674
55610
  * Claim (or reuse) the lane for a group of same-lane message events and
55675
55611
  * fold every group member into it. Returns 'foreign' when a healthy
@@ -55719,11 +55655,15 @@ var LaneLedger = class {
55719
55655
  threadRootId: trigger.threadRootId,
55720
55656
  coverageMode: actualCoverage,
55721
55657
  folded: /* @__PURE__ */ new Map(),
55658
+ framed: [],
55659
+ seen: /* @__PURE__ */ new Set(),
55722
55660
  ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
55723
55661
  };
55724
55662
  for (const ev of res.events ?? []) {
55725
55663
  lane.folded.set(ev.source_id, ev.id);
55726
55664
  }
55665
+ this.recordFrame(lane, res.frame, (res.events ?? []).map((ev) => ev.source_id));
55666
+ this.recordWake(lane, res);
55727
55667
  this.lanes.set(laneKey, lane);
55728
55668
  }
55729
55669
  for (const ev of events) {
@@ -55737,6 +55677,7 @@ var LaneLedger = class {
55737
55677
  ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
55738
55678
  });
55739
55679
  lane.folded.set(ev.messageId, res.dispatch_event_id);
55680
+ this.recordFrame(lane, res.frame, [ev.messageId]);
55740
55681
  } catch (err) {
55741
55682
  if (isStaleLane(err)) {
55742
55683
  this.lanes.delete(laneKey);
@@ -55760,8 +55701,13 @@ var LaneLedger = class {
55760
55701
  const lane = this.lanes.get(laneKey);
55761
55702
  if (!lane)
55762
55703
  return null;
55704
+ if (lane.seen.has(event.messageId))
55705
+ return null;
55763
55706
  if (lane.folded.has(event.messageId)) {
55764
- return { inputLifecycle: this.inputLifecycle(lane, [event]) };
55707
+ return {
55708
+ inputLifecycle: this.inputLifecycleFor(lane, [event.messageId]),
55709
+ covered: [event.messageId]
55710
+ };
55765
55711
  }
55766
55712
  try {
55767
55713
  const res = await this.opts.client.steerDispatch(this.opts.orgId, {
@@ -55771,7 +55717,12 @@ var LaneLedger = class {
55771
55717
  ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
55772
55718
  });
55773
55719
  lane.folded.set(event.messageId, res.dispatch_event_id);
55774
- return { inputLifecycle: this.inputLifecycle(lane, [event]) };
55720
+ const covered = [event.messageId];
55721
+ return {
55722
+ inputLifecycle: this.inputLifecycleFor(lane, covered),
55723
+ frame: res.frame,
55724
+ covered
55725
+ };
55775
55726
  } catch (err) {
55776
55727
  if (isStaleLane(err)) {
55777
55728
  this.lanes.delete(laneKey);
@@ -55786,10 +55737,18 @@ var LaneLedger = class {
55786
55737
  * batched prompt covers every WorkItem represented in that single frame.
55787
55738
  */
55788
55739
  inputLifecycle(lane, events) {
55740
+ return this.inputLifecycleFor(lane, events.map((event) => event.messageId));
55741
+ }
55742
+ /**
55743
+ * Exact lifecycle over a set of folded members by message id — the set a
55744
+ * prompt or injection actually delivers (frame coverage ∪ buffered group).
55745
+ */
55746
+ inputLifecycleFor(lane, messageIds) {
55789
55747
  if (lane.coverageMode !== "explicit")
55790
55748
  return void 0;
55791
- const dispatchEventIds = events.map((event) => lane.folded.get(event.messageId)).filter((id) => Boolean(id));
55792
- if (dispatchEventIds.length !== events.length) {
55749
+ const unique = [...new Set(messageIds)];
55750
+ const dispatchEventIds = unique.map((messageId) => lane.folded.get(messageId)).filter((id) => Boolean(id));
55751
+ if (dispatchEventIds.length !== unique.length) {
55793
55752
  throw new Error(`explicit lane ${lane.lane} is missing a folded WorkItem mapping`);
55794
55753
  }
55795
55754
  return {
@@ -55987,10 +55946,12 @@ var LaneLedger = class {
55987
55946
  return this.lanes.size;
55988
55947
  }
55989
55948
  /**
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.
55949
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>)
55950
+ * by WorkItem id. The server renders the wake frame on claim (or resolves
55951
+ * the item as stale and answers `claimed: false, reason: "stale"`).
55952
+ * Returns null when a healthy incumbent (another pod) holds it, the
55953
+ * WorkItem is already resolved, or the server found nothing to wake for
55954
+ * — the caller must skip processing.
55994
55955
  */
55995
55956
  async claimTyped(ref) {
55996
55957
  let res;
@@ -56005,8 +55966,15 @@ var LaneLedger = class {
56005
55966
  throw new LedgerUnsupportedError("claim endpoint unavailable");
56006
55967
  throw err;
56007
55968
  }
56008
- if (!res.claimed || !res.lane || !res.events?.length)
55969
+ if (!res.claimed || !res.lane || !res.events?.length) {
55970
+ if (res.reason === "stale") {
55971
+ this.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} resolved by the server as stale (${res.stale_reason ?? "unspecified"})`);
55972
+ } else if (res.claimed && res.lane) {
55973
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, res.lane).catch(() => {
55974
+ });
55975
+ }
56009
55976
  return null;
55977
+ }
56010
55978
  const workItem = res.events[0];
56011
55979
  const targetUri = `dsp:${workItem.id}`;
56012
55980
  const leaseUntilMs = Date.parse(res.lease_until ?? "");
@@ -56016,9 +55984,13 @@ var LaneLedger = class {
56016
55984
  targetUri,
56017
55985
  coverageMode: "implicit",
56018
55986
  folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
55987
+ framed: [],
55988
+ seen: /* @__PURE__ */ new Set(),
56019
55989
  typedDispatchEventId: workItem.id,
56020
55990
  ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
56021
55991
  };
55992
+ this.recordFrame(lane, res.frame, [workItem.source_id]);
55993
+ this.recordWake(lane, res);
56022
55994
  this.lanes.set(lane.laneKey, lane);
56023
55995
  return lane;
56024
55996
  }
@@ -56061,6 +56033,19 @@ function shiftMainBufferGroup(host, groupKey, preserveInjectedFrameBoundary) {
56061
56033
  }
56062
56034
  return events;
56063
56035
  }
56036
+ function applyWake(event, wake) {
56037
+ if (wake.frame)
56038
+ event.frame = wake.frame;
56039
+ if (wake.input) {
56040
+ event.input = wake.input;
56041
+ if (wake.input.sender_id)
56042
+ event.senderId = wake.input.sender_id;
56043
+ }
56044
+ if (wake.noReply != null)
56045
+ event.noReply = wake.noReply;
56046
+ if (wake.attachments?.length)
56047
+ event.attachments = wake.attachments;
56048
+ }
56064
56049
  function hasUninjectedSameLaneEventAhead(host, event) {
56065
56050
  const eventIndex = host.dispatchState.mainBuffer.lastIndexOf(event);
56066
56051
  if (eventIndex <= 0)
@@ -56078,10 +56063,17 @@ async function steerLaneMessage(host, event) {
56078
56063
  const folded = await ledger.steerLive(event);
56079
56064
  if (!folded)
56080
56065
  return;
56081
- const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, buildEventBody(event), folded.inputLifecycle);
56066
+ if (!folded.frame)
56067
+ return;
56068
+ event.frame = folded.frame;
56069
+ const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, eventBody(event), folded.inputLifecycle);
56082
56070
  if (injected) {
56083
56071
  host.injectedMainBufferEvents.add(event);
56072
+ ledger.markSeen(event, folded.covered);
56084
56073
  opts.log?.info(`steer folded+injected for ${event.messageId} (will drain for bookkeeping)`);
56074
+ } else if (folded.frame) {
56075
+ ledger.deferFrame(event, folded.frame, folded.covered);
56076
+ opts.log?.info(`steer folded but not injected for ${event.messageId} \u2014 frame deferred to the drain`);
56085
56077
  }
56086
56078
  }
56087
56079
  async function dispatchLaneGroup(host, opts) {
@@ -56094,18 +56086,9 @@ async function dispatchLaneGroup(host, opts) {
56094
56086
  if (!(err instanceof LedgerUnsupportedError))
56095
56087
  throw err;
56096
56088
  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";
56089
+ for (const ev of opts.events)
56090
+ host.dispatchedMessages.delete(ev.messageId);
56091
+ return "foreign";
56109
56092
  }
56110
56093
  if (!lane) {
56111
56094
  for (const ev of opts.events) {
@@ -56113,11 +56096,32 @@ async function dispatchLaneGroup(host, opts) {
56113
56096
  }
56114
56097
  return "foreign";
56115
56098
  }
56099
+ const pending = ledger.takeFrame(lane);
56100
+ const frame = pending.frame;
56101
+ if (!frame && opts.events.every((ev) => lane.seen.has(ev.messageId))) {
56102
+ host.opts.log?.info(`lane group for ${event.messageId} already rendered by the server frame \u2014 no turn`);
56103
+ const pendingInjections2 = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
56104
+ await ledger.completeIfIdle(lane.laneKey, pendingInjections2 || opts.hasMoreLocal());
56105
+ return "dispatched";
56106
+ }
56107
+ if (!frame) {
56108
+ host.opts.log?.warn(`lane group for ${event.messageId} claimed without a frame \u2014 releasing the members instead of running`);
56109
+ for (const ev of opts.events)
56110
+ host.dispatchedMessages.delete(ev.messageId);
56111
+ await ledger.release(lane.laneKey).catch(() => {
56112
+ });
56113
+ return "foreign";
56114
+ }
56115
+ applyWake(event, pending);
56116
56116
  host.noteSessionLane(opts.sessionKey, lane.laneKey);
56117
56117
  let dispatched = false;
56118
56118
  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);
56119
+ const inputLifecycle = ledger.inputLifecycleFor(lane, [
56120
+ ...opts.earlier.map((ev) => ev.messageId),
56121
+ event.messageId,
56122
+ ...frame ? pending.ids : []
56123
+ ]);
56124
+ dispatched = await host.runDispatch(event, opts.sessionKey, opts.bodyPrefix + eventBody(event), opts.earlier, opts.captureText, inputLifecycle);
56121
56125
  } catch (err) {
56122
56126
  host.noteSessionLane(opts.sessionKey, null);
56123
56127
  await ledger.release(lane.laneKey).catch(() => {
@@ -56185,50 +56189,16 @@ async function resolveDispatchByID(host, dispatchEventId, lane) {
56185
56189
  return "failed";
56186
56190
  }
56187
56191
  }
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
56192
  async function settleDrainedTypedGroup(host, events, ids, turnErrored) {
56219
56193
  if (turnErrored) {
56220
56194
  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
56195
  return;
56224
56196
  }
56225
56197
  const legacyAckFrom = async (start) => {
56226
- for (const [j, id] of ids.slice(start).entries()) {
56198
+ for (const id of ids.slice(start)) {
56227
56199
  try {
56228
56200
  await host.opts.client.ackDispatchByID(host.opts.config.org_id, id);
56229
56201
  } catch {
56230
- } finally {
56231
- clearTypedDedupeForEvent(host, events[start + j]);
56232
56202
  }
56233
56203
  }
56234
56204
  };
@@ -56244,7 +56214,6 @@ async function settleDrainedTypedGroup(host, events, ids, turnErrored) {
56244
56214
  await legacyAckFrom(i);
56245
56215
  return;
56246
56216
  }
56247
- clearTypedDedupeForEvent(host, events[i]);
56248
56217
  }
56249
56218
  }
56250
56219
  var TYPED_BACKOFF_BASE_MS = 2e3;
@@ -56280,18 +56249,8 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56280
56249
  }
56281
56250
  host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
56282
56251
  };
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
56252
  if (!host.laneLedger || host.ledgerDisabled) {
56294
- await runLegacy();
56253
+ host.opts.log?.info(`typed dispatch ${backoffKey} skipped \u2014 the server renders no wake frame`);
56295
56254
  return;
56296
56255
  }
56297
56256
  let lane;
@@ -56300,7 +56259,6 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56300
56259
  } catch (err) {
56301
56260
  if (err instanceof LedgerUnsupportedError) {
56302
56261
  host.disableLedger("claim endpoint missing");
56303
- await runLegacy();
56304
56262
  return;
56305
56263
  }
56306
56264
  throw err;
@@ -56312,7 +56270,7 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56312
56270
  let resolved = false;
56313
56271
  let viaLegacyAck = false;
56314
56272
  try {
56315
- if (await run(lane.typedDispatchEventId)) {
56273
+ if (await run(lane)) {
56316
56274
  if (host.typedByIdCompleteUnsupported || !lane.typedDispatchEventId) {
56317
56275
  viaLegacyAck = true;
56318
56276
  resolved = settleAck(await hooks.legacyAck(lane.typedDispatchEventId));
@@ -56324,13 +56282,9 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56324
56282
  viaLegacyAck = true;
56325
56283
  resolved = settleAck(await hooks.legacyAck(lane.typedDispatchEventId));
56326
56284
  } else if (outcome === "stale") {
56327
- hooks.clearDedupe?.();
56328
56285
  resolved = true;
56329
56286
  } else {
56330
56287
  resolved = outcome === "ok";
56331
- if (!resolved) {
56332
- hooks.clearDedupe?.();
56333
- }
56334
56288
  }
56335
56289
  }
56336
56290
  }
@@ -56349,56 +56303,27 @@ async function consumeMessageWorkItem(host, item) {
56349
56303
  return;
56350
56304
  if (!host.tryClaimMessage(item.source_id))
56351
56305
  return;
56352
- if (host.dispatchState.mainBuffer.some((event) => event.messageId === item.source_id))
56306
+ if (host.dispatchState.mainBuffer.some((event2) => event2.messageId === item.source_id))
56353
56307
  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();
56308
+ if (host.laneLedger && !host.ledgerDisabled && host.laneLedger.seenInFrame(item.chat_id, item.thread_root_id ?? void 0, item.source_id)) {
56382
56309
  return;
56383
56310
  }
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();
56392
- return;
56393
- }
56394
- decision.event.dispatchEventId = item.id;
56395
- const laneResolved = host.usesLaneLedger(decision.event);
56311
+ const change = splitChangeSource(item.source_id);
56312
+ const event = {
56313
+ type: "message",
56314
+ targetId: item.chat_id,
56315
+ targetType: "chat",
56316
+ senderId: item.actor_id ?? "",
56317
+ messageId: item.source_id,
56318
+ threadRootId: item.thread_root_id ?? void 0,
56319
+ deliveryReason: item.delivery_reason ?? change.reason ?? void 0,
56320
+ ackSourceType: "message",
56321
+ ackSourceId: item.source_id,
56322
+ dispatchEventId: item.id
56323
+ };
56396
56324
  try {
56397
- const dispatched = await host.handleInboundEvent(decision.event);
56398
- if (dispatched) {
56399
- if (!laneResolved)
56400
- ackItem();
56401
- } else {
56325
+ const dispatched = await host.handleInboundEvent(event);
56326
+ if (!dispatched) {
56402
56327
  host.dispatchedMessages.delete(item.source_id);
56403
56328
  }
56404
56329
  } catch (err) {
@@ -57587,6 +57512,16 @@ function createOtelLogger(layer, prefix) {
57587
57512
 
57588
57513
  // ts/agent-core/dist/gateway-base.js
57589
57514
  var LIVE_SESSION_STATUSES = /* @__PURE__ */ new Set(["open", "active", "idle"]);
57515
+ var TYPED_EVENT_KINDS = {
57516
+ task_assign: { type: "task", ackSourceType: "task_activity" },
57517
+ task_update: { type: "task", ackSourceType: "task_activity" },
57518
+ task_comment: { type: "task_comment", ackSourceType: "comment" },
57519
+ wiki_comment: { type: "wiki_comment", ackSourceType: "comment" },
57520
+ "schedule.fire": { type: "schedule", ackSourceType: "schedule_run" },
57521
+ external_trigger: { type: "external_trigger", ackSourceType: "external_trigger_run" },
57522
+ channel_message: { type: "channel_message", ackSourceType: "channel_message" },
57523
+ approval_decided: { type: "approval", ackSourceType: "approval" }
57524
+ };
57590
57525
  function parseShutdownDeadlineMs(raw) {
57591
57526
  if (!raw)
57592
57527
  return void 0;
@@ -57620,6 +57555,9 @@ function inputStepIdempotencyKey(event) {
57620
57555
  return randomUUID();
57621
57556
  }
57622
57557
  function resolveStepTarget(event) {
57558
+ if (event.input?.step_target) {
57559
+ return { target_type: event.input.step_target.type, target_id: event.input.step_target.id };
57560
+ }
57623
57561
  if (event.type === "task" || event.targetId.startsWith("tsk_")) {
57624
57562
  return { target_type: "task", target_id: event.targetId };
57625
57563
  }
@@ -57640,48 +57578,63 @@ function resolveStepTarget(event) {
57640
57578
  }
57641
57579
  return { target_type: "", target_id: event.targetId || void 0 };
57642
57580
  }
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
- }
57581
+ function inputTriggerTypeFor(type) {
57582
+ switch (type) {
57583
+ case "task":
57584
+ return "task_assign";
57585
+ case "task_comment":
57586
+ return "task_comment";
57587
+ case "wiki_comment":
57588
+ return "wiki_comment";
57589
+ case "schedule":
57590
+ return "schedule_fire";
57591
+ case "external_trigger":
57592
+ return "external_trigger";
57593
+ case "channel_message":
57594
+ return "channel_message";
57595
+ case "approval":
57596
+ return "approval_decided";
57597
+ default:
57598
+ return "mention";
57599
+ }
57600
+ }
57601
+ function inputTriggerRef(event) {
57602
+ const sourceId = event.ackSourceId ?? event.messageId;
57603
+ switch (event.type) {
57604
+ case "task":
57605
+ return { task_id: event.targetId };
57606
+ case "task_comment":
57607
+ return { comment_id: sourceId, task_id: event.targetId };
57608
+ case "wiki_comment":
57609
+ return { comment_id: sourceId, target_uri: `prll://${event.targetId}` };
57610
+ case "schedule":
57611
+ return { schedule_id: event.targetId, run_id: sourceId };
57612
+ case "external_trigger":
57613
+ return { trigger_id: event.targetId, run_id: sourceId };
57614
+ case "channel_message":
57615
+ return { conversation_id: event.targetId, channel_message_id: sourceId };
57616
+ case "approval":
57617
+ return { approval_id: sourceId };
57618
+ default:
57619
+ return {
57620
+ message_id: splitChangeSource(event.messageId).messageId,
57621
+ // Thread context for the session→chat backlink: a thread reply can
57622
+ // only be navigated to with its thread root.
57623
+ ...event.threadRootId ? { thread_root_id: event.threadRootId } : {}
57624
+ };
57657
57625
  }
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
57626
  }
57677
57627
  var ParallAgentGateway = class {
57678
57628
  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();
57629
+ // In-process in-flight guard for message WorkItems (see LaneFlowHost).
57684
57630
  dispatchedMessages = /* @__PURE__ */ new Set();
57631
+ /**
57632
+ * Consumption fence: no WorkItem is claimed before this connection's
57633
+ * runtime contract is declared (handleHello). A claim made before the
57634
+ * declaration would get no frame — and a frameless claim has nothing to
57635
+ * run. Open until the first hello starts a declaration.
57636
+ */
57637
+ contractReady = Promise.resolve();
57685
57638
  injectedMainBufferEvents = /* @__PURE__ */ new WeakSet();
57686
57639
  // Per-WorkItem failure backoff for typed dispatch consumption — see
57687
57640
  // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
@@ -57793,29 +57746,6 @@ var ParallAgentGateway = class {
57793
57746
  ws.on("hello", async (data) => {
57794
57747
  await this.handleHello(data);
57795
57748
  });
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
57749
  ws.on("agent_config.update", async (data) => {
57820
57750
  this.opts.log?.info(`config update notification (version=${data.version})`);
57821
57751
  try {
@@ -57843,135 +57773,11 @@ var ParallAgentGateway = class {
57843
57773
  this.opts.log?.warn(`recovery.overflow \u2014 triggering full catch-up`);
57844
57774
  this.catchUpFromDispatch().catch((err) => this.opts.log?.warn(`overflow catch-up failed: ${String(err)}`));
57845
57775
  });
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;
57776
+ ws.on("dispatch.new", async (data) => {
57851
57777
  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
- });
57778
+ await this.consumeWorkItem(data);
57870
57779
  } 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`);
57780
+ this.opts.log?.error(`dispatch ${data.id} (${String(data.event_type)}) failed: ${String(err)}`);
57975
57781
  }
57976
57782
  });
57977
57783
  this.opts.log?.info(`connecting to ${this.opts.connectionLabel ?? "Parall WS"}...`);
@@ -58156,44 +57962,6 @@ var ParallAgentGateway = class {
58156
57962
  isTypedEventBuffered(event) {
58157
57963
  return this.isBufferedTypedWorkItem(event.dispatchEventId);
58158
57964
  }
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
57965
  buildDispatchContext(event, sessionKey) {
58198
57966
  const binding = this.sessionBindings.get(sessionKey);
58199
57967
  return {
@@ -58206,7 +57974,7 @@ var ParallAgentGateway = class {
58206
57974
  runtimeKey: this.opts.runtimeKey,
58207
57975
  sessionId: binding?.agentSessionId,
58208
57976
  chatId: event.type === "message" || event.type === "approval" ? event.targetId : void 0,
58209
- triggerMessageId: event.messageId,
57977
+ triggerMessageId: splitChangeSource(event.messageId).messageId,
58210
57978
  noReply: event.noReply ?? false,
58211
57979
  contextFilePath: this.opts.contextFilePathForSession?.(sessionKey),
58212
57980
  stepIdFilePath: this.opts.stepIdFilePathForSession?.(sessionKey),
@@ -58220,35 +57988,24 @@ var ParallAgentGateway = class {
58220
57988
  }
58221
57989
  async createInputStep(sessionId, event) {
58222
57990
  const target = resolveStepTarget(event);
57991
+ const input = event.input;
58223
57992
  await this.stepPersister.persist(sessionId, "input", {
58224
57993
  step_type: "input",
58225
57994
  target_type: target.target_type,
58226
57995
  target_id: target.target_id,
58227
57996
  idempotency_key: inputStepIdempotencyKey(event),
58228
57997
  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
- },
57998
+ // What the server said about the wake (claim `input`), plus the
57999
+ // source pointer and the anchor the web needs to link a chat
58000
+ // message or a task to this session.
58001
+ trigger_type: input?.trigger_type ?? inputTriggerTypeFor(event.type),
58002
+ trigger_ref: inputTriggerRef(event),
58003
+ source_type: event.ackSourceType,
58004
+ source_id: event.ackSourceId ?? event.messageId,
58248
58005
  sender_id: event.senderId,
58249
- sender_name: event.senderName,
58250
- summary: event.body.substring(0, 200),
58251
- ...event.sentAt ? { sent_at: event.sentAt } : {}
58006
+ ...input?.sender_name ? { sender_name: input.sender_name } : {},
58007
+ summary: (input?.summary ?? eventBody(event)).substring(0, 200),
58008
+ ...input?.sent_at ? { sent_at: input.sent_at } : {}
58252
58009
  }
58253
58010
  });
58254
58011
  }
@@ -58760,13 +58517,14 @@ var ParallAgentGateway = class {
58760
58517
  retainForkContinuationRetries(this.forkContinuationRetries, events, fork.continuationPrefix);
58761
58518
  try {
58762
58519
  const batchText = [];
58763
- const body = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last) + buildEventBody(last);
58520
+ const bodyPrefix = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last);
58521
+ const body = bodyPrefix + eventBody(last);
58764
58522
  let dispatched;
58765
58523
  if (this.usesLaneLedger(last)) {
58766
58524
  const outcome = await this.dispatchLaneGroup({
58767
58525
  events,
58768
58526
  sessionKey: fork.fork.sessionKey,
58769
- body,
58527
+ bodyPrefix,
58770
58528
  earlier,
58771
58529
  captureText: batchText,
58772
58530
  // Per-LANE residue check (parity with the main-buffer path):
@@ -58841,9 +58599,9 @@ var ParallAgentGateway = class {
58841
58599
  sourceEvent: {
58842
58600
  type: first.type,
58843
58601
  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}`
58602
+ summary: fork.processedEvents.length === 1 ? `${first.type} in ${fork.targetId}` : `${fork.processedEvents.length} events in ${fork.targetId}`
58845
58603
  },
58846
- eventBodies: fork.processedEvents.map((e) => buildEventBodyForForkResult(e)),
58604
+ eventBodies: fork.processedEvents.map((e) => forkResultBody(e)),
58847
58605
  actions: [],
58848
58606
  agentSummary,
58849
58607
  historyPath
@@ -58914,7 +58672,7 @@ var ParallAgentGateway = class {
58914
58672
  outcome = await this.dispatchLaneGroup({
58915
58673
  events,
58916
58674
  sessionKey: this.opts.runtimeKey,
58917
- body: forkPrefix + buildEventBody(event),
58675
+ bodyPrefix: forkPrefix,
58918
58676
  earlier,
58919
58677
  hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === groupKey)
58920
58678
  });
@@ -58956,16 +58714,14 @@ var ParallAgentGateway = class {
58956
58714
  }
58957
58715
  }
58958
58716
  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);
58717
+ const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => eventBody(ev)).join("\n\n") : eventBody(event);
58960
58718
  let dispatched;
58961
58719
  try {
58962
58720
  dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + body, earlier);
58963
58721
  } catch (err) {
58964
58722
  if (!isTypedGroup)
58965
58723
  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);
58724
+ this.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}): ${String(err)}`);
58969
58725
  this.dispatchState.pendingForkResults.unshift(...pendingFork);
58970
58726
  continue;
58971
58727
  }
@@ -58986,7 +58742,6 @@ var ParallAgentGateway = class {
58986
58742
  source_id: sourceId
58987
58743
  }).catch(() => {
58988
58744
  });
58989
- clearTypedDedupeForEvent(this.laneFlowHost(), bufferedEvent);
58990
58745
  }
58991
58746
  } finally {
58992
58747
  for (const id of drainingIds)
@@ -59029,7 +58784,7 @@ var ParallAgentGateway = class {
59029
58784
  outcome = await this.dispatchLaneGroup({
59030
58785
  events: [event],
59031
58786
  sessionKey: this.opts.runtimeKey,
59032
- body: forkPrefix + buildEventBody(event),
58787
+ bodyPrefix: forkPrefix,
59033
58788
  earlier: [],
59034
58789
  hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === this.dispatchGroupKey(event))
59035
58790
  });
@@ -59061,7 +58816,7 @@ var ParallAgentGateway = class {
59061
58816
  }
59062
58817
  let dispatched = false;
59063
58818
  try {
59064
- dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + buildEventBody(event));
58819
+ dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + eventBody(event));
59065
58820
  if (dispatched && typedRefs && this.consumeTurnError(this.opts.runtimeKey)) {
59066
58821
  this.opts.log?.info(`typed dispatch turn for ${event.messageId} surfaced a runtime error \u2014 releasing for retry`);
59067
58822
  dispatched = false;
@@ -59095,7 +58850,7 @@ var ParallAgentGateway = class {
59095
58850
  // the WorkItem stays live, and every re-drive injects it AGAIN (the
59096
58851
  // 7/16 watcher duplicate-delivery loop, #1149). Typed events stay
59097
58852
  // 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))
58853
+ event.type === "message" && event.frame != null && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, eventBody(event))
59099
58854
  ) {
59100
58855
  this.opts.log?.info(`steer injected for ${event.messageId} (will drain for bookkeeping)`);
59101
58856
  }
@@ -59156,605 +58911,75 @@ var ParallAgentGateway = class {
59156
58911
  }
59157
58912
  }
59158
58913
  }
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) {
58914
+ /**
58915
+ * One WorkItem the server pushed (dispatch.new) or a catch-up page
58916
+ * listed: messages ride their (chat, thread) lane; every other family
58917
+ * rides its own dsp lane, claimed, run on the server frame, resolved by
58918
+ * id. A typed WorkItem whose event copy is already buffered for the
58919
+ * drain is left to the drain (re-claiming it would race the drain's
58920
+ * fence-less settlement).
58921
+ */
58922
+ async consumeWorkItem(item) {
58923
+ await this.contractReady;
59266
58924
  if (this.shuttingDown)
59267
58925
  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);
58926
+ if (item.event_type === "message") {
58927
+ if (!item.chat_id || !item.source_id)
58928
+ return;
58929
+ await this.consumeMessageWorkItem({
58930
+ id: item.id,
58931
+ source_id: item.source_id,
58932
+ chat_id: item.chat_id,
58933
+ actor_id: item.actor_id,
58934
+ thread_root_id: item.thread_root_id,
58935
+ delivery_reason: item.delivery_reason
58936
+ });
59278
58937
  return;
59279
58938
  }
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)
58939
+ if (!TYPED_EVENT_KINDS[item.event_type]) {
58940
+ this.opts.log?.info(`dispatch with unhandled event_type=${String(item.event_type)} (id=${item.id}) \u2014 no-op`);
59300
58941
  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)
58942
+ }
58943
+ if (this.isBufferedTypedWorkItem(item.id)) {
58944
+ this.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping re-claim`);
59313
58945
  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
- });
58946
+ }
58947
+ await this.consumeTypedDispatch({ dispatchEventId: item.id }, (lane) => this.runTypedFrame(item, lane), { legacyAck: () => this.ackDispatchEvent(item.id) });
59320
58948
  }
59321
58949
  consumeMessageWorkItem(item) {
59322
58950
  return consumeMessageWorkItem(this.laneFlowHost(), item);
59323
58951
  }
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
58952
  /**
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.
58953
+ * Run one claimed typed WorkItem on the frame the claim returned. The
58954
+ * event is addressing only: the routing target the server named
58955
+ * (`input.subject`the task, the wiki target, the schedule, the
58956
+ * conversation, the chat an approval belongs to), the ids the ledger
58957
+ * keys on, and the input-step metadata. No frame means nothing to run.
59519
58958
  */
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) {
58959
+ async runTypedFrame(item, lane) {
59538
58960
  if (this.shuttingDown)
59539
58961
  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)}`);
58962
+ const wake = this.laneLedger?.takeFrame(lane);
58963
+ if (!wake?.frame) {
58964
+ this.opts.log?.warn(`typed dispatch ${item.id} (${String(item.event_type)}) claimed without a frame \u2014 leaving it pending`);
59616
58965
  return false;
59617
58966
  }
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);
58967
+ const kind = TYPED_EVENT_KINDS[item.event_type];
58968
+ const targetId = wake.input?.subject || item.task_id || item.chat_id || item.source_id || item.id;
59634
58969
  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)}`);
59717
- return false;
59718
- }
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}`;
59734
- 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;
58970
+ type: kind.type,
58971
+ targetId,
58972
+ targetType: wake.input?.step_target?.type,
58973
+ senderId: wake.input?.sender_id ?? item.actor_id ?? "system",
58974
+ messageId: item.source_id,
58975
+ deliveryReason: item.delivery_reason ?? void 0,
58976
+ ackSourceType: kind.ackSourceType,
58977
+ ackSourceId: item.source_id,
58978
+ dispatchEventId: item.id
58979
+ };
58980
+ applyWake(event, wake);
58981
+ this.opts.log?.info(`${String(item.event_type)} ${item.source_id} \u2192 ${targetId}`);
58982
+ return this.handleInboundEvent(event);
59758
58983
  }
59759
58984
  async catchUpFromDispatch() {
59760
58985
  const OVERFLOW_THRESHOLD = 500;
@@ -59808,54 +59033,9 @@ ${reasonLine}` : "";
59808
59033
  }
59809
59034
  continue;
59810
59035
  }
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
59036
  processed++;
59816
59037
  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
- }
59038
+ await this.consumeWorkItem(item);
59859
59039
  } catch (err) {
59860
59040
  this.opts.log?.warn(`catch-up dispatch ${item.id} (${item.event_type}) failed: ${String(err)}`);
59861
59041
  }
@@ -59928,9 +59108,18 @@ ${fullSummary}` : fullSummary;
59928
59108
  this.ledgerDisabled = false;
59929
59109
  }
59930
59110
  const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
59111
+ let openFence = () => {
59112
+ };
59113
+ this.contractReady = new Promise((resolve4) => {
59114
+ openFence = resolve4;
59115
+ });
59931
59116
  try {
59932
- const count = await fetchAllChats(client, config.org_id, this.chatInfoMap);
59933
- log2?.info(`WebSocket connected, ${count} chats cached`);
59117
+ log2?.info("WebSocket connected");
59118
+ try {
59119
+ await this.declareRuntimeContract();
59120
+ } finally {
59121
+ openFence();
59122
+ }
59934
59123
  await this.opts.onSessionReady?.({
59935
59124
  activeSessionId: this.activeSessionId,
59936
59125
  ws: this.opts.ws,
@@ -59964,6 +59153,44 @@ ${fullSummary}` : fullSummary;
59964
59153
  log2?.error(`failed to fetch chats: ${String(err)}`);
59965
59154
  }
59966
59155
  }
59156
+ /**
59157
+ * Declare the runtime contract for this connection: the server decides
59158
+ * who runs and renders the wake frame; this runtime only runs. Bound to
59159
+ * the WS session id, so it repeats on every hello. Retried with backoff
59160
+ * until it lands — WorkItems wait behind the fence meanwhile, nothing is
59161
+ * claimed without a frame. A server without the endpoint renders no
59162
+ * frames: the runtime runs nothing and WorkItems stay pending. A
59163
+ * stale-session 409 means a newer connection already declared.
59164
+ */
59165
+ async declareRuntimeContract() {
59166
+ const session = this.sessionId;
59167
+ if (!session)
59168
+ return;
59169
+ for (let attempt = 0; ; attempt++) {
59170
+ try {
59171
+ await this.opts.client.declareReplyPolicyCapability(this.opts.config.org_id, session);
59172
+ this.opts.log?.info("runtime contract declared (server-rendered frames)");
59173
+ return;
59174
+ } catch (err) {
59175
+ if (err instanceof ApiError && err.status === 404) {
59176
+ this.opts.log?.warn("server predates the runtime contract \u2014 it renders no wake frames; WorkItems stay pending");
59177
+ return;
59178
+ }
59179
+ if (err instanceof ApiError && err.status === 409) {
59180
+ this.opts.log?.info("runtime contract already declared by a newer connection");
59181
+ return;
59182
+ }
59183
+ const delayMs = Math.min(3e4, 2e3 * 2 ** Math.min(attempt, 4));
59184
+ this.opts.log?.warn(`runtime contract declaration failed (retry in ${delayMs / 1e3}s): ${String(err)}`);
59185
+ await new Promise((resolve4) => {
59186
+ const timer = setTimeout(resolve4, delayMs);
59187
+ timer.unref?.();
59188
+ });
59189
+ if (this.shuttingDown || this.sessionId !== session)
59190
+ return;
59191
+ }
59192
+ }
59193
+ }
59967
59194
  // Resolves when in-flight dispatches hit 0 or the deadline elapses.
59968
59195
  // Deadline arming the resolver rather than rejecting keeps shutdown() linear
59969
59196
  // — callers don't need to try/catch.
@@ -60111,36 +59338,50 @@ function saveCache(stateDir, response) {
60111
59338
  fs4.writeFileSync(tmpPath, JSON.stringify(cached, null, 2), "utf-8");
60112
59339
  fs4.renameSync(tmpPath, filePath);
60113
59340
  }
60114
- function runtimeModelName(canonicalModel, runtimeType, config) {
59341
+ function runtimeModelConfig(canonicalModel, runtimeType, config) {
60115
59342
  const runtime = runtimeType?.trim();
60116
- if (!runtime || runtime === "openclaw" || runtime === "hermes")
60117
- return canonicalModel;
60118
59343
  const models = config.models ?? {};
60119
59344
  const providers = models.providers ?? {};
60120
59345
  const parall = providers.parall ?? {};
60121
59346
  const catalog = Array.isArray(parall.models) ? parall.models : [];
60122
59347
  const match = catalog.find((model) => model.id === canonicalModel);
60123
- if (!match)
60124
- return null;
59348
+ if (!match) {
59349
+ return !runtime || runtime === "openclaw" || runtime === "hermes" ? { model: canonicalModel, contextWindow: null, maxTokens: null } : null;
59350
+ }
59351
+ const contextWindow = typeof match.contextWindow === "number" && Number.isSafeInteger(match.contextWindow) && match.contextWindow > 0 ? match.contextWindow : null;
59352
+ const maxTokens = typeof match.maxTokens === "number" && Number.isSafeInteger(match.maxTokens) && match.maxTokens > 0 ? match.maxTokens : null;
59353
+ if (!runtime || runtime === "openclaw" || runtime === "hermes") {
59354
+ return { model: canonicalModel, contextWindow, maxTokens };
59355
+ }
60125
59356
  const runtimeNames = match.runtime_names ?? {};
60126
59357
  const runtimeName = runtimeNames[runtime];
60127
- if (typeof runtimeName === "string" && runtimeName)
60128
- return runtimeName;
60129
- return canonicalModel;
59358
+ if (typeof runtimeName === "string" && runtimeName) {
59359
+ return {
59360
+ model: runtimeName,
59361
+ contextWindow: runtimeName === canonicalModel ? contextWindow : null,
59362
+ maxTokens: runtimeName === canonicalModel ? maxTokens : null
59363
+ };
59364
+ }
59365
+ return { model: canonicalModel, contextWindow, maxTokens };
60130
59366
  }
60131
59367
  function extractDefaults(config, runtimeType) {
60132
59368
  const agents = config.agents ?? {};
60133
59369
  const defaults = agents.defaults ?? {};
60134
59370
  let model = null;
59371
+ let contextWindow = null;
59372
+ let maxTokens = null;
60135
59373
  if (typeof defaults.model === "string" && defaults.model) {
60136
59374
  const canonicalModel = defaults.model.replace(/^parall-anthropic\//, "").replace(/^parall\//, "");
60137
- model = runtimeModelName(canonicalModel, runtimeType, config);
59375
+ const resolved = runtimeModelConfig(canonicalModel, runtimeType, config);
59376
+ model = resolved?.model ?? null;
59377
+ contextWindow = resolved?.contextWindow ?? null;
59378
+ maxTokens = resolved?.maxTokens ?? null;
60138
59379
  }
60139
59380
  let thinkingEffort = null;
60140
59381
  if (typeof defaults.thinking_effort === "string" && defaults.thinking_effort) {
60141
59382
  thinkingEffort = defaults.thinking_effort;
60142
59383
  }
60143
- return { model, thinkingEffort };
59384
+ return { model, thinkingEffort, contextWindow, maxTokens };
60144
59385
  }
60145
59386
  function createPlatformConfigManager(opts) {
60146
59387
  const { client, stateDir, runtimeType, log: log2 } = opts;
@@ -60148,6 +59389,8 @@ function createPlatformConfigManager(opts) {
60148
59389
  let currentDefaults = {
60149
59390
  model: null,
60150
59391
  thinkingEffort: null,
59392
+ contextWindow: null,
59393
+ maxTokens: null,
60151
59394
  modelIsPin: void 0
60152
59395
  };
60153
59396
  let currentRawConfig = null;
@@ -60425,7 +59668,9 @@ parall approvals wait prll://apr_xxx --timeout 300
60425
59668
  # List all your pending approvals
60426
59669
  parall approvals list
60427
59670
 
60428
- # List available approvable actions
59671
+ # List available approvable actions \u2014 the output includes each documented
59672
+ # action's payload contract (exact field names, and where a CAS base like
59673
+ # expected_version is read from). Check it before hand-writing a --payload.
60429
59674
  parall approvals actions
60430
59675
 
60431
59676
  # Cancel a pending request you made
@@ -60611,8 +59856,19 @@ parall tasks update prll://tsk_xxx --planned-start none
60611
59856
  # Move a task to the end of its status column
60612
59857
  parall tasks update prll://tsk_xxx --placement end
60613
59858
 
60614
- # Add a comment
60615
- parall tasks comments add prll://tsk_xxx --body "Progress update..."
59859
+ # Add a comment \u2014 same shell rules as messages: the body runs through a
59860
+ # shell, so pass real content via --body-file (a written file, or a quoted
59861
+ # heredoc into stdin with '-'). --body "..." only for short literals with
59862
+ # no $, backtick, or quote (single or double). A bare --body - is refused,
59863
+ # not stdin.
59864
+ parall tasks comments add prll://tsk_xxx --body-file - <<'PARALL_EOF'
59865
+ Progress update: fixed the $1,000 rounding bug, it's in review.
59866
+ PARALL_EOF
59867
+ parall tasks comments add prll://tsk_xxx --body-file /tmp/comment.md
59868
+ parall tasks comments add prll://tsk_xxx --body "On it"
59869
+
59870
+ # Long or multi-line description \u2192 same file / stdin channel
59871
+ parall tasks create --title "Write the runbook" --project-id prll://prj_xxx --description-file /tmp/description.md
60616
59872
  \`\`\`
60617
59873
 
60618
59874
  Ordering: to append a task to the end of a status column, always use
@@ -60689,7 +59945,7 @@ When you receive \`[Event: task.comment.created]\`, someone commented on a task
60689
59945
 
60690
59946
  1. Resolve the project and read its current description as described above
60691
59947
  2. Review the comment content and task context
60692
- 3. Reply via comment: \`tasks comments add prll://tsk_xxx --body "Response..."\`
59948
+ 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
59949
  4. If the comment requests status changes, update accordingly
60694
59950
 
60695
59951
  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.