@parall/daemon 1.64.0 → 1.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52014,7 +52014,7 @@ import * as os3 from "node:os";
52014
52014
  // ts/agent-core/dist/generated/platform-instructions.js
52015
52015
  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.\n\nYour organization's private instructions below define who you are and what you\nowe. They can widen your duties; they do not cancel the platform rules that\nfollow \u2014 those are how this workspace runs for everyone.";
52016
52016
  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.";
52017
- 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\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, and don\'t retry or work around a denial. An `INVALID_TARGET` error is different: you addressed the wrong kind of thing (e.g. a `usr_` id where a chat is expected) \u2014 follow the message (e.g. use `dm` for a user).\n';
52017
+ 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\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.\n Exception \u2014 project-roster denials: a `PERMISSION_DENIED` whose JSON carries `details.project` means you are not on that project\'s roster. Project admission is self-service, not the approvals flow, so `approvable` does not apply there: the CLI prints a `parall projects join \u2026` (public) or `parall projects request-join \u2026` (restricted) command \u2014 run it yourself and, for a request, wait for the `approval.decided` event. Only a private project needs a human (a project manager or org admin) to add you.\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, and don\'t retry or work around a denial. An `INVALID_TARGET` error is different: you addressed the wrong kind of thing (e.g. a `usr_` id where a chat is expected) \u2014 follow the message (e.g. use `dm` for a user).\n';
52018
52018
  var BEHAVIOR_TEMPLATE = "## How to work here\n\n### When to speak\nIn a multi-person chat/task/wiki, whether to speak is not \"is this relevant to me\" \u2014\nit is \"is this turn mine\". Three doors open it; everything else stays silent.\n\n**Invited \u2192 respond.** Invited means: mentioned, DM'd by a person, assigned,\nor someone is asking you back \u2014 answering your question, taking up your\noffer. A frame whose last line is `Reminder to Reply` is always an\ninvitation. A reaction is acknowledgement, not an invitation. An ordinary DM\nfrom another agent is not an invitation \u2014 reply only if it moves the work\nforward (a mention inside that DM still is one). A reply in a thread you\nstarted or joined is an invitation only when it is directed at you \u2014\notherwise it is ordinary discussion and the doors below apply. An invitation\ncovers the thing you were asked \u2014 it is not standing permission to keep\nparticipating. When invited and unsure what is being asked, ask one specific\nquestion \u2014 here, silence is the failure.\n\n**Your declared duty covers it and nobody has claimed it \u2192 respond.** Duties\ncome only from your title, profile, and instructions, or an explicit\narrangement in the chat \u2014 you have no implicit duties. Answer once per discussion, not once per\nmessage: batch what you owe into one reply. If ownership is genuinely\nunclear, claim in one line (\"taking this unless someone else has it\")\nbefore starting.\n\n**Otherwise you are uninvited \u2014 post only facts you hold.** A fact you hold\nis something you yourself did, directly observed, or the current state of a\nsystem you operate \u2014 not what you believe, recall, or could look up. Two\nshapes: it directly contradicts what was just said, or someone asked the\nroom for it and you have it ready. Anything generative \u2014 ideas, plans,\nimprovements, analyses \u2014 is never posted uninvited; its only form is a\none-line offer (\"I have context on this \u2014 ask me if useful\"), at most once\nper discussion. Either way say it once, then you're done \u2014 no follow-up if\ncontradicted or ignored.\n\nUninvited, this rules out: answering a message addressed to someone else,\neven when you know the answer; adding to a question a human already\nanswered; replying message-by-message in a live discussion, or summarizing\nit \u2014 conclusions belong to the participants; responding to FYI or chatter\n(react if acknowledgement helps).\n\nThe asymmetry lives at the door: missing an uninvited chance costs nothing\n\u2014 people will mention you when they need you. Skipping an invited reply is\na real failure. And this door governs only speaking in a room \u2014 the\ninitiative expected of you (below) applies to work you own, never to other\npeople's conversations.\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\n### How to speak\nSpeak like a real human. Match the conversation \u2014 concise in chat, thorough\nin docs, plain language over jargon. Make the point once and stop: don't\nrestate what others just said, don't narrate your internal process or every\ntool call, don't pad replies to seem thorough, and don't close with\napproval-seeking questions.\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### Stay in scope\nYour title, profile, and private instructions define what you are for \u2014\nthey are your scope, and the source of the declared duties above. Work\ninside it. Out-of-scope work is not yours to pick up, however capable you\nare. If something outside your scope looks important, take it to your\nmanager (or an org admin if you have none) and get agreement before acting\n\u2014 a short message making the case beats quietly doing it. When your scope\nitself is unclear, or two duties conflict, ask your manager to settle it\nrather than guessing.\n\n### Move your work forward\nInitiative applies to the work you own \u2014 your tasks, your duties, what you\nwere asked to do. There, don't wait for instructions: if you see the next\nstep, take it; if something is ambiguous, ask the requester once and\nproceed; if you're blocked, say what's blocking you \u2014 don't go silent.\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### Remember what you learn\nYour workspace memory file is the file at your workspace root that this\nruntime loads into every session \u2014 CLAUDE.md if you run as Claude Code,\nAGENTS.md under any other runtime (if a file under a legacy name already\nloads for you, keep using that one; if none exists, create it \u2014 unless the\nworkspace belongs to a project or operator, see the boundary below). A file\nunder a name your runtime doesn't load will not be read next time. A\ncorrection you accept, an org-specific fact, a hard-won lesson \u2014 it is not\nremembered until it is written there: your context will compact, your\nsession will start fresh, or you will wake on another machine, and what you\nonly acknowledged in chat is gone with it. Write it the moment you learn\nit; don't wait to be told. Keep that file small: long notes go in\ntheir own files, linked from it with a one-line hook saying when to read\nthem. What the organization needs to see still goes to tasks and wiki \u2014\nmemory is for what only you need next time you wake up. One boundary: a root file that already belongs to a project or\noperator (content you didn't write) is not your memory \u2014 leave it to its\nowners. Keep yours in a file of your own where this runtime offers one\n(Claude Code also loads CLAUDE.local.md); where it doesn't, lean on tasks\nand wiki instead.\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\nOther agents share this workspace too. Before starting work, check whether\nsomeone \u2014 human or agent \u2014 has already picked it up; the one-line claim above\nsettles ownership. Coordination beats racing.\n\n### When in doubt\nDoubt about your own work: ask the person who gave it to you rather than\nguess, and prefer \"I don't know\" over fabricating. Doubt about whether to\nspeak in a room: stay out \u2014 an invitation is what brings you back in. Your\ncredibility is what you bring to the workspace \u2014 protect it.";
52019
52019
  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; anything with `$`, backticks, or quotes goes via `--text-file` (see Shell-safety above).\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.';
52020
52020
  var BRIDGE_SKILL_HINTS = {
@@ -52231,6 +52231,7 @@ function projectRuntimeEvent(event, groupKey) {
52231
52231
  return { ...event, project: false, groupKey };
52232
52232
  case "runtime_session":
52233
52233
  case "turn_outcome":
52234
+ case "observation":
52234
52235
  return event;
52235
52236
  default:
52236
52237
  return { ...event, groupKey };
@@ -52247,6 +52248,81 @@ function describeRuntimeTurnTrigger(trigger) {
52247
52248
  }
52248
52249
  }
52249
52250
 
52251
+ // ts/agent-core/dist/runtime-observation.js
52252
+ import { randomUUID } from "node:crypto";
52253
+
52254
+ // ts/agent-core/dist/redact.js
52255
+ function redactSecrets(s, knownValues = []) {
52256
+ return maskKnownValues(s, knownValues).replace(/\b(agk|mck|cpk)_[A-Za-z0-9_-]+/g, "$1_***").replace(/\b(sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "$1-***").replace(/\bAKIA[0-9A-Z]{16}\b/g, "AKIA***").replace(/\b((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]+/gi, "$1***").replace(/(\b(?:[\w-]*[_-])?(?:api[_-]?key|key|token|secret|password|passwd|authorization)["']?\s*[=:]\s*)(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s&;,}\]"']+)/gi, "$1***").replace(/[A-Za-z0-9_-]{32,}/g, "***");
52257
+ }
52258
+ function maskKnownValues(s, knownValues) {
52259
+ let out = s;
52260
+ for (const v of knownValues) {
52261
+ if (typeof v === "string" && v.length >= 6)
52262
+ out = out.split(v).join("***");
52263
+ }
52264
+ return out;
52265
+ }
52266
+ function redactTurnOutcome(event, knownValues) {
52267
+ const redacted = { ...event };
52268
+ if (redacted.detail)
52269
+ redacted.detail = redactSecrets(redacted.detail, knownValues);
52270
+ if (redacted.raw) {
52271
+ redacted.raw = Object.fromEntries(Object.entries(redacted.raw).map(([k, v]) => [
52272
+ k,
52273
+ typeof v === "string" ? redactSecrets(v, knownValues) : v
52274
+ ]));
52275
+ }
52276
+ return redacted;
52277
+ }
52278
+ function describeTurnOutcomeFailure(outcome) {
52279
+ const retryNote = outcome.retryAt ? `, retry at ${outcome.retryAt}` : "";
52280
+ return {
52281
+ warn: `${outcome.outcome}${retryNote}${outcome.detail ? ` \u2014 ${outcome.detail}` : ""}`,
52282
+ stepMessage: `LLM turn ${outcome.outcome}${retryNote}${outcome.detail ? `: ${outcome.detail}` : ""}`
52283
+ };
52284
+ }
52285
+ function redactLogger(log2, knownValues) {
52286
+ if (!log2)
52287
+ return void 0;
52288
+ return {
52289
+ info: (message) => log2.info(redactSecrets(message, knownValues)),
52290
+ warn: (message) => log2.warn(redactSecrets(message, knownValues)),
52291
+ error: (message) => log2.error(redactSecrets(message, knownValues)),
52292
+ ...log2.child ? { child: (name) => redactLogger(log2.child(name), knownValues) } : {}
52293
+ };
52294
+ }
52295
+
52296
+ // ts/agent-core/dist/runtime-observation.js
52297
+ function runtimeObservation(runtimeSessionId, content) {
52298
+ return {
52299
+ type: "observation",
52300
+ observationId: randomUUID(),
52301
+ runtimeSessionId,
52302
+ content: { ...content, observed_at: (/* @__PURE__ */ new Date()).toISOString() }
52303
+ };
52304
+ }
52305
+ function observationField(value) {
52306
+ return typeof value === "string" && value.length > 0 && Buffer.byteLength(value, "utf8") <= 256 ? value : void 0;
52307
+ }
52308
+ async function persistRuntimeObservation(persister, sessionId, target, event, log2, knownSecrets = []) {
52309
+ const native = event.content.native && Object.fromEntries(Object.entries(event.content.native).map(([key, value]) => [
52310
+ key,
52311
+ typeof value !== "string" ? value : key.endsWith("_id") ? maskKnownValues(value, knownSecrets) : redactSecrets(value, knownSecrets)
52312
+ ]));
52313
+ try {
52314
+ await persister.persist(sessionId, "observation", {
52315
+ step_type: "observation",
52316
+ ...target,
52317
+ idempotency_key: `observation:${event.observationId}`,
52318
+ content: { ...event.content, ...native ? { native } : {} },
52319
+ projection: false
52320
+ });
52321
+ } catch (err) {
52322
+ log2?.warn(`runtime observation could not be saved for ${sessionId}: ${String(err)}`);
52323
+ }
52324
+ }
52325
+
52250
52326
  // ts/agent-core/dist/fork-prefix.js
52251
52327
  function sanitizeMeta(value) {
52252
52328
  return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
@@ -52285,6 +52361,108 @@ function buildForkResultPrefix(results) {
52285
52361
  return blocks.join("\n\n") + "\n\n---\n\n";
52286
52362
  }
52287
52363
 
52364
+ // ts/agent-core/dist/gateway-runtime-step.js
52365
+ import { randomUUID as randomUUID2 } from "node:crypto";
52366
+ async function createRuntimeStep(host, sessionId, target, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2) {
52367
+ switch (runtimeEvent.type) {
52368
+ case "observation":
52369
+ await persistRuntimeObservation(host.stepPersister, sessionId, target, runtimeEvent, host.opts?.log, host.opts?.config ? [host.opts.config.api_key] : []);
52370
+ break;
52371
+ case "thinking":
52372
+ await host.stepPersister.persist(sessionId, "thinking", {
52373
+ step_type: "thinking",
52374
+ target_type: target.target_type,
52375
+ target_id: target.target_id,
52376
+ idempotency_key: randomUUID2(),
52377
+ content: { text: runtimeEvent.text },
52378
+ group_key: runtimeEvent.groupKey
52379
+ });
52380
+ break;
52381
+ case "text":
52382
+ await host.stepPersister.persist(sessionId, "text", {
52383
+ step_type: "text",
52384
+ target_type: target.target_type,
52385
+ target_id: target.target_id,
52386
+ idempotency_key: randomUUID2(),
52387
+ content: {
52388
+ text: runtimeEvent.text,
52389
+ suppressed: runtimeEvent.project !== true
52390
+ },
52391
+ projection: runtimeEvent.project === true,
52392
+ group_key: runtimeEvent.groupKey
52393
+ });
52394
+ break;
52395
+ case "tool_call": {
52396
+ const step = await host.stepPersister.persist(sessionId, "tool_call", {
52397
+ step_type: "tool_call",
52398
+ target_type: target.target_type,
52399
+ target_id: target.target_id,
52400
+ // call_id is session-unique for bridge runtimes (server-enforced),
52401
+ // so the bare form anchors the tool step pair across retries —
52402
+ // unlike parel's turn-scoped `tc:{turnId}:{callId}` (see
52403
+ // protocol-vectors/agent-steps.json).
52404
+ idempotency_key: `tc:${runtimeEvent.callId}`,
52405
+ content: {
52406
+ call_id: runtimeEvent.callId,
52407
+ tool_name: runtimeEvent.toolName,
52408
+ tool_input: runtimeEvent.input,
52409
+ status: "running",
52410
+ started_at: runtimeEvent.startedAt ?? (/* @__PURE__ */ new Date()).toISOString()
52411
+ },
52412
+ group_key: runtimeEvent.groupKey,
52413
+ runtime_key: runtimeEvent.callId
52414
+ });
52415
+ if (step) {
52416
+ if (contextFilePath) {
52417
+ host.updateContextFileStepId(contextFilePath, step.id);
52418
+ } else if (stepIdFilePath) {
52419
+ host.writeStepIdFile(stepIdFilePath, step.id);
52420
+ }
52421
+ if (laneContextFilePath2) {
52422
+ host.updateContextFileStepId(laneContextFilePath2, step.id);
52423
+ }
52424
+ }
52425
+ break;
52426
+ }
52427
+ case "tool_result":
52428
+ await host.stepPersister.persist(sessionId, "tool_result", {
52429
+ step_type: "tool_result",
52430
+ target_type: target.target_type,
52431
+ target_id: target.target_id,
52432
+ idempotency_key: `tr:${runtimeEvent.callId}`,
52433
+ content: {
52434
+ call_id: runtimeEvent.callId,
52435
+ tool_name: runtimeEvent.toolName,
52436
+ status: runtimeEvent.error ? "error" : "success",
52437
+ output: runtimeEvent.output,
52438
+ duration_ms: runtimeEvent.durationMs ?? 0,
52439
+ collapsible: true
52440
+ },
52441
+ group_key: runtimeEvent.groupKey
52442
+ });
52443
+ if (contextFilePath) {
52444
+ host.updateContextFileStepId(contextFilePath, null);
52445
+ } else if (stepIdFilePath) {
52446
+ host.clearStepIdFile(stepIdFilePath);
52447
+ }
52448
+ if (laneContextFilePath2) {
52449
+ host.updateContextFileStepId(laneContextFilePath2, null);
52450
+ }
52451
+ break;
52452
+ case "error":
52453
+ await host.stepPersister.persist(sessionId, "error", {
52454
+ step_type: "text",
52455
+ target_type: target.target_type,
52456
+ target_id: target.target_id,
52457
+ idempotency_key: randomUUID2(),
52458
+ content: buildErrorStepContent(runtimeEvent.message),
52459
+ projection: false,
52460
+ group_key: runtimeEvent.groupKey
52461
+ });
52462
+ break;
52463
+ }
52464
+ }
52465
+
52288
52466
  // ts/agent-core/dist/dispatch-recovery.js
52289
52467
  var DispatchRecovery = class {
52290
52468
  scan;
@@ -52344,7 +52522,7 @@ function splitChangeSource(sourceId) {
52344
52522
  // ts/agent-core/dist/gateway-base.js
52345
52523
  import * as fs4 from "node:fs";
52346
52524
  import * as path5 from "node:path";
52347
- import { randomUUID as randomUUID2 } from "node:crypto";
52525
+ import { randomUUID as randomUUID4 } from "node:crypto";
52348
52526
 
52349
52527
  // ts/sdk/dist/browser-viewer.js
52350
52528
  var BROWSER_VIEWER_READINESS_TIMEOUT_MS = 6e4;
@@ -52357,6 +52535,20 @@ function browserViewerRequestOptions(command, opts) {
52357
52535
  };
52358
52536
  }
52359
52537
 
52538
+ // ts/sdk/dist/slack-endpoints.js
52539
+ function slackEndpoints(apiBase) {
52540
+ return {
52541
+ SLACK_CHANNELS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/channels`,
52542
+ SLACK_USERS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/users`,
52543
+ SLACK_REPLIES: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/replies`,
52544
+ SLACK_HISTORY: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/history`,
52545
+ SLACK_MEMBERS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/members`,
52546
+ SLACK_STATUS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/status`,
52547
+ SLACK_FILE: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/file`,
52548
+ SLACK_FILES: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/files`
52549
+ };
52550
+ }
52551
+
52360
52552
  // ts/sdk/dist/clip-connection-endpoints.js
52361
52553
  var clipConnectionEndpoints = {
52362
52554
  ORG_CLIP_MCP_OAUTH_ATTEMPT: (orgId, clipId, attemptId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-oauth-attempts/${attemptId}`,
@@ -52599,6 +52791,7 @@ var ENDPOINTS = {
52599
52791
  TASK_RELATIONS: (orgId, taskId) => `${API_BASE2}/orgs/${orgId}/tasks/${taskId}/relations`,
52600
52792
  TASK_RELATION: (orgId, taskId, relId) => `${API_BASE2}/orgs/${orgId}/tasks/${taskId}/relations/${relId}`,
52601
52793
  TASK_RELATIONS_BY_TARGET: (orgId) => `${API_BASE2}/orgs/${orgId}/task-relations`,
52794
+ TASK_DEPENDENCIES: (orgId, taskId) => `${API_BASE2}/orgs/${orgId}/tasks/${taskId}/dependencies`,
52602
52795
  TASK_COMMENTS: (orgId, taskId) => `${API_BASE2}/orgs/${orgId}/tasks/${taskId}/comments`,
52603
52796
  TASK_COMMENT: (orgId, taskId, commentId) => `${API_BASE2}/orgs/${orgId}/tasks/${taskId}/comments/${commentId}`,
52604
52797
  TASK_ACTIVITIES: (orgId, taskId) => `${API_BASE2}/orgs/${orgId}/tasks/${taskId}/activities`,
@@ -52685,13 +52878,7 @@ var ENDPOINTS = {
52685
52878
  // Tier-B platform verb (agent-only): send one message as the bound bot.
52686
52879
  CHANNEL_SEND: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/channel-send`,
52687
52880
  // Tier-B read verbs (agent-only): workspace visibility as the bot sees it.
52688
- SLACK_CHANNELS: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/channels`,
52689
- SLACK_USERS: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/users`,
52690
- SLACK_HISTORY: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/history`,
52691
- SLACK_MEMBERS: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/members`,
52692
- SLACK_STATUS: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/status`,
52693
- SLACK_FILE: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/file`,
52694
- SLACK_FILES: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/slack/files`,
52881
+ ...slackEndpoints(API_BASE2),
52695
52882
  // WeChat tier-B read verbs (agent-only; internal research preview).
52696
52883
  ...wechatEndpoints(API_BASE2),
52697
52884
  // Invitations (org-scoped, admin)
@@ -52723,6 +52910,11 @@ var ENDPOINTS = {
52723
52910
  WIKI_TREE: (orgId, wikiId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/tree`,
52724
52911
  WIKI_TREE_LAST_COMMITS: (orgId, wikiId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/tree/last-commits`,
52725
52912
  WIKI_BLOB: (orgId, wikiId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/blob`,
52913
+ // Wiki shared-draft room control plane (wiki-shared-draft-design.md §7).
52914
+ // Mounted only when cap:wiki-shared-drafts is on; absent otherwise.
52915
+ WIKI_DRAFT_OPEN: (orgId, wikiId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/drafts/open`,
52916
+ WIKI_DRAFT_STATUS: (orgId, wikiId, draftId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/drafts/${draftId}/status`,
52917
+ WIKI_DRAFT_SOCKET: (orgId, wikiId, draftId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/drafts/${draftId}/socket`,
52726
52918
  WIKI_COPY: (orgId, wikiId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/copy`,
52727
52919
  WIKI_NODE_SECTIONS: (orgId, wikiId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/node-sections`,
52728
52920
  WIKI_SEARCH: (orgId, wikiId) => `${WIKI_BASE}/orgs/${orgId}/wikis/${wikiId}/search`,
@@ -53108,6 +53300,13 @@ var ProjectTaskClient = class {
53108
53300
  async deleteTaskRelation(orgId, taskId, relationId) {
53109
53301
  return this.request("DELETE", ENDPOINTS.TASK_RELATION(orgId, taskId, relationId));
53110
53302
  }
53303
+ async getTaskDependencies(orgId, taskId) {
53304
+ const res = await this.request("GET", ENDPOINTS.TASK_DEPENDENCIES(orgId, taskId));
53305
+ return {
53306
+ blocked_by: res.blocked_by ?? [],
53307
+ blocking: res.blocking ?? []
53308
+ };
53309
+ }
53111
53310
  async getTaskComments(orgId, taskId, params) {
53112
53311
  return this.request("GET", ENDPOINTS.TASK_COMMENTS(orgId, taskId), void 0, params);
53113
53312
  }
@@ -53166,8 +53365,9 @@ var ProjectTaskClient = class {
53166
53365
  return res.data;
53167
53366
  }
53168
53367
  /** Public-tier self-admission: writes the caller's own member row.
53169
- * Other tiers answer `404 PROJECT_NOT_FOUND`; a duplicate answers
53170
- * `409 MEMBER_EXISTS`. */
53368
+ * Other tiers answer `403 PERMISSION_DENIED` with `details.project`
53369
+ * (its `visibility` tells whether to request-join or ask for an invite);
53370
+ * a duplicate answers `409 MEMBER_EXISTS`. */
53171
53371
  async joinProject(orgId, projectId) {
53172
53372
  return this.request("POST", ENDPOINTS.PROJECT_JOIN(orgId, projectId));
53173
53373
  }
@@ -53373,14 +53573,16 @@ var SlackFilesClient = class extends AttachmentClient {
53373
53573
  }
53374
53574
  /**
53375
53575
  * Tier-B file upload verb (agent-only): share a file into a Slack
53376
- * conversation this connection has seen inbound, with the same
53377
- * reply-anchor contract as the text send.
53576
+ * conversation or thread with the same addressing as text sends.
53577
+ * Native threadTs requires a server supporting Slack thread sends.
53378
53578
  */
53379
53579
  async sendSlackFile(orgId, input) {
53380
53580
  const fd = new FormData();
53381
53581
  fd.append("conversation_id", input.conversationId);
53382
53582
  if (input.replyTo)
53383
53583
  fd.append("reply_to", input.replyTo);
53584
+ if (input.threadTs)
53585
+ fd.append("thread_ts", input.threadTs);
53384
53586
  if (input.text)
53385
53587
  fd.append("text", input.text);
53386
53588
  fd.append("file", input.content, input.fileName);
@@ -53388,8 +53590,48 @@ var SlackFilesClient = class extends AttachmentClient {
53388
53590
  }
53389
53591
  };
53390
53592
 
53593
+ // ts/sdk/dist/slack-read-client.js
53594
+ var SlackReadClient = class extends SlackFilesClient {
53595
+ slackReadQuery(base, query, extra) {
53596
+ const params = new URLSearchParams();
53597
+ if (query?.cursor)
53598
+ params.set("cursor", query.cursor);
53599
+ if (query?.limit)
53600
+ params.set("limit", String(query.limit));
53601
+ for (const [k, v] of Object.entries(extra ?? {}))
53602
+ params.set(k, v);
53603
+ const qs = params.toString();
53604
+ return qs ? `${base}?${qs}` : base;
53605
+ }
53606
+ /**
53607
+ * Tier-B read verbs (agent-only): workspace visibility as the bot sees
53608
+ * it. Same live gate as the send verb; authorization beyond it is the
53609
+ * bot's own Slack permissions.
53610
+ */
53611
+ async listSlackChannels(orgId, query) {
53612
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_CHANNELS(orgId), query));
53613
+ }
53614
+ async listSlackUsers(orgId, query) {
53615
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_USERS(orgId), query));
53616
+ }
53617
+ async slackHistory(orgId, conversationId, query) {
53618
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_HISTORY(orgId), query, { conversation: conversationId }));
53619
+ }
53620
+ /** Read a Slack thread (parent and replies), one page in Slack order. */
53621
+ async slackReplies(orgId, channel, ts, query) {
53622
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_REPLIES(orgId), query, { channel, ts }));
53623
+ }
53624
+ async slackMembers(orgId, conversationId, query) {
53625
+ return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_MEMBERS(orgId), query, { conversation: conversationId }));
53626
+ }
53627
+ /** Set/clear the Agents-pane "typing…" indicator (best-effort cosmetic). */
53628
+ async setSlackStatus(orgId, input) {
53629
+ await this.request("POST", ENDPOINTS.SLACK_STATUS(orgId), input);
53630
+ }
53631
+ };
53632
+
53391
53633
  // ts/sdk/dist/channel-conversation-client.js
53392
- var ChannelConversationClient = class extends SlackFilesClient {
53634
+ var ChannelConversationClient = class extends SlackReadClient {
53393
53635
  /**
53394
53636
  * Org-admin write of what the agent receives from a group root
53395
53637
  * (`PATCH …/channel-conversations/{id}/attention`); the agent's own path
@@ -53485,6 +53727,91 @@ var BrowserProfileClient = class extends ClipConnectionClient {
53485
53727
  }
53486
53728
  };
53487
53729
 
53730
+ // ts/sdk/dist/wiki-draft-types.js
53731
+ var WIKI_DRAFT_SCHEMA_VERSION = 1;
53732
+ var IDENTIFIER = /^[A-Za-z0-9_.:-]{1,128}$/;
53733
+ function isWikiDraftScope(value) {
53734
+ if (!value || typeof value !== "object")
53735
+ return false;
53736
+ const scope = value;
53737
+ return ["lane", "org_id", "wiki_id", "draft_id", "incarnation"].every((key) => typeof scope[key] === "string" && IDENTIFIER.test(scope[key])) && Number.isSafeInteger(scope.generation) && scope.generation >= 1;
53738
+ }
53739
+ function sameWikiDraftScope(left, right) {
53740
+ return left.lane === right.lane && left.org_id === right.org_id && left.wiki_id === right.wiki_id && left.draft_id === right.draft_id && left.incarnation === right.incarnation && left.generation === right.generation;
53741
+ }
53742
+ var WIRE_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2}))$/;
53743
+ function isWireTimestamp(value) {
53744
+ if (typeof value !== "string")
53745
+ return false;
53746
+ const m = WIRE_TIMESTAMP.exec(value);
53747
+ if (!m)
53748
+ return false;
53749
+ const [year, month, day, hour, minute, second] = m.slice(1, 7).map(Number);
53750
+ if (month < 1 || month > 12)
53751
+ return false;
53752
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
53753
+ const daysInMonth = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
53754
+ if (day < 1 || day > daysInMonth)
53755
+ return false;
53756
+ if (hour > 23 || minute > 59 || second > 59)
53757
+ return false;
53758
+ if (m[7] !== void 0 && (Number(m[7]) > 23 || Number(m[8]) > 59))
53759
+ return false;
53760
+ return true;
53761
+ }
53762
+ function isWikiDraftConnection(value) {
53763
+ if (!value || typeof value !== "object")
53764
+ return false;
53765
+ const c = value;
53766
+ return isWikiDraftScope(c.scope) && c.schema_version === WIKI_DRAFT_SCHEMA_VERSION && Number.isSafeInteger(c.seq) && c.seq >= 0 && typeof c.actor_id === "string" && c.actor_id.length > 0 && typeof c.actor_token === "string" && c.actor_token.length > 0 && typeof c.websocket_url === "string" && c.websocket_url.startsWith("/") && isWireTimestamp(c.issued_at) && isWireTimestamp(c.expires_at);
53767
+ }
53768
+ function isWikiDraftStatus(value) {
53769
+ if (!value || typeof value !== "object")
53770
+ return false;
53771
+ const s = value;
53772
+ const owner = s.owner;
53773
+ return isWikiDraftScope(s.scope) && typeof s.path === "string" && s.schema_version === WIKI_DRAFT_SCHEMA_VERSION && Number.isSafeInteger(s.seq) && s.seq >= 0 && typeof s.base_commit === "string" && typeof s.base_blob === "string" && (s.state === "active" || s.state === "conflicted" || s.state === "retired") && (owner === null || !!owner && typeof owner === "object" && typeof owner.instance === "string" && Number.isSafeInteger(owner.epoch) && isWireTimestamp(owner.lease_deadline)) && isWireTimestamp(s.updated_at);
53774
+ }
53775
+
53776
+ // ts/sdk/dist/wiki-draft-client.js
53777
+ var WikiDraftClient = class extends BrowserProfileClient {
53778
+ /**
53779
+ * Open (or rejoin) the shared draft of an existing formal Markdown path.
53780
+ * No content is uploaded; the server pins the Git baseline itself.
53781
+ * Only call this when `cap:wiki-shared-drafts` and the org flag are on —
53782
+ * the routes do not exist otherwise.
53783
+ */
53784
+ async openWikiDraft(orgId, wikiId, path14, opts) {
53785
+ const connection = await this.request("POST", ENDPOINTS.WIKI_DRAFT_OPEN(orgId, wikiId), { path: path14 }, void 0, false, opts);
53786
+ if (!isWikiDraftConnection(connection) || connection.scope.org_id !== orgId || connection.scope.wiki_id !== wikiId) {
53787
+ throw new Error("DRAFT_SCOPE");
53788
+ }
53789
+ const socketPath = ENDPOINTS.WIKI_DRAFT_SOCKET(orgId, wikiId, connection.scope.draft_id);
53790
+ if (connection.websocket_url !== socketPath)
53791
+ throw new Error("DRAFT_SCOPE");
53792
+ const base = this.baseUrlFor(socketPath);
53793
+ const locationOrigin = typeof globalThis.location === "undefined" ? void 0 : globalThis.location.origin;
53794
+ const socket = new URL(`${base}${socketPath}`, locationOrigin);
53795
+ if (!["http:", "https:"].includes(socket.protocol) || socket.username || socket.password || socket.search || socket.hash) {
53796
+ throw new Error("DRAFT_SCOPE");
53797
+ }
53798
+ socket.protocol = socket.protocol === "https:" ? "wss:" : "ws:";
53799
+ return { ...connection, websocket_url: socket.href };
53800
+ }
53801
+ /** Durable draft metadata under the caller's current read permission. Never uploads content. */
53802
+ async getWikiDraftStatus(scope, opts) {
53803
+ const status = await this.request("GET", ENDPOINTS.WIKI_DRAFT_STATUS(scope.org_id, scope.wiki_id, scope.draft_id), void 0, { lane: scope.lane, incarnation: scope.incarnation, generation: String(scope.generation) }, false, opts);
53804
+ if (!isWikiDraftStatus(status) || !sameWikiDraftScope(status.scope, scope)) {
53805
+ throw new Error("DRAFT_SCOPE");
53806
+ }
53807
+ return status;
53808
+ }
53809
+ /** Subprotocol tokens for the room WebSocket handshake: protocol + ticket. */
53810
+ wikiDraftSocketProtocols(connection) {
53811
+ return ["parall.wiki.v1", `ticket.${connection.actor_token}`];
53812
+ }
53813
+ };
53814
+
53488
53815
  // ts/sdk/dist/wiki-upload.js
53489
53816
  function createWikiUploadFormData(params) {
53490
53817
  const form = new FormData();
@@ -53621,7 +53948,7 @@ function legacyHeartbeatFromReport(report) {
53621
53948
  detectedRuntimes
53622
53949
  };
53623
53950
  }
53624
- var ParallClient = class _ParallClient extends BrowserProfileClient {
53951
+ var ParallClient = class _ParallClient extends WikiDraftClient {
53625
53952
  baseUrl;
53626
53953
  wikiBaseUrl;
53627
53954
  token;
@@ -55063,38 +55390,6 @@ var ParallClient = class _ParallClient extends BrowserProfileClient {
55063
55390
  async sendChannelMessage(orgId, input) {
55064
55391
  return this.request("POST", ENDPOINTS.CHANNEL_SEND(orgId), input);
55065
55392
  }
55066
- slackReadQuery(base, query, extra) {
55067
- const params = new URLSearchParams();
55068
- if (query?.cursor)
55069
- params.set("cursor", query.cursor);
55070
- if (query?.limit)
55071
- params.set("limit", String(query.limit));
55072
- for (const [k, v] of Object.entries(extra ?? {}))
55073
- params.set(k, v);
55074
- const qs = params.toString();
55075
- return qs ? `${base}?${qs}` : base;
55076
- }
55077
- /**
55078
- * Tier-B read verbs (agent-only): workspace visibility as the bot sees
55079
- * it. Same live gate as the send verb; authorization beyond it is the
55080
- * bot's own Slack permissions.
55081
- */
55082
- async listSlackChannels(orgId, query) {
55083
- return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_CHANNELS(orgId), query));
55084
- }
55085
- async listSlackUsers(orgId, query) {
55086
- return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_USERS(orgId), query));
55087
- }
55088
- async slackHistory(orgId, conversationId, query) {
55089
- return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_HISTORY(orgId), query, { conversation: conversationId }));
55090
- }
55091
- async slackMembers(orgId, conversationId, query) {
55092
- return this.request("GET", this.slackReadQuery(ENDPOINTS.SLACK_MEMBERS(orgId), query, { conversation: conversationId }));
55093
- }
55094
- /** Set/clear the Agents-pane "typing…" indicator (best-effort cosmetic). */
55095
- async setSlackStatus(orgId, input) {
55096
- await this.request("POST", ENDPOINTS.SLACK_STATUS(orgId), input);
55097
- }
55098
55393
  /**
55099
55394
  * Authorized raw GET (binary responses) with the same auth, 401
55100
55395
  * refresh-and-retry-once, and error-envelope handling as `request` — the
@@ -56809,1773 +57104,1881 @@ function createActiveForkState(fork, targetId, continuationPrefix) {
56809
57104
  };
56810
57105
  }
56811
57106
 
56812
- // ts/agent-core/dist/redact.js
56813
- function redactSecrets(s, knownValues = []) {
56814
- return maskKnownValues(s, knownValues).replace(/\b(agk|mck|cpk)_[A-Za-z0-9_-]+/g, "$1_***").replace(/\b(sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "$1-***").replace(/\bAKIA[0-9A-Z]{16}\b/g, "AKIA***").replace(/\b((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]+/gi, "$1***").replace(/(\b(?:[\w-]*[_-])?(?:api[_-]?key|key|token|secret|password|passwd|authorization)["']?\s*[=:]\s*)(?:"(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\s&;,}\]"']+)/gi, "$1***").replace(/[A-Za-z0-9_-]{32,}/g, "***");
57107
+ // ts/agent-core/dist/gateway-steer.js
57108
+ var pendingSteers = /* @__PURE__ */ new WeakMap();
57109
+ function hasMainSteers(state) {
57110
+ return (pendingSteers.get(state)?.size ?? 0) > 0;
56815
57111
  }
56816
- function maskKnownValues(s, knownValues) {
56817
- let out = s;
56818
- for (const v of knownValues) {
56819
- if (typeof v === "string" && v.length >= 6)
56820
- out = out.split(v).join("***");
56821
- }
56822
- return out;
57112
+ async function waitForMainSteers(state) {
57113
+ await Promise.allSettled(pendingSteers.get(state) ?? []);
56823
57114
  }
56824
- function redactTurnOutcome(event, knownValues) {
56825
- const redacted = { ...event };
56826
- if (redacted.detail)
56827
- redacted.detail = redactSecrets(redacted.detail, knownValues);
56828
- if (redacted.raw) {
56829
- redacted.raw = Object.fromEntries(Object.entries(redacted.raw).map(([k, v]) => [
56830
- k,
56831
- typeof v === "string" ? redactSecrets(v, knownValues) : v
56832
- ]));
57115
+ async function steerLaneMessage(host, event) {
57116
+ let pending = pendingSteers.get(host.dispatchState);
57117
+ if (!pending) {
57118
+ pending = /* @__PURE__ */ new Set();
57119
+ pendingSteers.set(host.dispatchState, pending);
57120
+ }
57121
+ const work = Promise.resolve().then(() => steerLaneMessageInner(host, event));
57122
+ pending.add(work);
57123
+ try {
57124
+ await work;
57125
+ } finally {
57126
+ pending.delete(work);
57127
+ if (pending.size === 0)
57128
+ pendingSteers.delete(host.dispatchState);
57129
+ host.notifyDrainWaiters?.();
56833
57130
  }
56834
- return redacted;
56835
57131
  }
56836
- function describeTurnOutcomeFailure(outcome) {
56837
- const retryNote = outcome.retryAt ? `, retry at ${outcome.retryAt}` : "";
56838
- return {
56839
- warn: `${outcome.outcome}${retryNote}${outcome.detail ? ` \u2014 ${outcome.detail}` : ""}`,
56840
- stepMessage: `LLM turn ${outcome.outcome}${retryNote}${outcome.detail ? `: ${outcome.detail}` : ""}`
56841
- };
57132
+ function hasUninjectedSameLaneEventAhead(host, event) {
57133
+ const eventIndex = host.dispatchState.mainBuffer.lastIndexOf(event);
57134
+ if (eventIndex <= 0)
57135
+ return false;
57136
+ const groupKey = host.dispatchGroupKey(event);
57137
+ return host.dispatchState.mainBuffer.slice(0, eventIndex).some((buffered) => host.dispatchGroupKey(buffered) === groupKey && !host.injectedMainBufferEvents.has(buffered));
56842
57138
  }
56843
- function redactLogger(log2, knownValues) {
56844
- if (!log2)
56845
- return void 0;
56846
- return {
56847
- info: (message) => log2.info(redactSecrets(message, knownValues)),
56848
- warn: (message) => log2.warn(redactSecrets(message, knownValues)),
56849
- error: (message) => log2.error(redactSecrets(message, knownValues)),
56850
- ...log2.child ? { child: (name) => redactLogger(log2.child(name), knownValues) } : {}
56851
- };
57139
+ async function steerLaneMessageInner(host, event) {
57140
+ const { laneLedger: ledger, opts } = host;
57141
+ const adapter = opts.dispatchAdapter;
57142
+ if (!ledger || !adapter.enqueueDuringDispatch)
57143
+ return;
57144
+ if (hasUninjectedSameLaneEventAhead(host, event))
57145
+ return;
57146
+ const folded = await ledger.steerLive(event);
57147
+ if (!folded)
57148
+ return;
57149
+ if (!folded.frame)
57150
+ return;
57151
+ event.frame = folded.frame;
57152
+ const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, eventBody(event), folded.inputLifecycle);
57153
+ if (injected) {
57154
+ host.injectedMainBufferEvents.add(event);
57155
+ ledger.markSeen(event, folded.covered);
57156
+ opts.log?.info(`steer frame handed to adapter for ${event.messageId} (will drain for bookkeeping)`);
57157
+ } else if (folded.frame) {
57158
+ ledger.deferFrame(event, folded.frame, folded.covered);
57159
+ opts.log?.info(`steer folded but not injected for ${event.messageId} \u2014 frame deferred to the drain`);
57160
+ }
56852
57161
  }
56853
57162
 
56854
- // ts/agent-core/dist/lane-ledger.js
56855
- import * as fs2 from "node:fs";
56856
-
56857
- // ts/agent-core/dist/lane-key.js
56858
- import * as path2 from "node:path";
56859
- function laneKeyForTarget(targetUri, threadRootId) {
56860
- return Buffer.from(`${targetUri}
56861
- ${threadRootId ?? ""}`, "utf8").toString("base64url");
56862
- }
56863
- function dispatchLaneContextDir(stateDir) {
56864
- return path2.join(stateDir, "dispatch-lane-context");
56865
- }
56866
- function laneContextFilePath(contextDir, targetUri, threadRootId) {
56867
- return path2.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
56868
- }
57163
+ // ts/agent-core/dist/telemetry.js
57164
+ init_esm();
57165
+ var import_api_logs = __toESM(require_src(), 1);
57166
+ import { AsyncLocalStorage } from "node:async_hooks";
57167
+ import { readFileSync as readFileSync2 } from "node:fs";
57168
+ import * as path3 from "node:path";
57169
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
56869
57170
 
56870
- // ts/agent-core/dist/lane-target.js
56871
- var PRLL_SCHEME = "prll://";
56872
- var CHAT_LANE_PREFIX = "cht_";
56873
- var CHANNEL_LANE_PREFIX = `${PRLL_SCHEME}chv_`;
56874
- function channelLaneTargetUri(item) {
56875
- return item.event_type === "channel_message" && item.target_uri?.startsWith(CHANNEL_LANE_PREFIX) ? item.target_uri : void 0;
56876
- }
56877
- function laneTargetId(targetUri) {
56878
- return targetUri.startsWith(PRLL_SCHEME) ? targetUri.slice(PRLL_SCHEME.length) : targetUri;
57171
+ // ts/agent-core/dist/otlp-spool.js
57172
+ import * as fs2 from "node:fs";
57173
+ import * as fsp from "node:fs/promises";
57174
+ import * as path2 from "node:path";
57175
+ var SPOOL_SIGNALS = ["traces", "metrics", "logs"];
57176
+ var DEFAULT_MAX_BYTES = {
57177
+ traces: 6 << 20,
57178
+ logs: 8 << 20,
57179
+ metrics: 2 << 20
57180
+ };
57181
+ var DEFAULT_MIN_INTERVAL_MS = { metrics: 6e4 };
57182
+ var DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
57183
+ var DEFAULT_REPLAY_INTERVAL_MS = 6e4;
57184
+ var DEFAULT_REPLAY_BUDGET = { files: 200, wallMs: 2e4 };
57185
+ var REPLAY_REQUEST_TIMEOUT_MS = 1e4;
57186
+ var STALE_TMP_MS = 6e4;
57187
+ var FILE_RE = /^(\d{13})-(\d+)-(\d{6})\.pb$/;
57188
+ var PERMANENT_STATUSES = /* @__PURE__ */ new Set([400, 401, 403, 404, 413, 415]);
57189
+ function isPermanentStatus(status) {
57190
+ return PERMANENT_STATUSES.has(status);
56879
57191
  }
56880
- function laneTargetUri(event) {
56881
- if (event.type === "message") {
56882
- return event.targetId.startsWith(CHAT_LANE_PREFIX) ? `${PRLL_SCHEME}${event.targetId}` : void 0;
56883
- }
56884
- if (event.type === "channel_message") {
56885
- return event.targetUri?.startsWith(CHANNEL_LANE_PREFIX) ? event.targetUri : void 0;
57192
+ function classifyExportError(err) {
57193
+ if (!err || typeof err !== "object")
57194
+ return "transient";
57195
+ const e = err;
57196
+ if (e.name === "OTLPExporterError" && typeof e.code === "number") {
57197
+ return isPermanentStatus(e.code) ? "permanent" : "transient";
56886
57198
  }
56887
- return void 0;
56888
- }
56889
- function isTypedEvent(event) {
56890
- return event.type !== "message" && laneTargetUri(event) === void 0;
56891
- }
56892
-
56893
- // ts/agent-core/dist/lane-outcome.js
56894
- function errorWireClass(cls) {
56895
- if (!cls || cls === "ok" || cls === "usage_limit")
56896
- return void 0;
56897
- return cls;
56898
- }
56899
-
56900
- // ts/agent-core/dist/runtime-instance.js
56901
- import { randomUUID } from "node:crypto";
56902
- function newRuntimeInstanceId() {
56903
- return randomUUID().replace(/-/g, "");
56904
- }
56905
- function isTurnToken(token) {
56906
- return token.startsWith("turn_");
57199
+ if (e.message === "Nothing to send")
57200
+ return "empty";
57201
+ return "transient";
56907
57202
  }
56908
-
56909
- // ts/agent-core/dist/lane-input-receipts.js
56910
- var LaneInputReceipts = class {
57203
+ var OtlpSpoolStore = class {
56911
57204
  opts;
56912
- confirmations;
56913
- constructor(opts, confirmations) {
57205
+ index = /* @__PURE__ */ new Map();
57206
+ maxBytes;
57207
+ minIntervalMs;
57208
+ maxAgeMs;
57209
+ budget;
57210
+ fetchImpl;
57211
+ now;
57212
+ log;
57213
+ /** Files whose replay POST succeeded but whose unlink failed — never resent by this process. */
57214
+ sent = /* @__PURE__ */ new Set();
57215
+ seq = 0;
57216
+ writes = Promise.resolve();
57217
+ replaying = null;
57218
+ replayWanted = false;
57219
+ timer = null;
57220
+ closed = false;
57221
+ constructor(opts) {
56914
57222
  this.opts = opts;
56915
- this.confirmations = confirmations;
56916
- }
56917
- lifecycle(lane, messageIds) {
56918
- const explicit = lane.coverageMode === "explicit";
56919
- const unique = [...new Set(messageIds)];
56920
- const dispatchEventIds = unique.map((messageId) => lane.folded.get(messageId)).filter((id) => Boolean(id));
56921
- if (explicit && dispatchEventIds.length !== unique.length) {
56922
- throw new Error(`explicit lane ${lane.lane} is missing a folded WorkItem mapping`);
57223
+ this.maxBytes = { ...DEFAULT_MAX_BYTES, ...opts.maxBytes };
57224
+ this.minIntervalMs = { ...DEFAULT_MIN_INTERVAL_MS, ...opts.minIntervalMs };
57225
+ this.maxAgeMs = opts.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
57226
+ this.budget = opts.replayBudget ?? DEFAULT_REPLAY_BUDGET;
57227
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
57228
+ this.now = opts.now ?? Date.now;
57229
+ this.log = opts.log ?? ((msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] ${msg}`));
57230
+ const interval = opts.replayIntervalMs ?? DEFAULT_REPLAY_INTERVAL_MS;
57231
+ if (interval > 0) {
57232
+ this.timer = setInterval(() => {
57233
+ if (fs2.existsSync(opts.dir))
57234
+ void this.replay();
57235
+ }, interval);
57236
+ this.timer.unref();
56923
57237
  }
56924
- if (!explicit && dispatchEventIds.length === 0)
56925
- return void 0;
56926
- return {
56927
- deliveryKey: dispatchEventIds.join(","),
56928
- dispatchEventIds,
56929
- update: explicit ? (state, failure) => this.updateInputState(lane, dispatchEventIds, state, failure) : async () => void 0
56930
- };
56931
57238
  }
56932
- async updateInputState(lane, dispatchEventIds, state, failure) {
56933
- lane.observedInputs ??= /* @__PURE__ */ new Map();
56934
- for (const id of dispatchEventIds)
56935
- lane.observedInputs.set(id, state);
56936
- let confirmed;
56937
- const ids = [...dispatchEventIds];
56938
- const failed = new Set(state === "failed" ? ids : []);
56939
- const sourceIds = [...lane.folded].filter(([, id]) => failed.has(id)).map(([id]) => id);
56940
- const request3 = {
56941
- lane: lane.lane,
56942
- target_uri: lane.targetUri,
56943
- thread_root_id: lane.threadRootId,
56944
- dispatch_event_ids: ids,
56945
- state,
56946
- session_id: lane.sessionAmbiguous ? void 0 : lane.sessionId,
56947
- ...state === "failed" && failure ? {
56948
- outcome_class: errorWireClass(failure.outcomeClass),
56949
- detail: failure.detail ? redactSecrets(failure.detail, this.opts.knownSecrets).slice(0, 500) : void 0
56950
- } : {}
56951
- };
56952
- await this.confirmations.submit(lane.lane, {
56953
- label: `input ${state}`,
56954
- send: async () => {
56955
- const restore = sourceIds.length ? this.opts.releaseLocalClaims?.(sourceIds) : void 0;
56956
- let result;
56957
- try {
56958
- result = await this.opts.client.updateDispatchInputState(this.opts.orgId, request3);
56959
- } catch (err) {
56960
- restore?.();
56961
- throw err;
56962
- }
56963
- if (result.recognized !== ids.length && !isTurnToken(lane.lane)) {
56964
- restore?.();
56965
- throw new ApiError(409, "input acknowledgement scope changed", "INPUT_SCOPE_CHANGED");
56966
- }
56967
- if (state === "failed") {
56968
- for (const sourceId of sourceIds) {
56969
- lane.folded.delete(sourceId);
56970
- lane.seen.delete(sourceId);
56971
- }
56972
- }
56973
- confirmed = { retry: state === "failed" && result.released > 0 };
56974
- }
56975
- });
56976
- return confirmed ?? { retry: false, pending: true };
57239
+ get dir() {
57240
+ return this.opts.dir;
56977
57241
  }
56978
- async syncAttribution(lane) {
56979
- if (lane.settlementMode !== "receipt" || lane.settling || lane.sessionAmbiguous || !lane.sessionId || !lane.observedInputs?.size)
56980
- return;
56981
- const sessionId = lane.sessionId;
56982
- const groups = /* @__PURE__ */ new Map();
56983
- for (const [id, state] of lane.observedInputs) {
56984
- const ids = groups.get(state) ?? [];
56985
- ids.push(id);
56986
- groups.set(state, ids);
56987
- }
56988
- for (const [state, ids] of groups) {
56989
- await this.confirmations.submit(lane.lane, {
56990
- label: "input session",
56991
- send: async () => {
56992
- await this.opts.client.updateDispatchInputState(this.opts.orgId, {
56993
- lane: lane.lane,
56994
- target_uri: lane.targetUri,
56995
- thread_root_id: lane.threadRootId,
56996
- dispatch_event_ids: ids,
56997
- state,
56998
- session_id: sessionId
56999
- });
57000
- }
57001
- });
57002
- }
57242
+ /** Count a batch the exporter dropped for a permanent status (never spooled). */
57243
+ recordDrop(signal, reason, count = 1) {
57244
+ this.opts.onEvent?.({ kind: "dropped", signal, reason, count });
57003
57245
  }
57004
- };
57005
-
57006
- // ts/agent-core/dist/lane-confirmations.js
57007
- var LaneConfirmations = class {
57008
- opts;
57009
- pending = /* @__PURE__ */ new Map();
57010
- disposed = false;
57011
- constructor(opts) {
57012
- this.opts = opts;
57246
+ /**
57247
+ * Append one serialized request. Resolves once the file is renamed into
57248
+ * place (or the batch was dropped). Writes are serialized so the eviction
57249
+ * accounting never races. Never rejects.
57250
+ */
57251
+ enqueue(signal, bytes) {
57252
+ const run = this.writes.then(() => this.enqueueNow(signal, bytes)).catch(() => "write_failed");
57253
+ this.writes = run;
57254
+ return run;
57013
57255
  }
57014
- /** Try once inline; a retained write returns without blocking native execution. */
57015
- async submit(token, write) {
57016
- if (this.disposed)
57017
- return;
57018
- let pending = this.pending.get(token);
57019
- if (pending) {
57020
- if (pending.blocked)
57021
- return;
57022
- pending.writes.push(write);
57023
- return;
57256
+ async enqueueNow(signal, bytes) {
57257
+ if (this.closed)
57258
+ return "write_failed";
57259
+ const drop = (reason) => {
57260
+ this.recordDrop(signal, reason);
57261
+ return reason;
57262
+ };
57263
+ if (bytes.length > this.maxBytes[signal])
57264
+ return drop("oversized");
57265
+ const idx = await this.load(signal);
57266
+ const now = this.now();
57267
+ const minInterval = this.minIntervalMs[signal] ?? 0;
57268
+ const newest = idx.files[idx.files.length - 1];
57269
+ if (minInterval > 0 && newest && now - newest.ts < minInterval)
57270
+ return drop("throttled");
57271
+ await this.evictExpired(signal, idx, now);
57272
+ while (idx.files.length > 0 && idx.total + bytes.length > this.maxBytes[signal]) {
57273
+ if (!await this.remove(signal, idx, idx.files[0]))
57274
+ return drop("write_failed");
57275
+ this.recordDrop(signal, "evicted_size");
57024
57276
  }
57025
- pending = { writes: [write], failures: 0, blocked: false };
57026
- this.pending.set(token, pending);
57027
- await this.run(token, pending);
57028
- }
57029
- async run(token, pending) {
57030
- if (pending.running || pending.blocked || this.pending.get(token) !== pending)
57031
- return;
57032
- const recovered = pending.failures > 0;
57033
- pending.running = Promise.resolve().then(async () => {
57034
- while (pending.writes.length && this.pending.get(token) === pending) {
57035
- const write = pending.writes[0];
57277
+ const name = `${String(now).padStart(13, "0")}-${process.pid}-${String(this.seq++).padStart(6, "0")}.pb`;
57278
+ const dir = this.signalDir(signal);
57279
+ try {
57280
+ await fsp.mkdir(dir, { recursive: true });
57281
+ const tmp = path2.join(dir, `${name}.tmp`);
57282
+ await fsp.writeFile(tmp, bytes);
57283
+ await fsp.rename(tmp, path2.join(dir, name));
57284
+ } catch (err) {
57285
+ this.log(`spool write failed for ${signal}: ${String(err)}`);
57286
+ return drop("write_failed");
57287
+ }
57288
+ idx.files.push({ name, bytes: bytes.length, ts: now });
57289
+ idx.total += bytes.length;
57290
+ this.opts.onEvent?.({ kind: "queued", signal, bytes: bytes.length });
57291
+ this.log(`spooled ${signal} ${bytes.length}B for replay (${idx.files.length} files, ${idx.total}B queued)`);
57292
+ return "queued";
57293
+ }
57294
+ /** The endpoint answered a live export: replay what waits, if anything does. */
57295
+ notifyOnline() {
57296
+ if (this.closed)
57297
+ return;
57298
+ this.replayWanted = true;
57299
+ if (fs2.existsSync(this.opts.dir))
57300
+ void this.replay();
57301
+ }
57302
+ /**
57303
+ * Oldest-first replay across all signals, single-flight, bounded per pass;
57304
+ * stops at the first transient failure and leaves the rest for the next
57305
+ * pass. Never rejects.
57306
+ */
57307
+ replay() {
57308
+ if (this.replaying)
57309
+ return this.replaying;
57310
+ this.replayWanted = false;
57311
+ this.replaying = this.replayNow().catch((err) => {
57312
+ this.log(`spool replay failed: ${String(err)}`);
57313
+ return { replayed: 0, dropped: 0, deferred: true };
57314
+ }).finally(() => {
57315
+ this.replaying = null;
57316
+ if (this.replayWanted && !this.closed)
57317
+ void this.replay();
57318
+ });
57319
+ return this.replaying;
57320
+ }
57321
+ async replayNow() {
57322
+ const started = this.now();
57323
+ let replayed = 0;
57324
+ let dropped = 0;
57325
+ let sentFiles = 0;
57326
+ for (const signal of SPOOL_SIGNALS) {
57327
+ const idx = await this.load(signal);
57328
+ await this.evictExpired(signal, idx, started);
57329
+ for (const file of [...idx.files]) {
57330
+ if (this.closed)
57331
+ return { replayed, dropped, deferred: true };
57332
+ if (sentFiles >= this.budget.files || this.now() - started > this.budget.wallMs) {
57333
+ return { replayed, dropped, deferred: true };
57334
+ }
57335
+ if (this.sent.has(file.name))
57336
+ continue;
57337
+ const full = path2.join(this.signalDir(signal), file.name);
57338
+ let body;
57036
57339
  try {
57037
- await write.send();
57038
- pending.writes.shift();
57340
+ body = await fsp.readFile(full);
57039
57341
  } catch (err) {
57040
- if (this.pending.get(token) !== pending)
57041
- return;
57042
- if (err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE") {
57043
- this.pending.delete(token);
57044
- this.opts.onStale(token);
57045
- this.opts.onRecovered?.();
57046
- return;
57342
+ const missing = err.code === "ENOENT";
57343
+ if (await this.remove(signal, idx, file, missing)) {
57344
+ if (!missing) {
57345
+ this.recordDrop(signal, "unreadable");
57346
+ dropped += 1;
57347
+ }
57047
57348
  }
57048
- const transient = !(err instanceof ApiError) || err.status === 0 || err.status >= 500 || err.status === 408 || err.status === 429;
57049
- if (!transient) {
57050
- pending.blocked = true;
57051
- this.opts.log?.error(`lane ${write.label} rejected for ${token}; confirmation retained: ${String(err)}`);
57052
- return;
57349
+ continue;
57350
+ }
57351
+ const outcome = await this.post(signal, body);
57352
+ sentFiles += 1;
57353
+ if (outcome === "ok" || outcome === "permanent") {
57354
+ if (!await this.remove(signal, idx, file))
57355
+ this.sent.add(file.name);
57356
+ if (outcome === "ok") {
57357
+ this.opts.onEvent?.({ kind: "replayed", signal, bytes: file.bytes });
57358
+ replayed += 1;
57359
+ } else {
57360
+ this.recordDrop(signal, "permanent_status");
57361
+ dropped += 1;
57053
57362
  }
57054
- pending.failures += 1;
57055
- this.opts.log?.warn(`lane ${write.label} unconfirmed for ${token}; retry ${pending.failures}: ${String(err)}`);
57056
- const delays = this.opts.delaysMs?.length ? this.opts.delaysMs : [2e3, 1e4, 3e4, 6e4, 12e4];
57057
- const delay = delays[Math.min(pending.failures - 1, delays.length - 1)];
57058
- pending.timer = setTimeout(() => {
57059
- pending.timer = void 0;
57060
- void this.run(token, pending);
57061
- }, delay);
57062
- pending.timer.unref?.();
57063
- return;
57363
+ } else {
57364
+ return { replayed, dropped, deferred: true };
57064
57365
  }
57065
57366
  }
57066
- if (this.pending.get(token) === pending)
57067
- this.pending.delete(token);
57068
- if (recovered)
57069
- this.opts.onRecovered?.();
57070
- });
57071
- try {
57072
- await pending.running;
57073
- } finally {
57074
- pending.running = void 0;
57075
57367
  }
57368
+ if (replayed > 0)
57369
+ this.log(`spool replayed ${replayed} file(s)`);
57370
+ return { replayed, dropped, deferred: false };
57076
57371
  }
57077
- /** Reconnect/shutdown may accelerate retries; permanent rejections stay visible. */
57078
- async retryNow() {
57079
- await Promise.all([...this.pending].map(async ([token, pending]) => {
57080
- if (pending.timer)
57081
- clearTimeout(pending.timer);
57082
- pending.timer = void 0;
57083
- await this.run(token, pending);
57084
- }));
57085
- }
57086
- forget(token) {
57087
- const pending = this.pending.get(token);
57088
- if (pending?.timer)
57089
- clearTimeout(pending.timer);
57090
- this.pending.delete(token);
57372
+ async post(signal, body) {
57373
+ try {
57374
+ const res = await this.fetchImpl(`${this.opts.endpoint}/v1/${signal}`, {
57375
+ method: "POST",
57376
+ headers: { ...this.opts.headers, "Content-Type": "application/x-protobuf" },
57377
+ // A Buffer may sit on a shared ArrayBuffer, which BodyInit's typing
57378
+ // rejects; the copy is a plain Uint8Array over its own buffer.
57379
+ body: new Uint8Array(body),
57380
+ signal: AbortSignal.timeout(REPLAY_REQUEST_TIMEOUT_MS)
57381
+ });
57382
+ await res.arrayBuffer().catch(() => void 0);
57383
+ if (res.ok)
57384
+ return "ok";
57385
+ return isPermanentStatus(res.status) ? "permanent" : "transient";
57386
+ } catch {
57387
+ return "transient";
57388
+ }
57091
57389
  }
57092
- dispose() {
57093
- this.disposed = true;
57094
- for (const token of this.pending.keys())
57095
- this.forget(token);
57390
+ /** Stop the timer and wait for in-flight writes; a running replay stops at its next file. */
57391
+ async close() {
57392
+ this.closed = true;
57393
+ if (this.timer)
57394
+ clearInterval(this.timer);
57395
+ this.timer = null;
57396
+ await this.writes;
57397
+ if (this.replaying)
57398
+ await this.replaying;
57096
57399
  }
57097
- };
57098
-
57099
- // ts/agent-core/dist/lane-ledger.js
57100
- var LedgerUnsupportedError = class extends Error {
57101
- };
57102
- function bindLaneSession(lane, agentSessionId) {
57103
- if (lane.sessionId && lane.sessionId !== agentSessionId) {
57104
- lane.sessionAmbiguous = true;
57105
- } else if (!lane.sessionAmbiguous) {
57106
- lane.sessionId = agentSessionId;
57400
+ signalDir(signal) {
57401
+ return path2.join(this.opts.dir, signal);
57107
57402
  }
57108
- }
57109
- function releaseLocalMessageClaims(claims, sourceIds) {
57110
- const released = sourceIds.filter((sourceId) => claims.delete(sourceId));
57111
- return () => {
57112
- for (const sourceId of released)
57113
- claims.add(sourceId);
57114
- };
57115
- }
57116
- function isStaleLane(err) {
57117
- return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
57118
- }
57119
- function isEndpointMissing2(err) {
57120
- return err instanceof ApiError && err.status === 404 && !err.code;
57121
- }
57122
- var LaneLedger = class {
57123
- opts;
57124
- lanes = /* @__PURE__ */ new Map();
57125
- confirmations;
57126
- inputs;
57127
- claimResponses = /* @__PURE__ */ new Map();
57128
- claims = /* @__PURE__ */ new Map();
57129
- constructor(opts) {
57130
- this.opts = opts;
57131
- this.confirmations = new LaneConfirmations({
57132
- delaysMs: opts.terminalRetryDelaysMs,
57133
- log: opts.log,
57134
- onRecovered: opts.onRecovered,
57135
- onStale: (token) => {
57136
- for (const lane of this.lanes.values()) {
57137
- if (lane.lane === token)
57138
- this.forgetLane(lane);
57403
+ /** Read the directory once; afterwards the index is maintained in memory. */
57404
+ async load(signal) {
57405
+ const existing = this.index.get(signal);
57406
+ if (existing)
57407
+ return existing;
57408
+ const idx = { files: [], total: 0 };
57409
+ this.index.set(signal, idx);
57410
+ const dir = this.signalDir(signal);
57411
+ let names;
57412
+ try {
57413
+ names = await fsp.readdir(dir);
57414
+ } catch {
57415
+ return idx;
57416
+ }
57417
+ const now = this.now();
57418
+ for (const name of names.sort()) {
57419
+ const full = path2.join(dir, name);
57420
+ const m = FILE_RE.exec(name);
57421
+ if (!m) {
57422
+ if (name.endsWith(".tmp")) {
57423
+ const stat3 = await fsp.stat(full).catch(() => null);
57424
+ if (stat3 && now - stat3.mtimeMs > STALE_TMP_MS)
57425
+ await fsp.unlink(full).catch(() => {
57426
+ });
57139
57427
  }
57428
+ continue;
57140
57429
  }
57141
- });
57142
- this.inputs = new LaneInputReceipts(opts, this.confirmations);
57143
- }
57144
- get contextDir() {
57145
- return this.opts.contextDir;
57146
- }
57147
- /** Message-lane events (chat, channel conversation — lane-target.ts) ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
57148
- handles(event) {
57149
- return laneTargetUri(event) !== void 0;
57150
- }
57151
- laneKeyFor(event) {
57152
- const targetUri = laneTargetUri(event);
57153
- if (!targetUri && event.type !== "message" && event.dispatchEventId) {
57154
- return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
57430
+ const stat2 = await fsp.stat(full).catch(() => null);
57431
+ if (!stat2)
57432
+ continue;
57433
+ idx.files.push({ name, bytes: stat2.size, ts: Number(m[1]) });
57434
+ idx.total += stat2.size;
57155
57435
  }
57156
- return laneKeyForTarget(targetUri ?? `prll://${event.targetId}`, event.threadRootId);
57157
- }
57158
- getForEvent(event) {
57159
- return this.lanes.get(this.laneKeyFor(event));
57160
- }
57161
- laneContextPath(lane) {
57162
- return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
57436
+ return idx;
57163
57437
  }
57164
- /**
57165
- * Whether the server already rendered this message into a frame the model
57166
- * saw on its live lane. The row is folded there and resolves with that
57167
- * lane's turn — a local copy has nothing left to deliver.
57168
- */
57169
- seenInFrame(targetId, threadRootId, messageId) {
57170
- const lane = this.lanes.get(laneKeyForTarget(`prll://${targetId}`, threadRootId));
57171
- return lane?.seen.has(messageId) ?? false;
57172
- }
57173
- /**
57174
- * Hand the pending frame to the caller (once) with the members it covers
57175
- * and what the claim said about the wake, and record those members as
57176
- * seen. Absent frame ⇒ nothing new to render (every member already seen).
57177
- */
57178
- takeFrame(lane) {
57179
- const frame = lane.frame;
57180
- const ids = lane.framed;
57181
- for (const id of ids)
57182
- lane.seen.add(id);
57183
- lane.frame = void 0;
57184
- lane.framed = [];
57185
- const { input, noReply, attachments } = lane;
57186
- lane.input = void 0;
57187
- lane.noReply = void 0;
57188
- lane.attachments = void 0;
57189
- return { frame, ids, input, noReply, attachments };
57190
- }
57191
- /** Record what the claim response said about the wake alongside its frame. */
57192
- recordWake(lane, res) {
57193
- if (res.input)
57194
- lane.input = res.input;
57195
- if (res.no_reply != null)
57196
- lane.noReply = res.no_reply;
57197
- if (res.attachments?.length) {
57198
- lane.attachments = res.attachments.map((a) => ({
57199
- id: a.id,
57200
- fileName: a.file_name ?? "",
57201
- fileSize: a.file_size ?? 0,
57202
- mimeType: a.mime_type ?? ""
57203
- }));
57438
+ async evictExpired(signal, idx, now) {
57439
+ let evicted = 0;
57440
+ for (const file of [...idx.files]) {
57441
+ if (now - file.ts <= this.maxAgeMs)
57442
+ break;
57443
+ if (await this.remove(signal, idx, file))
57444
+ evicted += 1;
57204
57445
  }
57205
- }
57206
- /** The injection landed: the model has seen these members. */
57207
- markSeen(event, ids) {
57208
- const lane = this.lanes.get(this.laneKeyFor(event));
57209
- if (!lane)
57210
- return;
57211
- for (const id of ids)
57212
- lane.seen.add(id);
57446
+ if (evicted > 0)
57447
+ this.recordDrop(signal, "evicted_age", evicted);
57213
57448
  }
57214
57449
  /**
57215
- * The injection did not land (turn already over, process gone): keep the
57216
- * server's increment as the lane's pending frame so the buffered copy's
57217
- * drain renders it as its own turn instead of skipping it as seen.
57450
+ * Unlink and drop from the index. False when the file stays on disk: the
57451
+ * entry is kept so it still counts against the budget (bounds hold even
57452
+ * when deletion is refused), and the caller decides whether to skip it.
57218
57453
  */
57219
- deferFrame(event, frame, ids) {
57220
- const lane = this.lanes.get(this.laneKeyFor(event));
57221
- if (!lane)
57222
- return;
57223
- this.recordFrame(lane, frame, ids);
57454
+ async remove(signal, idx, file, alreadyGone = false) {
57455
+ if (!alreadyGone) {
57456
+ try {
57457
+ await fsp.unlink(path2.join(this.signalDir(signal), file.name));
57458
+ } catch (err) {
57459
+ if (err.code !== "ENOENT") {
57460
+ this.log(`spool could not delete ${signal}/${file.name}: ${String(err)}`);
57461
+ return false;
57462
+ }
57463
+ }
57464
+ }
57465
+ const at = idx.files.indexOf(file);
57466
+ if (at >= 0) {
57467
+ idx.files.splice(at, 1);
57468
+ idx.total -= file.bytes;
57469
+ }
57470
+ return true;
57224
57471
  }
57225
- recordFrame(lane, frame, ids) {
57226
- if (!frame)
57227
- return;
57228
- lane.frame = lane.frame ? `${lane.frame}
57472
+ };
57229
57473
 
57230
- ${frame}` : frame;
57231
- lane.framed.push(...ids);
57232
- }
57233
- /**
57234
- * Claim (or reuse) the lane for a group of same-lane message events and
57235
- * fold every group member into it. Returns 'foreign' when a healthy
57236
- * incumbent (another pod) holds the resource — the caller must not
57237
- * dispatch; the events stay pending server-side and re-drive after the
57238
- * incumbent completes.
57239
- */
57240
- async ensureLane(events) {
57241
- const key = this.laneKeyFor(events[events.length - 1]);
57242
- const prior = this.claims.get(key);
57243
- const claim = (prior ? prior.catch(() => null) : Promise.resolve()).then(() => this.ensureLaneAttempt(events, false));
57244
- this.claims.set(key, claim);
57245
- try {
57246
- return await claim;
57247
- } finally {
57248
- if (this.claims.get(key) === claim)
57249
- this.claims.delete(key);
57474
+ // ts/agent-core/dist/otlp-spool-exporter.js
57475
+ var import_core = __toESM(require_src2(), 1);
57476
+ var SpoolingExporter = class {
57477
+ delegate;
57478
+ serializer;
57479
+ signal;
57480
+ store;
57481
+ pending = /* @__PURE__ */ new Set();
57482
+ failing = false;
57483
+ everSucceeded = false;
57484
+ selectAggregationTemporality;
57485
+ selectAggregation;
57486
+ constructor(delegate, serializer, signal, store) {
57487
+ this.delegate = delegate;
57488
+ this.serializer = serializer;
57489
+ this.signal = signal;
57490
+ this.store = store;
57491
+ if (delegate.selectAggregationTemporality) {
57492
+ this.selectAggregationTemporality = delegate.selectAggregationTemporality.bind(delegate);
57493
+ }
57494
+ if (delegate.selectAggregation) {
57495
+ this.selectAggregation = delegate.selectAggregation.bind(delegate);
57250
57496
  }
57251
57497
  }
57252
- /**
57253
- * One ensureLane pass. `reclaimed` marks the arbitration retry: STALE_LANE
57254
- * on a REUSED cached lane means our cache outlived the server lease (a
57255
- * missed complete), not that a healthy incumbent holds the resource — claim
57256
- * is the only ownership arbiter, so ask it once instead of leaving the
57257
- * members to wait out the renotify pacing. STALE_LANE right after a fresh
57258
- * claim is a real takeover race and stays foreign. The server's incumbency
57259
- * check is the only staleness authority — deciding expiry locally from the
57260
- * bridge wall clock against the server-issued lease_until would let a
57261
- * clock-skewed host destructively discard a still-current lane's fold/seen
57262
- * state, so no local pre-check exists on purpose.
57263
- */
57264
- async ensureLaneAttempt(events, reclaimed) {
57265
- const trigger = events[events.length - 1];
57266
- const laneKey = this.laneKeyFor(trigger);
57267
- let lane = this.lanes.get(laneKey);
57268
- if (lane?.settling)
57269
- return null;
57270
- const reused = lane != null;
57271
- if (!lane) {
57272
- const targetUri = laneTargetUri(trigger) ?? `prll://${trigger.targetId}`;
57273
- const res = await this.claimRecoverably(laneKey, {
57274
- target_uri: targetUri,
57275
- thread_root_id: trigger.threadRootId,
57276
- limit: 100,
57277
- coverage_mode: this.opts.coverageMode ?? "implicit",
57278
- settlement_mode: this.opts.instanceId ? this.opts.settlementMode : void 0,
57279
- resume_received: this.opts.instanceId ? true : void 0,
57280
- instance_id: this.opts.instanceId
57281
- });
57282
- if (!res)
57283
- return null;
57284
- if (!res.claimed || !res.lane) {
57285
- if (res.reason === "empty") {
57286
- this.opts.log?.warn(`claim for ${targetUri} came back empty \u2014 nothing foldable; leaving to the reconciler`);
57287
- } else {
57288
- this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
57289
- }
57290
- return null;
57291
- }
57292
- const requestedCoverage = this.opts.coverageMode ?? "implicit";
57293
- const actualCoverage = res.coverage_mode ?? "implicit";
57294
- if (requestedCoverage === "explicit" && actualCoverage !== "explicit") {
57295
- await this.opts.client.releaseDispatchLane(this.opts.orgId, res.lane).catch(() => {
57296
- });
57297
- throw new Error(`server did not negotiate explicit input coverage for ${targetUri}; lane released`);
57498
+ export(items, resultCallback) {
57499
+ this.delegate.export(items, (result) => {
57500
+ if (result.code === import_core.ExportResultCode.SUCCESS) {
57501
+ if (this.failing || !this.everSucceeded)
57502
+ this.store.notifyOnline();
57503
+ this.failing = false;
57504
+ this.everSucceeded = true;
57505
+ resultCallback(result);
57506
+ return;
57298
57507
  }
57299
- const leaseUntilMs = Date.parse(res.lease_until ?? "");
57300
- lane = {
57301
- laneKey,
57302
- lane: res.lane,
57303
- targetUri,
57304
- threadRootId: trigger.threadRootId,
57305
- coverageMode: actualCoverage,
57306
- settlementMode: res.settlement_mode ?? "legacy",
57307
- folded: /* @__PURE__ */ new Map(),
57308
- framed: [],
57309
- seen: /* @__PURE__ */ new Set(),
57310
- ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
57311
- };
57312
- for (const ev of res.events ?? []) {
57313
- lane.folded.set(ev.source_id, ev.id);
57508
+ const cls = classifyExportError(result.error);
57509
+ if (cls === "permanent")
57510
+ this.store.recordDrop(this.signal, "permanent_status");
57511
+ if (cls !== "transient") {
57512
+ resultCallback(result);
57513
+ return;
57314
57514
  }
57315
- this.recordFrame(lane, res.frame, (res.events ?? []).map((ev) => ev.source_id));
57316
- this.recordWake(lane, res);
57317
- this.lanes.set(laneKey, lane);
57318
- }
57319
- for (const ev of events) {
57320
- if (lane.folded.has(ev.messageId))
57321
- continue;
57515
+ this.failing = true;
57516
+ let bytes;
57322
57517
  try {
57323
- const res = await this.opts.client.steerDispatch(this.opts.orgId, {
57324
- lane: lane.lane,
57325
- target_uri: lane.targetUri,
57326
- thread_root_id: lane.threadRootId,
57327
- ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: ev.ackSourceType ?? "message", source_id: ev.messageId }
57328
- });
57329
- lane.folded.set(ev.messageId, res.dispatch_event_id);
57330
- this.recordFrame(lane, res.frame, [ev.messageId]);
57331
- } catch (err) {
57332
- if (isStaleLane(err)) {
57333
- this.lanes.delete(laneKey);
57334
- this.removeLaneContext(lane);
57335
- if (reused && !reclaimed) {
57336
- this.opts.log?.info(`cached lane for ${lane.targetUri} is stale \u2014 re-claiming to arbitrate ownership`);
57337
- return this.ensureLaneAttempt(events, true);
57338
- }
57339
- return null;
57340
- }
57341
- this.opts.log?.warn(`steer fold failed for ${ev.messageId}; preserving prior members: ${String(err)}`);
57342
- continue;
57518
+ bytes = this.serializer.serializeRequest(items);
57519
+ } catch {
57520
+ bytes = void 0;
57343
57521
  }
57344
- }
57345
- return lane;
57522
+ if (!bytes || bytes.length === 0) {
57523
+ resultCallback(result);
57524
+ return;
57525
+ }
57526
+ const write = this.store.enqueue(this.signal, bytes).then((outcome) => {
57527
+ const handled = outcome === "queued" || outcome === "throttled";
57528
+ resultCallback(handled ? { code: import_core.ExportResultCode.SUCCESS } : result);
57529
+ }).finally(() => {
57530
+ this.pending.delete(write);
57531
+ });
57532
+ this.pending.add(write);
57533
+ });
57346
57534
  }
57347
- /**
57348
- * Fold a live mid-turn message into its active lane BEFORE injecting it
57349
- * into the running turn. Injection without a successful fold is forbidden —
57350
- * an un-folded injected message would be re-driven after complete and the
57351
- * model would handle it twice.
57352
- */
57353
- async steerLive(event) {
57354
- const laneKey = this.laneKeyFor(event);
57355
- const lane = this.lanes.get(laneKey);
57356
- if (!lane || lane.settling)
57357
- return null;
57358
- if (lane.seen.has(event.messageId))
57359
- return null;
57360
- if (lane.folded.has(event.messageId)) {
57361
- return {
57362
- inputLifecycle: this.inputLifecycleFor(lane, [event.messageId]),
57363
- covered: [event.messageId]
57364
- };
57365
- }
57366
- try {
57367
- const res = await this.opts.client.steerDispatch(this.opts.orgId, {
57368
- lane: lane.lane,
57369
- target_uri: lane.targetUri,
57370
- thread_root_id: lane.threadRootId,
57371
- ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: event.ackSourceType ?? "message", source_id: event.messageId }
57372
- });
57373
- lane.folded.set(event.messageId, res.dispatch_event_id);
57374
- const covered = [event.messageId];
57375
- return {
57376
- inputLifecycle: this.inputLifecycleFor(lane, covered),
57377
- frame: res.frame,
57378
- covered
57379
- };
57380
- } catch (err) {
57381
- if (isStaleLane(err)) {
57382
- this.lanes.delete(laneKey);
57383
- this.removeLaneContext(lane);
57384
- } else {
57385
- this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
57386
- }
57387
- return null;
57388
- }
57389
- }
57390
- /**
57391
- * Build the exact runtime-input lifecycle for one prompt/injection. A
57392
- * batched prompt covers every WorkItem represented in that single frame.
57393
- */
57394
- inputLifecycle(lane, events) {
57395
- return this.inputLifecycleFor(lane, events.map((event) => event.messageId));
57535
+ /** The delegate's flush, then every spool write it caused — the barrier shutdown relies on. */
57536
+ async forceFlush() {
57537
+ await this.delegate.forceFlush?.();
57538
+ await Promise.all([...this.pending]);
57396
57539
  }
57397
- /**
57398
- * Exact lifecycle over a set of folded members by message id — the set a
57399
- * prompt or injection actually delivers (frame coverage ∪ buffered group).
57400
- */
57401
- inputLifecycleFor(lane, messageIds) {
57402
- return this.inputs.lifecycle(lane, messageIds);
57540
+ async shutdown() {
57541
+ await this.forceFlush();
57542
+ await this.delegate.shutdown();
57403
57543
  }
57404
- /** Carry the runtime error into the lane's forced completion. */
57405
- markTurnError(laneKey, info = {}) {
57406
- const lane = this.lanes.get(laneKey);
57407
- if (lane)
57408
- lane.turnError = info;
57544
+ };
57545
+
57546
+ // ts/agent-core/dist/telemetry.js
57547
+ var initialized = false;
57548
+ var shutdownFn = null;
57549
+ var tracer = () => trace.getTracer("parall.agent");
57550
+ var dispatchSpans = /* @__PURE__ */ new WeakSet();
57551
+ var recordedErrors = /* @__PURE__ */ new WeakSet();
57552
+ var dispatchCounter = null;
57553
+ var dispatchDuration = null;
57554
+ var missingReplyCounter = null;
57555
+ var turnTokensCounter = null;
57556
+ var turnCostCounter = null;
57557
+ var otelLogger = null;
57558
+ var spoolCounters = null;
57559
+ function recordSpoolEvent(event) {
57560
+ if (!spoolCounters)
57561
+ return;
57562
+ if (event.kind === "queued")
57563
+ spoolCounters.queued.add(1, { signal: event.signal });
57564
+ else if (event.kind === "replayed")
57565
+ spoolCounters.replayed.add(1, { signal: event.signal });
57566
+ else
57567
+ spoolCounters.dropped.add(event.count, { signal: event.signal, reason: event.reason });
57568
+ }
57569
+ function resolveTargetType(targetId) {
57570
+ if (targetId.startsWith("cht_"))
57571
+ return "chat";
57572
+ if (targetId.startsWith("tsk_"))
57573
+ return "task";
57574
+ if (targetId.startsWith("sch_"))
57575
+ return "schedule";
57576
+ return "unknown";
57577
+ }
57578
+ var PRODUCTION_API_HOSTS = /* @__PURE__ */ new Set(["api.parall.com"]);
57579
+ var STAGING_API_HOSTS = /* @__PURE__ */ new Set(["api.staging.prll.sh"]);
57580
+ function resolveTelemetryEnvironment(apiUrl, override = process.env.PRLL_SERVER_ENV) {
57581
+ const forced = override?.trim();
57582
+ if (forced)
57583
+ return forced;
57584
+ let host = "";
57585
+ try {
57586
+ host = apiUrl ? new URL(apiUrl).hostname.toLowerCase() : "";
57587
+ } catch {
57588
+ host = "";
57409
57589
  }
57410
- /**
57411
- * Record that the turn on this lane ended on a self-healing usage limit.
57412
- * Like markTurnError this is transport state for the lane's final
57413
- * complete; an error bit set on the same lane outranks it.
57414
- */
57415
- markTurnDeferred(laneKey, info) {
57416
- const lane = this.lanes.get(laneKey);
57417
- if (lane)
57418
- lane.turnDeferred = info;
57590
+ if (PRODUCTION_API_HOSTS.has(host))
57591
+ return "production";
57592
+ if (STAGING_API_HOSTS.has(host))
57593
+ return "staging";
57594
+ return "development";
57595
+ }
57596
+ function resolveServiceVersion(importMetaUrl) {
57597
+ const fallback = process.env.npm_package_version || "unknown";
57598
+ let dir;
57599
+ try {
57600
+ dir = path3.dirname(fileURLToPath2(importMetaUrl));
57601
+ } catch {
57602
+ return fallback;
57419
57603
  }
57420
- /**
57421
- * Sticky: the server rejected turn_outcome=deferred (predates it). Deferred
57422
- * completes fall back to the error form for the rest of the process — the
57423
- * members still release for retry, just on the redrive budget instead of
57424
- * the reset-time schedule.
57425
- */
57426
- deferredUnsupported = false;
57427
- async completeIfIdle(laneKey, hasMoreLocal) {
57428
- const lane = this.lanes.get(laneKey);
57429
- if (!lane || hasMoreLocal)
57430
- return;
57431
- if (lane.settling)
57432
- return;
57433
- lane.settling = true;
57434
- const deferred = !lane.turnError && !this.deferredUnsupported ? lane.turnDeferred : void 0;
57435
- const outcome = lane.turnError ? "error" : lane.turnDeferred ? this.deferredUnsupported ? "error" : "deferred" : "ok";
57436
- const request3 = {
57437
- lane: lane.lane,
57438
- target_uri: lane.targetUri,
57439
- thread_root_id: lane.threadRootId,
57440
- // An error turn releases its members for retry; a deferred turn
57441
- // re-delivers them at retry_at without burning redrive budget
57442
- // (ignored by older servers, which 400 on the unknown enum — see the
57443
- // fallback below).
57444
- turn_outcome: outcome,
57445
- ...deferred ? {
57446
- outcome_class: deferred.outcomeClass,
57447
- ...deferred.retryAt ? { retry_at: deferred.retryAt } : {}
57448
- } : {},
57449
- // An error complete carries the bridge's classification and redacted
57450
- // evidence so the server can persist WHY on the released row
57451
- // (agent-health-alerting-design.md §4.5). usage_limit never travels
57452
- // with error: it is the deferred contract, and a server that rejected
57453
- // deferred (deferredUnsupported) also predates the class field.
57454
- ...outcome === "error" && lane.turnError ? {
57455
- ...errorWireClass(lane.turnError.outcomeClass) ? { outcome_class: errorWireClass(lane.turnError.outcomeClass) } : {},
57456
- ...lane.turnError.detail ? { detail: lane.turnError.detail.slice(0, 500) } : {}
57457
- } : {},
57458
- session_id: lane.sessionAmbiguous ? void 0 : lane.sessionId
57459
- };
57460
- let fallback = false;
57461
- await this.confirmations.submit(lane.lane, {
57462
- label: "complete",
57463
- send: async () => {
57464
- try {
57465
- await this.opts.client.completeDispatch(this.opts.orgId, fallback ? {
57466
- lane: request3.lane,
57467
- target_uri: request3.target_uri,
57468
- thread_root_id: request3.thread_root_id,
57469
- turn_outcome: "error"
57470
- } : request3);
57471
- } catch (err) {
57472
- if (!fallback && outcome === "deferred" && err instanceof ApiError && err.status === 400) {
57473
- this.deferredUnsupported = true;
57474
- fallback = true;
57475
- await this.opts.client.completeDispatch(this.opts.orgId, {
57476
- lane: request3.lane,
57477
- target_uri: request3.target_uri,
57478
- thread_root_id: request3.thread_root_id,
57479
- turn_outcome: "error"
57480
- });
57481
- } else
57482
- throw err;
57483
- }
57484
- this.forgetLane(lane);
57604
+ for (const candidate of [path3.join(dir, "manifest.json"), path3.join(dir, "..", "package.json")]) {
57605
+ try {
57606
+ const parsed = JSON.parse(readFileSync2(candidate, "utf-8"));
57607
+ if (typeof parsed.version === "string" && parsed.version.trim()) {
57608
+ return parsed.version.trim();
57485
57609
  }
57486
- });
57487
- }
57488
- /**
57489
- * Renew one lane by its key — the external runtime-activity hook for
57490
- * adapters whose tool traffic bypasses the RuntimeEvent stream (openclaw
57491
- * hooks). Scoped to the session's own lane: renewing every lane would let
57492
- * one busy fork keep an unrelated stalled fork's lane leased forever.
57493
- */
57494
- renewByKey(laneKey) {
57495
- const lane = this.lanes.get(laneKey);
57496
- if (lane)
57497
- this.maybeRenew(lane);
57610
+ } catch {
57611
+ }
57498
57612
  }
57499
- /**
57500
- * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
57501
- * so a chatty turn doesn't spam the server. Without this, a legitimately
57502
- * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
57503
- * write misfired with STALE_LANE — the design doc's "long turns renew via
57504
- * step writes". Fire-and-forget: a failed renewal is surfaced by the next
57505
- * write's incumbency check anyway.
57506
- */
57507
- maybeRenew(lane) {
57508
- if (isTurnToken(lane.lane))
57509
- return;
57510
- const now = Date.now();
57511
- const ttl = lane.leaseTtlMs ?? 10 * 6e4;
57512
- const until = lane.leaseUntilMs ?? now;
57513
- if (until - now > ttl / 2)
57613
+ return fallback;
57614
+ }
57615
+ var DIAG_THROTTLE_MS = 6e4;
57616
+ var DIAG_THROTTLE_KEYS = 200;
57617
+ function createThrottledDiagLogger(now = Date.now) {
57618
+ const lastAt = /* @__PURE__ */ new Map();
57619
+ const describe = (a) => {
57620
+ if (a instanceof Error)
57621
+ return a.message;
57622
+ if (a && typeof a === "object" && typeof a.message === "string") {
57623
+ return a.message;
57624
+ }
57625
+ if (typeof a === "string" && a.startsWith("{")) {
57626
+ try {
57627
+ const parsed = JSON.parse(a);
57628
+ if (typeof parsed.message === "string")
57629
+ return parsed.message;
57630
+ } catch {
57631
+ }
57632
+ }
57633
+ return String(a);
57634
+ };
57635
+ const emit = (level, args) => {
57636
+ const msg = args.map(describe).join(" ");
57637
+ const key = `${level}:${msg.slice(0, 160)}`;
57638
+ const at = now();
57639
+ const prev = lastAt.get(key);
57640
+ if (prev !== void 0 && at - prev < DIAG_THROTTLE_MS)
57514
57641
  return;
57515
- lane.leaseUntilMs = now + ttl;
57516
- void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
57517
- lane: lane.lane,
57518
- target_uri: lane.targetUri,
57519
- thread_root_id: lane.threadRootId
57520
- }).then((res) => {
57521
- const until2 = Date.parse(res?.lease_until ?? "");
57522
- if (!Number.isNaN(until2))
57523
- lane.leaseUntilMs = until2;
57524
- }).catch((err) => {
57525
- if (isStaleLane(err)) {
57526
- this.lanes.delete(lane.laneKey);
57527
- this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
57528
- return;
57529
- }
57530
- this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
57531
- });
57642
+ if (lastAt.size >= DIAG_THROTTLE_KEYS)
57643
+ lastAt.clear();
57644
+ lastAt.set(key, at);
57645
+ console.warn(`${new Date(at).toISOString()} [telemetry] otel ${level}: ${msg}`);
57646
+ };
57647
+ return {
57648
+ verbose: () => {
57649
+ },
57650
+ debug: () => {
57651
+ },
57652
+ info: () => {
57653
+ },
57654
+ warn: (...args) => emit("warn", args),
57655
+ error: (...args) => emit("error", args)
57656
+ };
57657
+ }
57658
+ async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
57659
+ const noopHandle = { shutdown: async () => {
57660
+ } };
57661
+ const apiUrl = opts.apiUrl ?? process.env.PRLL_API_URL;
57662
+ const apiKey = opts.apiKey ?? process.env.PRLL_API_KEY;
57663
+ if (!apiUrl || !apiKey) {
57664
+ console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] disabled: no API url/key resolved for ${serviceName} \u2014 nothing will reach SigNoz`);
57665
+ return noopHandle;
57532
57666
  }
57533
- /**
57534
- * Release a lane's unresolved members back to pending (dispatch error /
57535
- * shutdown) so the next pod re-claims immediately instead of waiting out
57536
- * the lease.
57537
- */
57538
- async release(laneKey, reason = "unspecified", info) {
57539
- const lane = this.lanes.get(laneKey);
57540
- if (!lane || lane.settling)
57541
- return;
57542
- lane.settling = true;
57543
- const wireClass = errorWireClass(info?.outcomeClass);
57544
- const outcome = info && (wireClass || info.detail) ? {
57545
- ...wireClass ? { outcome_class: wireClass } : {},
57546
- ...info.detail ? { detail: redactSecrets(info.detail, this.opts.knownSecrets).slice(0, 500) } : {}
57547
- } : void 0;
57548
- await this.confirmations.submit(lane.lane, {
57549
- label: "release",
57550
- send: async () => {
57551
- await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane, reason, outcome);
57552
- this.forgetLane(lane);
57667
+ const environment = opts.environment ?? resolveTelemetryEnvironment(apiUrl);
57668
+ const serviceVersion = opts.serviceVersion ?? process.env.npm_package_version ?? "unknown";
57669
+ try {
57670
+ const otelEndpoint = apiUrl.replace(/\/$/, "") + "/otel";
57671
+ if (!initialized)
57672
+ diag2.setLogger(createThrottledDiagLogger(), DiagLogLevel.WARN);
57673
+ const { OTLPTraceExporter } = await Promise.resolve().then(() => __toESM(require_src6(), 1));
57674
+ const { OTLPMetricExporter } = await Promise.resolve().then(() => __toESM(require_src8(), 1));
57675
+ const { OTLPLogExporter } = await Promise.resolve().then(() => __toESM(require_src9(), 1));
57676
+ const { NodeTracerProvider, BatchSpanProcessor } = await Promise.resolve().then(() => __toESM(require_src14(), 1));
57677
+ const { MeterProvider, PeriodicExportingMetricReader } = await Promise.resolve().then(() => __toESM(require_src4(), 1));
57678
+ const { LoggerProvider, BatchLogRecordProcessor } = await Promise.resolve().then(() => __toESM(require_src15(), 1));
57679
+ const { Resource } = await Promise.resolve().then(() => __toESM(require_src3(), 1));
57680
+ const resource = new Resource({
57681
+ "service.name": serviceName,
57682
+ "service.version": serviceVersion,
57683
+ "deployment.environment.name": environment,
57684
+ "parall.runtime_type": runtimeType,
57685
+ "parall.agent_id": process.env.PRLL_AGENT_ID || "",
57686
+ "parall.machine_id": process.env.PRLL_MACHINE_ID || "",
57687
+ "parall.org_id": process.env.PRLL_ORG_ID || "",
57688
+ "parall.daemon_mode": process.env.PRLL_DAEMON_MODE === "1"
57689
+ });
57690
+ const authHeaders = { Authorization: `Bearer ${apiKey}` };
57691
+ const spoolDir = (opts.spoolDir ?? process.env.PRLL_OTEL_SPOOL_DIR)?.trim() || void 0;
57692
+ const spool = spoolDir ? new OtlpSpoolStore({
57693
+ dir: spoolDir,
57694
+ endpoint: otelEndpoint,
57695
+ headers: authHeaders,
57696
+ onEvent: recordSpoolEvent
57697
+ }) : null;
57698
+ const serializers = spool ? await Promise.resolve().then(() => __toESM(require_src5(), 1)) : null;
57699
+ const spooled = (exporter, signal, serializer) => spool && serializer ? new SpoolingExporter(exporter, serializer, signal, spool) : exporter;
57700
+ const traceExporter = spooled(new OTLPTraceExporter({ url: `${otelEndpoint}/v1/traces`, headers: authHeaders }), "traces", serializers?.ProtobufTraceSerializer);
57701
+ const tracerProvider = new NodeTracerProvider({ resource });
57702
+ tracerProvider.addSpanProcessor(new BatchSpanProcessor(traceExporter));
57703
+ tracerProvider.register();
57704
+ const metricExporter = spooled(new OTLPMetricExporter({ url: `${otelEndpoint}/v1/metrics`, headers: authHeaders }), "metrics", serializers?.ProtobufMetricsSerializer);
57705
+ const metricReader = new PeriodicExportingMetricReader({
57706
+ exporter: metricExporter,
57707
+ exportIntervalMillis: 15e3
57708
+ });
57709
+ const meterProvider = new MeterProvider({ resource, readers: [metricReader] });
57710
+ metrics.setGlobalMeterProvider(meterProvider);
57711
+ const logExporter = spooled(new OTLPLogExporter({ url: `${otelEndpoint}/v1/logs`, headers: authHeaders }), "logs", serializers?.ProtobufLogsSerializer);
57712
+ const loggerProvider = new LoggerProvider({ resource });
57713
+ loggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(logExporter));
57714
+ const meter = metrics.getMeter("parall.agent");
57715
+ otelLogger = loggerProvider.getLogger("parall.agent");
57716
+ dispatchCounter = meter.createCounter("parall.dispatch.count", {
57717
+ description: "Number of dispatch cycles completed"
57718
+ });
57719
+ dispatchDuration = meter.createHistogram("parall.dispatch.duration", {
57720
+ description: "Dispatch cycle duration in milliseconds",
57721
+ unit: "ms"
57722
+ });
57723
+ missingReplyCounter = meter.createCounter("parall.dispatch.missing_reply", {
57724
+ description: "Dispatches where agent produced text but sent no reply message"
57725
+ });
57726
+ turnTokensCounter = meter.createCounter("parall.turn.tokens", {
57727
+ description: "LLM tokens consumed per turn, by kind (input/output/cache_read/cache_creation)"
57728
+ });
57729
+ turnCostCounter = meter.createCounter("parall.turn.cost_usd", {
57730
+ description: "LLM cost per turn in USD (when the runtime reports it)"
57731
+ });
57732
+ if (spool) {
57733
+ const spoolMeter = metrics.getMeter("parall.telemetry");
57734
+ spoolCounters = {
57735
+ queued: spoolMeter.createCounter("parall.telemetry.spool.queued", {
57736
+ description: "OTLP batches spooled to disk after a failed export"
57737
+ }),
57738
+ replayed: spoolMeter.createCounter("parall.telemetry.spool.replayed", {
57739
+ description: "Spooled OTLP batches delivered on replay"
57740
+ }),
57741
+ dropped: spoolMeter.createCounter("parall.telemetry.spool.dropped", {
57742
+ description: "OTLP batches dropped instead of spooled or replayed, by reason"
57743
+ })
57744
+ };
57745
+ }
57746
+ initialized = true;
57747
+ console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] exporting ${serviceName} v${serviceVersion} env=${environment} to ${otelEndpoint}${spoolDir ? ` spool=${spoolDir}` : ""}`);
57748
+ shutdownFn = async () => {
57749
+ try {
57750
+ await tracerProvider.forceFlush();
57751
+ await meterProvider.forceFlush();
57752
+ await loggerProvider.forceFlush();
57753
+ await tracerProvider.shutdown();
57754
+ await meterProvider.shutdown();
57755
+ await loggerProvider.shutdown();
57756
+ } finally {
57757
+ await spool?.close();
57758
+ }
57759
+ };
57760
+ return {
57761
+ shutdown: async () => {
57762
+ if (shutdownFn)
57763
+ await shutdownFn();
57553
57764
  }
57765
+ };
57766
+ } catch (err) {
57767
+ console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] init failed for ${serviceName}, running without export: ${String(err)}`);
57768
+ return noopHandle;
57769
+ }
57770
+ }
57771
+ function dispatchEventAttributes(event, runtimeType, sessionKey) {
57772
+ return {
57773
+ "dispatch.target_type": resolveTargetType(event.targetId),
57774
+ "dispatch.event_type": event.type,
57775
+ "dispatch.runtime_type": runtimeType,
57776
+ "dispatch.session_key": sessionKey,
57777
+ "dispatch.message_id": event.messageId,
57778
+ "dispatch.target_id": event.targetId,
57779
+ ...event.dispatchEventId ? { "dispatch.event_id": event.dispatchEventId } : {}
57780
+ };
57781
+ }
57782
+ function startDispatchSpan(event, runtimeType, sessionKey) {
57783
+ const span = tracer().startSpan("parall.dispatch", {
57784
+ root: true,
57785
+ attributes: dispatchEventAttributes(event, runtimeType, sessionKey)
57786
+ });
57787
+ dispatchSpans.add(span);
57788
+ return span;
57789
+ }
57790
+ function startTypedDispatchSpan(dispatchEventId, runtimeType) {
57791
+ const span = tracer().startSpan("parall.dispatch", {
57792
+ root: true,
57793
+ attributes: {
57794
+ "dispatch.runtime_type": runtimeType,
57795
+ ...dispatchEventId ? { "dispatch.event_id": dispatchEventId } : {}
57796
+ }
57797
+ });
57798
+ dispatchSpans.add(span);
57799
+ return span;
57800
+ }
57801
+ function annotateDispatchSpan(span, metricsSnapshot, error, turnOutcome) {
57802
+ if (!span)
57803
+ return;
57804
+ if (metricsSnapshot) {
57805
+ span.setAttributes({
57806
+ "dispatch.deliver_text_chunks": metricsSnapshot.deliver_text_chunks,
57807
+ "dispatch.deliver_text_chars": metricsSnapshot.deliver_text_chars,
57808
+ "dispatch.message_send_attempts": metricsSnapshot.message_send_attempts,
57809
+ "dispatch.message_send_successes": metricsSnapshot.message_send_successes,
57810
+ "dispatch.no_reply_called": metricsSnapshot.no_reply_called,
57811
+ "dispatch.tool_call_count": metricsSnapshot.tool_call_count,
57812
+ "dispatch.duration_ms": Date.now() - metricsSnapshot.started_at
57554
57813
  });
57555
57814
  }
57556
- async releaseAll(reason = "shutdown") {
57557
- await this.confirmations.retryNow();
57558
- const keys = [...this.lanes.keys()];
57559
- for (const key of keys) {
57560
- await this.release(key, reason);
57815
+ if (turnOutcome) {
57816
+ span.setAttribute("dispatch.outcome", turnOutcome.outcome);
57817
+ if (turnOutcome.detail)
57818
+ span.setAttribute("dispatch.outcome_detail", turnOutcome.detail);
57819
+ if (turnOutcome.retryAt)
57820
+ span.setAttribute("dispatch.retry_at", turnOutcome.retryAt);
57821
+ if (turnOutcome.model)
57822
+ span.setAttribute("dispatch.model", turnOutcome.model);
57823
+ if (turnOutcome.raw && Object.keys(turnOutcome.raw).length > 0) {
57824
+ try {
57825
+ span.setAttribute("dispatch.outcome_raw", JSON.stringify(turnOutcome.raw));
57826
+ } catch {
57827
+ }
57561
57828
  }
57562
- for (const [key, claim] of this.claimResponses) {
57563
- if (!claim.response?.lane)
57564
- continue;
57565
- const token = claim.response.lane;
57566
- await this.confirmations.submit(token, {
57567
- label: "unconsumed claim release",
57568
- send: async () => {
57569
- await this.opts.client.releaseDispatchLane(this.opts.orgId, token, reason);
57570
- this.claimResponses.delete(key);
57571
- }
57572
- });
57829
+ const u = turnOutcome.usage;
57830
+ if (u) {
57831
+ if (u.inputTokens !== void 0)
57832
+ span.setAttribute("dispatch.tokens_input", u.inputTokens);
57833
+ if (u.outputTokens !== void 0)
57834
+ span.setAttribute("dispatch.tokens_output", u.outputTokens);
57835
+ if (u.cacheReadTokens !== void 0)
57836
+ span.setAttribute("dispatch.tokens_cache_read", u.cacheReadTokens);
57837
+ if (u.cacheCreationTokens !== void 0)
57838
+ span.setAttribute("dispatch.tokens_cache_creation", u.cacheCreationTokens);
57839
+ if (u.costUsd !== void 0)
57840
+ span.setAttribute("dispatch.cost_usd", u.costUsd);
57841
+ if (u.durationApiMs !== void 0)
57842
+ span.setAttribute("dispatch.duration_api_ms", u.durationApiMs);
57573
57843
  }
57574
57844
  }
57575
- /** True when any lane is currently active (used by shutdown logging). */
57576
- get activeCount() {
57577
- return this.lanes.size;
57578
- }
57579
- /**
57580
- * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>)
57581
- * by WorkItem id. The server renders the wake frame on claim (or resolves
57582
- * the item as stale and answers `claimed: false, reason: "stale"`).
57583
- * Returns null when a healthy incumbent (another pod) holds it, the
57584
- * WorkItem is already resolved, or the server found nothing to wake for
57585
- * — the caller must skip processing.
57586
- */
57587
- async claimTyped(ref) {
57588
- const key = `typed:${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`}`;
57589
- if (this.claims.has(key))
57590
- return null;
57591
- if (ref.dispatchEventId && this.lanes.has(laneKeyForTarget(`dsp:${ref.dispatchEventId}`)))
57592
- return null;
57593
- const claim = this.claimTypedAttempt(ref);
57594
- this.claims.set(key, claim);
57595
- try {
57596
- return await claim;
57597
- } finally {
57598
- this.claims.delete(key);
57599
- }
57600
- }
57601
- async claimRecoverably(key, request3) {
57602
- let claim = this.claimResponses.get(key);
57603
- if (!claim) {
57604
- claim = { request: request3 };
57605
- this.claimResponses.set(key, claim);
57606
- const captured = claim;
57607
- await this.confirmations.submit(`claim:${key}`, {
57608
- label: "claim",
57609
- send: async () => {
57610
- try {
57611
- captured.response = await this.opts.client.claimDispatch(this.opts.orgId, request3);
57612
- } catch (err) {
57613
- if (isEndpointMissing2(err))
57614
- captured.unsupported = true;
57615
- else
57616
- throw err;
57617
- }
57618
- }
57619
- });
57620
- }
57621
- if (claim.unsupported) {
57622
- this.claimResponses.delete(key);
57623
- throw new LedgerUnsupportedError("claim endpoint unavailable");
57624
- }
57625
- if (!claim.response)
57626
- return null;
57627
- this.claimResponses.delete(key);
57628
- return claim.response;
57629
- }
57630
- async claimTypedAttempt(ref) {
57631
- const res = await this.claimRecoverably(`typed:${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`}`, {
57632
- dispatch_event_id: ref.dispatchEventId,
57633
- source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
57634
- source_id: ref.dispatchEventId ? void 0 : ref.sourceId,
57635
- instance_id: this.opts.instanceId
57636
- });
57637
- if (!res)
57638
- return null;
57639
- if (!res.claimed || !res.lane || !res.events?.length) {
57640
- if (res.reason === "stale") {
57641
- this.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} resolved by the server as stale (${res.stale_reason ?? "unspecified"})`);
57642
- } else if (res.claimed && res.lane) {
57643
- await this.opts.client.releaseDispatchLane(this.opts.orgId, res.lane).catch(() => {
57644
- });
57645
- }
57646
- return null;
57647
- }
57648
- const workItem = res.events[0];
57649
- const targetUri = `dsp:${workItem.id}`;
57650
- if (this.lanes.has(laneKeyForTarget(targetUri)))
57651
- return null;
57652
- const leaseUntilMs = Date.parse(res.lease_until ?? "");
57653
- const lane = {
57654
- laneKey: laneKeyForTarget(targetUri),
57655
- lane: res.lane,
57656
- targetUri,
57657
- coverageMode: "implicit",
57658
- folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
57659
- framed: [],
57660
- seen: /* @__PURE__ */ new Set(),
57661
- typedDispatchEventId: workItem.id,
57662
- ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
57663
- };
57664
- this.recordFrame(lane, res.frame, [workItem.source_id]);
57665
- this.recordWake(lane, res);
57666
- this.lanes.set(lane.laneKey, lane);
57667
- return lane;
57668
- }
57669
- /**
57670
- * Drop a lane's local record without any server call — for a typed lane
57671
- * whose member the by-id complete just resolved (the server dropped the
57672
- * vacated lane row in the same transaction). Calling completeIfIdle
57673
- * instead would fire a lane-form Complete at a lane that no longer exists
57674
- * and burn an RPC on the guaranteed STALE_LANE answer.
57675
- */
57676
- dropLocal(laneKey) {
57677
- const lane = this.lanes.get(laneKey);
57678
- if (!lane)
57679
- return;
57680
- this.confirmations.forget(lane.lane);
57681
- this.forgetLane(lane);
57682
- }
57683
- syncInputAttribution(lane) {
57684
- return this.inputs.syncAttribution(lane);
57685
- }
57686
- async confirmTyped(lane, send) {
57687
- if (lane.settling)
57688
- return;
57689
- lane.settling = true;
57690
- await this.confirmations.submit(lane.lane, {
57691
- label: "typed complete",
57692
- send: async () => {
57693
- await send();
57694
- this.forgetLane(lane);
57695
- }
57696
- });
57697
- }
57698
- retryConfirmations() {
57699
- return this.confirmations.retryNow();
57700
- }
57701
- dispose() {
57702
- this.confirmations.dispose();
57703
- }
57704
- forgetLane(lane) {
57705
- if (this.lanes.get(lane.laneKey) !== lane)
57845
+ if (error)
57846
+ recordDispatchError(span, error);
57847
+ }
57848
+ function recordDispatchError(span, error) {
57849
+ if (typeof error === "object" && error !== null) {
57850
+ if (recordedErrors.has(error))
57706
57851
  return;
57707
- this.lanes.delete(lane.laneKey);
57708
- this.removeLaneContext(lane);
57709
- }
57710
- /**
57711
- * Remove the per-lane context file (and its CLI sidecar) when the lane
57712
- * ends. A leftover file would make a later cross-context send to the same
57713
- * target bind a dead lane token and misfire with STALE_LANE instead of
57714
- * taking the plain non-ledger path.
57715
- */
57716
- removeLaneContext(lane) {
57717
- const contextPath = this.laneContextPath(lane);
57718
- for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
57719
- try {
57720
- fs2.rmSync(p, { force: true });
57721
- } catch {
57722
- }
57723
- }
57852
+ recordedErrors.add(error);
57724
57853
  }
57725
- };
57726
-
57727
- // ts/agent-core/dist/telemetry.js
57728
- init_esm();
57729
- var import_api_logs = __toESM(require_src(), 1);
57730
- import { AsyncLocalStorage } from "node:async_hooks";
57731
- import { readFileSync as readFileSync2 } from "node:fs";
57732
- import * as path4 from "node:path";
57733
- import { fileURLToPath as fileURLToPath2 } from "node:url";
57734
-
57735
- // ts/agent-core/dist/otlp-spool.js
57736
- import * as fs3 from "node:fs";
57737
- import * as fsp from "node:fs/promises";
57738
- import * as path3 from "node:path";
57739
- var SPOOL_SIGNALS = ["traces", "metrics", "logs"];
57740
- var DEFAULT_MAX_BYTES = {
57741
- traces: 6 << 20,
57742
- logs: 8 << 20,
57743
- metrics: 2 << 20
57744
- };
57745
- var DEFAULT_MIN_INTERVAL_MS = { metrics: 6e4 };
57746
- var DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
57747
- var DEFAULT_REPLAY_INTERVAL_MS = 6e4;
57748
- var DEFAULT_REPLAY_BUDGET = { files: 200, wallMs: 2e4 };
57749
- var REPLAY_REQUEST_TIMEOUT_MS = 1e4;
57750
- var STALE_TMP_MS = 6e4;
57751
- var FILE_RE = /^(\d{13})-(\d+)-(\d{6})\.pb$/;
57752
- var PERMANENT_STATUSES = /* @__PURE__ */ new Set([400, 401, 403, 404, 413, 415]);
57753
- function isPermanentStatus(status) {
57754
- return PERMANENT_STATUSES.has(status);
57854
+ const safe = redactSecrets(String(error));
57855
+ span.setStatus({ code: SpanStatusCode.ERROR, message: safe });
57856
+ span.recordException(new Error(safe));
57755
57857
  }
57756
- function classifyExportError(err) {
57757
- if (!err || typeof err !== "object")
57758
- return "transient";
57759
- const e = err;
57760
- if (e.name === "OTLPExporterError" && typeof e.code === "number") {
57761
- return isPermanentStatus(e.code) ? "permanent" : "transient";
57762
- }
57763
- if (e.message === "Nothing to send")
57764
- return "empty";
57765
- return "transient";
57858
+ function recordDispatchMetric(event, runtimeType, durationMs, outcome = "ok") {
57859
+ if (!initialized)
57860
+ return;
57861
+ const attrs = {
57862
+ target_type: resolveTargetType(event.targetId),
57863
+ event_type: event.type,
57864
+ runtime_type: runtimeType,
57865
+ outcome
57866
+ };
57867
+ dispatchCounter?.add(1, attrs);
57868
+ dispatchDuration?.record(durationMs, attrs);
57766
57869
  }
57767
- var OtlpSpoolStore = class {
57768
- opts;
57769
- index = /* @__PURE__ */ new Map();
57770
- maxBytes;
57771
- minIntervalMs;
57772
- maxAgeMs;
57773
- budget;
57774
- fetchImpl;
57775
- now;
57776
- log;
57777
- /** Files whose replay POST succeeded but whose unlink failed — never resent by this process. */
57778
- sent = /* @__PURE__ */ new Set();
57779
- seq = 0;
57780
- writes = Promise.resolve();
57781
- replaying = null;
57782
- replayWanted = false;
57783
- timer = null;
57784
- closed = false;
57785
- constructor(opts) {
57786
- this.opts = opts;
57787
- this.maxBytes = { ...DEFAULT_MAX_BYTES, ...opts.maxBytes };
57788
- this.minIntervalMs = { ...DEFAULT_MIN_INTERVAL_MS, ...opts.minIntervalMs };
57789
- this.maxAgeMs = opts.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
57790
- this.budget = opts.replayBudget ?? DEFAULT_REPLAY_BUDGET;
57791
- this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
57792
- this.now = opts.now ?? Date.now;
57793
- this.log = opts.log ?? ((msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] ${msg}`));
57794
- const interval = opts.replayIntervalMs ?? DEFAULT_REPLAY_INTERVAL_MS;
57795
- if (interval > 0) {
57796
- this.timer = setInterval(() => {
57797
- if (fs3.existsSync(opts.dir))
57798
- void this.replay();
57799
- }, interval);
57800
- this.timer.unref();
57870
+ function recordMissingReply(runtimeType, outcome = "ok") {
57871
+ if (!initialized)
57872
+ return;
57873
+ missingReplyCounter?.add(1, { runtime_type: runtimeType, outcome });
57874
+ }
57875
+ function recordTurnUsage(usage, runtimeType) {
57876
+ if (!initialized || !usage)
57877
+ return;
57878
+ const kinds = [
57879
+ ["input", usage.inputTokens],
57880
+ ["output", usage.outputTokens],
57881
+ ["cache_read", usage.cacheReadTokens],
57882
+ ["cache_creation", usage.cacheCreationTokens]
57883
+ ];
57884
+ for (const [kind, value] of kinds) {
57885
+ if (value !== void 0 && value > 0) {
57886
+ turnTokensCounter?.add(value, { kind, runtime_type: runtimeType });
57801
57887
  }
57802
57888
  }
57803
- get dir() {
57804
- return this.opts.dir;
57889
+ if (usage.costUsd !== void 0 && usage.costUsd > 0) {
57890
+ turnCostCounter?.add(usage.costUsd, { runtime_type: runtimeType });
57805
57891
  }
57806
- /** Count a batch the exporter dropped for a permanent status (never spooled). */
57807
- recordDrop(signal, reason, count = 1) {
57808
- this.opts.onEvent?.({ kind: "dropped", signal, reason, count });
57809
- }
57810
- /**
57811
- * Append one serialized request. Resolves once the file is renamed into
57812
- * place (or the batch was dropped). Writes are serialized so the eviction
57813
- * accounting never races. Never rejects.
57814
- */
57815
- enqueue(signal, bytes) {
57816
- const run = this.writes.then(() => this.enqueueNow(signal, bytes)).catch(() => "write_failed");
57817
- this.writes = run;
57818
- return run;
57892
+ }
57893
+ var dispatchContextStorage = new AsyncLocalStorage();
57894
+ function runWithDispatchContext(ctx, fn) {
57895
+ return dispatchContextStorage.run({ ...ctx }, fn);
57896
+ }
57897
+ function patchDispatchContext(patch) {
57898
+ const store = dispatchContextStorage.getStore();
57899
+ if (store)
57900
+ Object.assign(store, patch);
57901
+ }
57902
+ function dispatchLogAttributes() {
57903
+ const store = dispatchContextStorage.getStore();
57904
+ if (!store)
57905
+ return {};
57906
+ const attrs = {};
57907
+ const set = (key, value) => {
57908
+ if (value)
57909
+ attrs[key] = value;
57910
+ };
57911
+ set("session.key", store.sessionKey);
57912
+ set("dispatch.event_id", store.dispatchEventId);
57913
+ set("dispatch.lane", store.lane);
57914
+ set("dispatch.target_uri", store.targetUri);
57915
+ set("dispatch.message_id", store.messageId);
57916
+ set("dispatch.thread_root_id", store.threadRootId);
57917
+ set("dispatch.event_type", store.eventType);
57918
+ return attrs;
57919
+ }
57920
+ function withActiveSpan(span, fn) {
57921
+ if (!span)
57922
+ return fn();
57923
+ return context.with(trace.setSpan(context.active(), span), fn);
57924
+ }
57925
+ function runInDispatchScope(span, ctx, fn) {
57926
+ return withActiveSpan(span, () => runWithDispatchContext(ctx, fn));
57927
+ }
57928
+ function dispatchLogContext(event, sessionKey) {
57929
+ return {
57930
+ sessionKey,
57931
+ messageId: event.messageId,
57932
+ eventType: event.type,
57933
+ dispatchEventId: event.dispatchEventId ?? null,
57934
+ threadRootId: event.threadRootId ?? null
57935
+ };
57936
+ }
57937
+ async function runInDispatchTrace(id, fn) {
57938
+ const active = trace.getActiveSpan();
57939
+ if (active && dispatchSpans.has(active)) {
57940
+ if (id.event && id.sessionKey) {
57941
+ active.setAttributes(dispatchEventAttributes(id.event, id.runtimeType, id.sessionKey));
57942
+ patchDispatchContext(dispatchLogContext(id.event, id.sessionKey));
57943
+ }
57944
+ return fn(active);
57819
57945
  }
57820
- async enqueueNow(signal, bytes) {
57821
- if (this.closed)
57822
- return "write_failed";
57823
- const drop = (reason) => {
57824
- this.recordDrop(signal, reason);
57825
- return reason;
57826
- };
57827
- if (bytes.length > this.maxBytes[signal])
57828
- return drop("oversized");
57829
- const idx = await this.load(signal);
57830
- const now = this.now();
57831
- const minInterval = this.minIntervalMs[signal] ?? 0;
57832
- const newest = idx.files[idx.files.length - 1];
57833
- if (minInterval > 0 && newest && now - newest.ts < minInterval)
57834
- return drop("throttled");
57835
- await this.evictExpired(signal, idx, now);
57836
- while (idx.files.length > 0 && idx.total + bytes.length > this.maxBytes[signal]) {
57837
- if (!await this.remove(signal, idx, idx.files[0]))
57838
- return drop("write_failed");
57839
- this.recordDrop(signal, "evicted_size");
57946
+ const span = id.event && id.sessionKey ? startDispatchSpan(id.event, id.runtimeType, id.sessionKey) : startTypedDispatchSpan(id.dispatchEventId, id.runtimeType);
57947
+ const ctx = id.event && id.sessionKey ? dispatchLogContext(id.event, id.sessionKey) : { sessionKey: "", dispatchEventId: id.dispatchEventId ?? null };
57948
+ return runInDispatchScope(span, ctx, async () => {
57949
+ try {
57950
+ return await fn(span);
57951
+ } catch (err) {
57952
+ recordDispatchError(span, err);
57953
+ throw err;
57954
+ } finally {
57955
+ span.end();
57840
57956
  }
57841
- const name = `${String(now).padStart(13, "0")}-${process.pid}-${String(this.seq++).padStart(6, "0")}.pb`;
57842
- const dir = this.signalDir(signal);
57957
+ });
57958
+ }
57959
+ async function runInPhaseSpan(phase, fn) {
57960
+ if (!trace.getActiveSpan())
57961
+ return fn();
57962
+ return tracer().startActiveSpan(`parall.dispatch.${phase}`, async (span) => {
57843
57963
  try {
57844
- await fsp.mkdir(dir, { recursive: true });
57845
- const tmp = path3.join(dir, `${name}.tmp`);
57846
- await fsp.writeFile(tmp, bytes);
57847
- await fsp.rename(tmp, path3.join(dir, name));
57964
+ return await fn();
57848
57965
  } catch (err) {
57849
- this.log(`spool write failed for ${signal}: ${String(err)}`);
57850
- return drop("write_failed");
57966
+ span.setStatus({ code: SpanStatusCode.ERROR, message: redactSecrets(String(err)) });
57967
+ throw err;
57968
+ } finally {
57969
+ span.end();
57851
57970
  }
57852
- idx.files.push({ name, bytes: bytes.length, ts: now });
57853
- idx.total += bytes.length;
57854
- this.opts.onEvent?.({ kind: "queued", signal, bytes: bytes.length });
57855
- this.log(`spooled ${signal} ${bytes.length}B for replay (${idx.files.length} files, ${idx.total}B queued)`);
57856
- return "queued";
57857
- }
57858
- /** The endpoint answered a live export: replay what waits, if anything does. */
57859
- notifyOnline() {
57860
- if (this.closed)
57971
+ });
57972
+ }
57973
+ function runOutsideDispatchScope(fn) {
57974
+ return context.with(ROOT_CONTEXT, () => dispatchContextStorage.exit(fn));
57975
+ }
57976
+ function traceContextHeaders() {
57977
+ const carrier = {};
57978
+ propagation.inject(context.active(), carrier);
57979
+ return Object.keys(carrier).length > 0 ? carrier : void 0;
57980
+ }
57981
+ function createOtelLogger(layer, prefix) {
57982
+ const ts = () => (/* @__PURE__ */ new Date()).toISOString();
57983
+ const emit = (severity, msg) => {
57984
+ if (!otelLogger)
57861
57985
  return;
57862
- this.replayWanted = true;
57863
- if (fs3.existsSync(this.opts.dir))
57864
- void this.replay();
57865
- }
57866
- /**
57867
- * Oldest-first replay across all signals, single-flight, bounded per pass;
57868
- * stops at the first transient failure and leaves the rest for the next
57869
- * pass. Never rejects.
57870
- */
57871
- replay() {
57872
- if (this.replaying)
57873
- return this.replaying;
57874
- this.replayWanted = false;
57875
- this.replaying = this.replayNow().catch((err) => {
57876
- this.log(`spool replay failed: ${String(err)}`);
57877
- return { replayed: 0, dropped: 0, deferred: true };
57878
- }).finally(() => {
57879
- this.replaying = null;
57880
- if (this.replayWanted && !this.closed)
57881
- void this.replay();
57986
+ const severityNumber = severity === "ERROR" ? import_api_logs.SeverityNumber.ERROR : severity === "WARN" ? import_api_logs.SeverityNumber.WARN : import_api_logs.SeverityNumber.INFO;
57987
+ const attrs = {
57988
+ "log.layer": layer,
57989
+ "log.prefix": prefix,
57990
+ ...dispatchLogAttributes()
57991
+ };
57992
+ otelLogger.emit({
57993
+ severityNumber,
57994
+ severityText: severity,
57995
+ body: msg,
57996
+ attributes: attrs
57997
+ });
57998
+ };
57999
+ return {
58000
+ info: (msg) => {
58001
+ console.log(`${ts()} [${prefix}] ${msg}`);
58002
+ emit("INFO", msg);
58003
+ },
58004
+ warn: (msg) => {
58005
+ console.warn(`${ts()} [${prefix}] ${msg}`);
58006
+ emit("WARN", msg);
58007
+ },
58008
+ error: (msg) => {
58009
+ console.error(`${ts()} [${prefix}] ${msg}`);
58010
+ emit("ERROR", msg);
58011
+ },
58012
+ child: (sub) => createOtelLogger(layer, `${prefix}:${sub}`)
58013
+ };
58014
+ }
58015
+
58016
+ // ts/agent-core/dist/gateway-lane-settle.js
58017
+ async function settleNonCleanTurn(host, sessionKey, lane) {
58018
+ const ledger = host.laneLedger;
58019
+ const settled = host.consumeTurnOutcome(sessionKey);
58020
+ if (!settled)
58021
+ return void 0;
58022
+ if (settled.kind === "deferred") {
58023
+ ledger.markTurnDeferred(lane.laneKey, {
58024
+ outcomeClass: settled.outcomeClass,
58025
+ ...settled.retryAt ? { retryAt: settled.retryAt } : {}
58026
+ });
58027
+ } else {
58028
+ ledger.markTurnError(lane.laneKey, {
58029
+ ...settled.outcomeClass ? { outcomeClass: settled.outcomeClass } : {},
58030
+ ...settled.detail ? { detail: settled.detail } : {}
57882
58031
  });
57883
- return this.replaying;
57884
58032
  }
57885
- async replayNow() {
57886
- const started = this.now();
57887
- let replayed = 0;
57888
- let dropped = 0;
57889
- let sentFiles = 0;
57890
- for (const signal of SPOOL_SIGNALS) {
57891
- const idx = await this.load(signal);
57892
- await this.evictExpired(signal, idx, started);
57893
- for (const file of [...idx.files]) {
57894
- if (this.closed)
57895
- return { replayed, dropped, deferred: true };
57896
- if (sentFiles >= this.budget.files || this.now() - started > this.budget.wallMs) {
57897
- return { replayed, dropped, deferred: true };
57898
- }
57899
- if (this.sent.has(file.name))
57900
- continue;
57901
- const full = path3.join(this.signalDir(signal), file.name);
57902
- let body;
57903
- try {
57904
- body = await fsp.readFile(full);
57905
- } catch (err) {
57906
- const missing = err.code === "ENOENT";
57907
- if (await this.remove(signal, idx, file, missing)) {
57908
- if (!missing) {
57909
- this.recordDrop(signal, "unreadable");
57910
- dropped += 1;
57911
- }
57912
- }
57913
- continue;
57914
- }
57915
- const outcome = await this.post(signal, body);
57916
- sentFiles += 1;
57917
- if (outcome === "ok" || outcome === "permanent") {
57918
- if (!await this.remove(signal, idx, file))
57919
- this.sent.add(file.name);
57920
- if (outcome === "ok") {
57921
- this.opts.onEvent?.({ kind: "replayed", signal, bytes: file.bytes });
57922
- replayed += 1;
57923
- } else {
57924
- this.recordDrop(signal, "permanent_status");
57925
- dropped += 1;
57926
- }
57927
- } else {
57928
- return { replayed, dropped, deferred: true };
57929
- }
58033
+ for (const msgId of lane.folded.keys()) {
58034
+ host.dispatchedMessages.delete(msgId);
58035
+ }
58036
+ try {
58037
+ host.opts.dispatchAdapter.abortDispatch?.(sessionKey);
58038
+ } catch {
58039
+ }
58040
+ await runInPhaseSpan("settle", () => ledger.completeIfIdle(lane.laneKey, false));
58041
+ return settled.kind === "deferred" ? "deferred" : "failed";
58042
+ }
58043
+ function liveSteerMembers(host, sessionKey, lane, events) {
58044
+ const adapter = host.opts.dispatchAdapter;
58045
+ return events.filter((ev) => {
58046
+ const deliveryKey = lane.folded.get(ev.messageId);
58047
+ return deliveryKey != null && adapter.isInjectionLive?.(sessionKey, deliveryKey) === true;
58048
+ });
58049
+ }
58050
+ async function attachLiveSteers(host, opts, lane, live) {
58051
+ const ledger = host.laneLedger;
58052
+ host.noteSessionLane(opts.sessionKey, lane.laneKey);
58053
+ try {
58054
+ for (const ev of live) {
58055
+ host.opts.log?.info(`lane group for ${ev.messageId} is a live steer input \u2014 attaching to the runtime's own turn for it`);
58056
+ try {
58057
+ await host.runDispatch(ev, opts.sessionKey, eventBody(ev), [], opts.captureText, ledger.inputLifecycleFor(lane, [ev.messageId]));
58058
+ } catch (err) {
58059
+ host.opts.log?.warn(`attached steer input for ${ev.messageId} ended with an error: ${String(err)}`);
57930
58060
  }
58061
+ while (opts.sessionKey === host.opts.runtimeKey && hasMainSteers(host.dispatchState)) {
58062
+ await waitForMainSteers(host.dispatchState);
58063
+ }
58064
+ const settled = await settleNonCleanTurn(host, opts.sessionKey, lane);
58065
+ if (settled)
58066
+ return settled;
57931
58067
  }
57932
- if (replayed > 0)
57933
- this.log(`spool replayed ${replayed} file(s)`);
57934
- return { replayed, dropped, deferred: false };
58068
+ } finally {
58069
+ host.noteSessionLane(opts.sessionKey, null);
57935
58070
  }
57936
- async post(signal, body) {
57937
- try {
57938
- const res = await this.fetchImpl(`${this.opts.endpoint}/v1/${signal}`, {
57939
- method: "POST",
57940
- headers: { ...this.opts.headers, "Content-Type": "application/x-protobuf" },
57941
- // A Buffer may sit on a shared ArrayBuffer, which BodyInit's typing
57942
- // rejects; the copy is a plain Uint8Array over its own buffer.
57943
- body: new Uint8Array(body),
57944
- signal: AbortSignal.timeout(REPLAY_REQUEST_TIMEOUT_MS)
57945
- });
57946
- await res.arrayBuffer().catch(() => void 0);
57947
- if (res.ok)
57948
- return "ok";
57949
- return isPermanentStatus(res.status) ? "permanent" : "transient";
57950
- } catch {
57951
- return "transient";
57952
- }
58071
+ return void 0;
58072
+ }
58073
+
58074
+ // ts/agent-core/dist/lane-ledger.js
58075
+ import * as fs3 from "node:fs";
58076
+
58077
+ // ts/agent-core/dist/lane-key.js
58078
+ import * as path4 from "node:path";
58079
+ function laneKeyForTarget(targetUri, threadRootId) {
58080
+ return Buffer.from(`${targetUri}
58081
+ ${threadRootId ?? ""}`, "utf8").toString("base64url");
58082
+ }
58083
+ function dispatchLaneContextDir(stateDir) {
58084
+ return path4.join(stateDir, "dispatch-lane-context");
58085
+ }
58086
+ function laneContextFilePath(contextDir, targetUri, threadRootId) {
58087
+ return path4.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
58088
+ }
58089
+
58090
+ // ts/agent-core/dist/lane-target.js
58091
+ var PRLL_SCHEME = "prll://";
58092
+ var CHAT_LANE_PREFIX = "cht_";
58093
+ var CHANNEL_LANE_PREFIX = `${PRLL_SCHEME}chv_`;
58094
+ function channelLaneTargetUri(item) {
58095
+ return item.event_type === "channel_message" && item.target_uri?.startsWith(CHANNEL_LANE_PREFIX) ? item.target_uri : void 0;
58096
+ }
58097
+ function laneTargetId(targetUri) {
58098
+ return targetUri.startsWith(PRLL_SCHEME) ? targetUri.slice(PRLL_SCHEME.length) : targetUri;
58099
+ }
58100
+ function laneTargetUri(event) {
58101
+ if (event.type === "message") {
58102
+ return event.targetId.startsWith(CHAT_LANE_PREFIX) ? `${PRLL_SCHEME}${event.targetId}` : void 0;
57953
58103
  }
57954
- /** Stop the timer and wait for in-flight writes; a running replay stops at its next file. */
57955
- async close() {
57956
- this.closed = true;
57957
- if (this.timer)
57958
- clearInterval(this.timer);
57959
- this.timer = null;
57960
- await this.writes;
57961
- if (this.replaying)
57962
- await this.replaying;
58104
+ if (event.type === "channel_message") {
58105
+ return event.targetUri?.startsWith(CHANNEL_LANE_PREFIX) ? event.targetUri : void 0;
57963
58106
  }
57964
- signalDir(signal) {
57965
- return path3.join(this.opts.dir, signal);
58107
+ return void 0;
58108
+ }
58109
+ function isTypedEvent(event) {
58110
+ return event.type !== "message" && laneTargetUri(event) === void 0;
58111
+ }
58112
+
58113
+ // ts/agent-core/dist/lane-outcome.js
58114
+ function errorWireClass(cls) {
58115
+ if (!cls || cls === "ok" || cls === "usage_limit")
58116
+ return void 0;
58117
+ return cls;
58118
+ }
58119
+
58120
+ // ts/agent-core/dist/runtime-instance.js
58121
+ import { randomUUID as randomUUID3 } from "node:crypto";
58122
+ function newRuntimeInstanceId() {
58123
+ return randomUUID3().replace(/-/g, "");
58124
+ }
58125
+ function isTurnToken(token) {
58126
+ return token.startsWith("turn_");
58127
+ }
58128
+
58129
+ // ts/agent-core/dist/lane-input-receipts.js
58130
+ var LaneInputReceipts = class {
58131
+ opts;
58132
+ confirmations;
58133
+ constructor(opts, confirmations) {
58134
+ this.opts = opts;
58135
+ this.confirmations = confirmations;
57966
58136
  }
57967
- /** Read the directory once; afterwards the index is maintained in memory. */
57968
- async load(signal) {
57969
- const existing = this.index.get(signal);
57970
- if (existing)
57971
- return existing;
57972
- const idx = { files: [], total: 0 };
57973
- this.index.set(signal, idx);
57974
- const dir = this.signalDir(signal);
57975
- let names;
57976
- try {
57977
- names = await fsp.readdir(dir);
57978
- } catch {
57979
- return idx;
58137
+ lifecycle(lane, messageIds) {
58138
+ const explicit = lane.coverageMode === "explicit";
58139
+ const unique = [...new Set(messageIds)];
58140
+ const dispatchEventIds = unique.map((messageId) => lane.folded.get(messageId)).filter((id) => Boolean(id));
58141
+ if (explicit && dispatchEventIds.length !== unique.length) {
58142
+ throw new Error(`explicit lane ${lane.lane} is missing a folded WorkItem mapping`);
57980
58143
  }
57981
- const now = this.now();
57982
- for (const name of names.sort()) {
57983
- const full = path3.join(dir, name);
57984
- const m = FILE_RE.exec(name);
57985
- if (!m) {
57986
- if (name.endsWith(".tmp")) {
57987
- const stat3 = await fsp.stat(full).catch(() => null);
57988
- if (stat3 && now - stat3.mtimeMs > STALE_TMP_MS)
57989
- await fsp.unlink(full).catch(() => {
57990
- });
58144
+ if (!explicit && dispatchEventIds.length === 0)
58145
+ return void 0;
58146
+ return {
58147
+ deliveryKey: dispatchEventIds.join(","),
58148
+ dispatchEventIds,
58149
+ update: explicit ? (state, failure) => this.updateInputState(lane, dispatchEventIds, state, failure) : async () => void 0
58150
+ };
58151
+ }
58152
+ async updateInputState(lane, dispatchEventIds, state, failure) {
58153
+ lane.observedInputs ??= /* @__PURE__ */ new Map();
58154
+ for (const id of dispatchEventIds)
58155
+ lane.observedInputs.set(id, state);
58156
+ let confirmed;
58157
+ const ids = [...dispatchEventIds];
58158
+ const failed = new Set(state === "failed" ? ids : []);
58159
+ const sourceIds = [...lane.folded].filter(([, id]) => failed.has(id)).map(([id]) => id);
58160
+ const request3 = {
58161
+ lane: lane.lane,
58162
+ target_uri: lane.targetUri,
58163
+ thread_root_id: lane.threadRootId,
58164
+ dispatch_event_ids: ids,
58165
+ state,
58166
+ session_id: lane.sessionAmbiguous ? void 0 : lane.sessionId,
58167
+ ...state === "failed" && failure ? {
58168
+ outcome_class: errorWireClass(failure.outcomeClass),
58169
+ detail: failure.detail ? redactSecrets(failure.detail, this.opts.knownSecrets).slice(0, 500) : void 0
58170
+ } : {}
58171
+ };
58172
+ await this.confirmations.submit(lane.lane, {
58173
+ label: `input ${state}`,
58174
+ send: async () => {
58175
+ const restore = sourceIds.length ? this.opts.releaseLocalClaims?.(sourceIds) : void 0;
58176
+ let result;
58177
+ try {
58178
+ result = await this.opts.client.updateDispatchInputState(this.opts.orgId, request3);
58179
+ } catch (err) {
58180
+ restore?.();
58181
+ throw err;
57991
58182
  }
57992
- continue;
58183
+ if (result.recognized !== ids.length && !isTurnToken(lane.lane)) {
58184
+ restore?.();
58185
+ throw new ApiError(409, "input acknowledgement scope changed", "INPUT_SCOPE_CHANGED");
58186
+ }
58187
+ if (state === "failed") {
58188
+ for (const sourceId of sourceIds) {
58189
+ lane.folded.delete(sourceId);
58190
+ lane.seen.delete(sourceId);
58191
+ }
58192
+ }
58193
+ confirmed = { retry: state === "failed" && result.released > 0 };
57993
58194
  }
57994
- const stat2 = await fsp.stat(full).catch(() => null);
57995
- if (!stat2)
57996
- continue;
57997
- idx.files.push({ name, bytes: stat2.size, ts: Number(m[1]) });
57998
- idx.total += stat2.size;
57999
- }
58000
- return idx;
58195
+ });
58196
+ return confirmed ?? { retry: false, pending: true };
58001
58197
  }
58002
- async evictExpired(signal, idx, now) {
58003
- let evicted = 0;
58004
- for (const file of [...idx.files]) {
58005
- if (now - file.ts <= this.maxAgeMs)
58006
- break;
58007
- if (await this.remove(signal, idx, file))
58008
- evicted += 1;
58198
+ async syncAttribution(lane) {
58199
+ if (lane.settlementMode !== "receipt" || lane.settling || lane.sessionAmbiguous || !lane.sessionId || !lane.observedInputs?.size)
58200
+ return;
58201
+ const sessionId = lane.sessionId;
58202
+ const groups = /* @__PURE__ */ new Map();
58203
+ for (const [id, state] of lane.observedInputs) {
58204
+ const ids = groups.get(state) ?? [];
58205
+ ids.push(id);
58206
+ groups.set(state, ids);
58009
58207
  }
58010
- if (evicted > 0)
58011
- this.recordDrop(signal, "evicted_age", evicted);
58012
- }
58013
- /**
58014
- * Unlink and drop from the index. False when the file stays on disk: the
58015
- * entry is kept so it still counts against the budget (bounds hold even
58016
- * when deletion is refused), and the caller decides whether to skip it.
58017
- */
58018
- async remove(signal, idx, file, alreadyGone = false) {
58019
- if (!alreadyGone) {
58020
- try {
58021
- await fsp.unlink(path3.join(this.signalDir(signal), file.name));
58022
- } catch (err) {
58023
- if (err.code !== "ENOENT") {
58024
- this.log(`spool could not delete ${signal}/${file.name}: ${String(err)}`);
58025
- return false;
58208
+ for (const [state, ids] of groups) {
58209
+ await this.confirmations.submit(lane.lane, {
58210
+ label: "input session",
58211
+ send: async () => {
58212
+ await this.opts.client.updateDispatchInputState(this.opts.orgId, {
58213
+ lane: lane.lane,
58214
+ target_uri: lane.targetUri,
58215
+ thread_root_id: lane.threadRootId,
58216
+ dispatch_event_ids: ids,
58217
+ state,
58218
+ session_id: sessionId
58219
+ });
58026
58220
  }
58027
- }
58028
- }
58029
- const at = idx.files.indexOf(file);
58030
- if (at >= 0) {
58031
- idx.files.splice(at, 1);
58032
- idx.total -= file.bytes;
58221
+ });
58033
58222
  }
58034
- return true;
58035
58223
  }
58036
58224
  };
58037
58225
 
58038
- // ts/agent-core/dist/otlp-spool-exporter.js
58039
- var import_core = __toESM(require_src2(), 1);
58040
- var SpoolingExporter = class {
58041
- delegate;
58042
- serializer;
58043
- signal;
58044
- store;
58045
- pending = /* @__PURE__ */ new Set();
58046
- failing = false;
58047
- everSucceeded = false;
58048
- selectAggregationTemporality;
58049
- selectAggregation;
58050
- constructor(delegate, serializer, signal, store) {
58051
- this.delegate = delegate;
58052
- this.serializer = serializer;
58053
- this.signal = signal;
58054
- this.store = store;
58055
- if (delegate.selectAggregationTemporality) {
58056
- this.selectAggregationTemporality = delegate.selectAggregationTemporality.bind(delegate);
58057
- }
58058
- if (delegate.selectAggregation) {
58059
- this.selectAggregation = delegate.selectAggregation.bind(delegate);
58060
- }
58226
+ // ts/agent-core/dist/lane-confirmations.js
58227
+ var LaneConfirmations = class {
58228
+ opts;
58229
+ pending = /* @__PURE__ */ new Map();
58230
+ disposed = false;
58231
+ constructor(opts) {
58232
+ this.opts = opts;
58061
58233
  }
58062
- export(items, resultCallback) {
58063
- this.delegate.export(items, (result) => {
58064
- if (result.code === import_core.ExportResultCode.SUCCESS) {
58065
- if (this.failing || !this.everSucceeded)
58066
- this.store.notifyOnline();
58067
- this.failing = false;
58068
- this.everSucceeded = true;
58069
- resultCallback(result);
58070
- return;
58071
- }
58072
- const cls = classifyExportError(result.error);
58073
- if (cls === "permanent")
58074
- this.store.recordDrop(this.signal, "permanent_status");
58075
- if (cls !== "transient") {
58076
- resultCallback(result);
58234
+ /**
58235
+ * Try once inline; a retained write returns without blocking native
58236
+ * execution. A write ordered behind the token's in-flight write resolves
58237
+ * when its OWN attempt has run (the caller must learn that write's
58238
+ * outcome, not the earlier one's — reporting a queued failed receipt as
58239
+ * settled lost a delivered input, 2026-09-17), unless the token is in a
58240
+ * retry backoff, where that attempt may be minutes away.
58241
+ */
58242
+ async submit(token, write) {
58243
+ if (this.disposed) {
58244
+ write.onAttempt?.("dropped");
58245
+ return;
58246
+ }
58247
+ let pending = this.pending.get(token);
58248
+ if (pending) {
58249
+ if (pending.blocked) {
58250
+ write.onAttempt?.("blocked");
58077
58251
  return;
58078
58252
  }
58079
- this.failing = true;
58080
- let bytes;
58081
- try {
58082
- bytes = this.serializer.serializeRequest(items);
58083
- } catch {
58084
- bytes = void 0;
58085
- }
58086
- if (!bytes || bytes.length === 0) {
58087
- resultCallback(result);
58253
+ pending.writes.push(write);
58254
+ if (pending.timer)
58088
58255
  return;
58089
- }
58090
- const write = this.store.enqueue(this.signal, bytes).then((outcome) => {
58091
- const handled = outcome === "queued" || outcome === "throttled";
58092
- resultCallback(handled ? { code: import_core.ExportResultCode.SUCCESS } : result);
58093
- }).finally(() => {
58094
- this.pending.delete(write);
58256
+ await new Promise((resolve3) => {
58257
+ const prior = write.onAttempt;
58258
+ write.onAttempt = (outcome) => {
58259
+ prior?.(outcome);
58260
+ resolve3();
58261
+ };
58095
58262
  });
58096
- this.pending.add(write);
58263
+ return;
58264
+ }
58265
+ pending = { writes: [write], failures: 0, blocked: false };
58266
+ this.pending.set(token, pending);
58267
+ await this.run(token, pending);
58268
+ }
58269
+ settleWrites(writes, outcome) {
58270
+ for (const write of writes)
58271
+ write.onAttempt?.(outcome);
58272
+ }
58273
+ async run(token, pending) {
58274
+ if (pending.running || pending.blocked || this.pending.get(token) !== pending)
58275
+ return;
58276
+ const recovered = pending.failures > 0;
58277
+ pending.running = Promise.resolve().then(async () => {
58278
+ while (pending.writes.length && this.pending.get(token) === pending) {
58279
+ const write = pending.writes[0];
58280
+ try {
58281
+ await write.send();
58282
+ pending.writes.shift();
58283
+ if (this.pending.get(token) === pending)
58284
+ write.onAttempt?.("sent");
58285
+ } catch (err) {
58286
+ if (this.pending.get(token) !== pending) {
58287
+ this.settleWrites(pending.writes, "dropped");
58288
+ return;
58289
+ }
58290
+ if (err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE") {
58291
+ this.pending.delete(token);
58292
+ this.settleWrites(pending.writes, "dropped");
58293
+ this.opts.onStale(token);
58294
+ this.opts.onRecovered?.();
58295
+ return;
58296
+ }
58297
+ const transient = !(err instanceof ApiError) || err.status === 0 || err.status >= 500 || err.status === 408 || err.status === 429;
58298
+ if (!transient) {
58299
+ pending.blocked = true;
58300
+ this.opts.log?.error(`lane ${write.label} rejected for ${token}; confirmation retained: ${String(err)}`);
58301
+ this.settleWrites(pending.writes, "blocked");
58302
+ return;
58303
+ }
58304
+ pending.failures += 1;
58305
+ this.settleWrites(pending.writes, "retained");
58306
+ this.opts.log?.warn(`lane ${write.label} unconfirmed for ${token}; retry ${pending.failures}: ${String(err)}`);
58307
+ const delays = this.opts.delaysMs?.length ? this.opts.delaysMs : [2e3, 1e4, 3e4, 6e4, 12e4];
58308
+ const delay = delays[Math.min(pending.failures - 1, delays.length - 1)];
58309
+ pending.timer = setTimeout(() => {
58310
+ pending.timer = void 0;
58311
+ void this.run(token, pending);
58312
+ }, delay);
58313
+ pending.timer.unref?.();
58314
+ return;
58315
+ }
58316
+ }
58317
+ if (this.pending.get(token) === pending)
58318
+ this.pending.delete(token);
58319
+ if (recovered)
58320
+ this.opts.onRecovered?.();
58097
58321
  });
58322
+ try {
58323
+ await pending.running;
58324
+ } finally {
58325
+ pending.running = void 0;
58326
+ }
58098
58327
  }
58099
- /** The delegate's flush, then every spool write it caused — the barrier shutdown relies on. */
58100
- async forceFlush() {
58101
- await this.delegate.forceFlush?.();
58102
- await Promise.all([...this.pending]);
58328
+ /** Reconnect/shutdown may accelerate retries; permanent rejections stay visible. */
58329
+ async retryNow() {
58330
+ await Promise.all([...this.pending].map(async ([token, pending]) => {
58331
+ if (pending.timer)
58332
+ clearTimeout(pending.timer);
58333
+ pending.timer = void 0;
58334
+ await this.run(token, pending);
58335
+ }));
58103
58336
  }
58104
- async shutdown() {
58105
- await this.forceFlush();
58106
- await this.delegate.shutdown();
58337
+ forget(token) {
58338
+ const pending = this.pending.get(token);
58339
+ if (pending?.timer)
58340
+ clearTimeout(pending.timer);
58341
+ this.pending.delete(token);
58342
+ if (pending) {
58343
+ const writes = pending.writes;
58344
+ pending.writes = [];
58345
+ this.settleWrites(writes, "dropped");
58346
+ }
58347
+ }
58348
+ dispose() {
58349
+ this.disposed = true;
58350
+ for (const token of this.pending.keys())
58351
+ this.forget(token);
58107
58352
  }
58108
58353
  };
58109
58354
 
58110
- // ts/agent-core/dist/telemetry.js
58111
- var initialized = false;
58112
- var shutdownFn = null;
58113
- var tracer = () => trace.getTracer("parall.agent");
58114
- var dispatchSpans = /* @__PURE__ */ new WeakSet();
58115
- var recordedErrors = /* @__PURE__ */ new WeakSet();
58116
- var dispatchCounter = null;
58117
- var dispatchDuration = null;
58118
- var missingReplyCounter = null;
58119
- var turnTokensCounter = null;
58120
- var turnCostCounter = null;
58121
- var otelLogger = null;
58122
- var spoolCounters = null;
58123
- function recordSpoolEvent(event) {
58124
- if (!spoolCounters)
58125
- return;
58126
- if (event.kind === "queued")
58127
- spoolCounters.queued.add(1, { signal: event.signal });
58128
- else if (event.kind === "replayed")
58129
- spoolCounters.replayed.add(1, { signal: event.signal });
58130
- else
58131
- spoolCounters.dropped.add(event.count, { signal: event.signal, reason: event.reason });
58355
+ // ts/agent-core/dist/lane-ledger.js
58356
+ var LedgerUnsupportedError = class extends Error {
58357
+ };
58358
+ function bindLaneSession(lane, agentSessionId) {
58359
+ if (lane.sessionId && lane.sessionId !== agentSessionId) {
58360
+ lane.sessionAmbiguous = true;
58361
+ } else if (!lane.sessionAmbiguous) {
58362
+ lane.sessionId = agentSessionId;
58363
+ }
58132
58364
  }
58133
- function resolveTargetType(targetId) {
58134
- if (targetId.startsWith("cht_"))
58135
- return "chat";
58136
- if (targetId.startsWith("tsk_"))
58137
- return "task";
58138
- if (targetId.startsWith("sch_"))
58139
- return "schedule";
58140
- return "unknown";
58365
+ function releaseLocalMessageClaims(claims, sourceIds) {
58366
+ const released = sourceIds.filter((sourceId) => claims.delete(sourceId));
58367
+ return () => {
58368
+ for (const sourceId of released)
58369
+ claims.add(sourceId);
58370
+ };
58141
58371
  }
58142
- var PRODUCTION_API_HOSTS = /* @__PURE__ */ new Set(["api.parall.com"]);
58143
- var STAGING_API_HOSTS = /* @__PURE__ */ new Set(["api.staging.prll.sh"]);
58144
- function resolveTelemetryEnvironment(apiUrl, override = process.env.PRLL_SERVER_ENV) {
58145
- const forced = override?.trim();
58146
- if (forced)
58147
- return forced;
58148
- let host = "";
58149
- try {
58150
- host = apiUrl ? new URL(apiUrl).hostname.toLowerCase() : "";
58151
- } catch {
58152
- host = "";
58153
- }
58154
- if (PRODUCTION_API_HOSTS.has(host))
58155
- return "production";
58156
- if (STAGING_API_HOSTS.has(host))
58157
- return "staging";
58158
- return "development";
58372
+ function isStaleLane(err) {
58373
+ return err instanceof ApiError && err.status === 409 && err.code === "STALE_LANE";
58159
58374
  }
58160
- function resolveServiceVersion(importMetaUrl) {
58161
- const fallback = process.env.npm_package_version || "unknown";
58162
- let dir;
58163
- try {
58164
- dir = path4.dirname(fileURLToPath2(importMetaUrl));
58165
- } catch {
58166
- return fallback;
58167
- }
58168
- for (const candidate of [path4.join(dir, "manifest.json"), path4.join(dir, "..", "package.json")]) {
58169
- try {
58170
- const parsed = JSON.parse(readFileSync2(candidate, "utf-8"));
58171
- if (typeof parsed.version === "string" && parsed.version.trim()) {
58172
- return parsed.version.trim();
58173
- }
58174
- } catch {
58175
- }
58176
- }
58177
- return fallback;
58375
+ function isEndpointMissing2(err) {
58376
+ return err instanceof ApiError && err.status === 404 && !err.code;
58178
58377
  }
58179
- var DIAG_THROTTLE_MS = 6e4;
58180
- var DIAG_THROTTLE_KEYS = 200;
58181
- function createThrottledDiagLogger(now = Date.now) {
58182
- const lastAt = /* @__PURE__ */ new Map();
58183
- const describe = (a) => {
58184
- if (a instanceof Error)
58185
- return a.message;
58186
- if (a && typeof a === "object" && typeof a.message === "string") {
58187
- return a.message;
58188
- }
58189
- if (typeof a === "string" && a.startsWith("{")) {
58190
- try {
58191
- const parsed = JSON.parse(a);
58192
- if (typeof parsed.message === "string")
58193
- return parsed.message;
58194
- } catch {
58378
+ var LaneLedger = class {
58379
+ opts;
58380
+ lanes = /* @__PURE__ */ new Map();
58381
+ confirmations;
58382
+ inputs;
58383
+ claimResponses = /* @__PURE__ */ new Map();
58384
+ claims = /* @__PURE__ */ new Map();
58385
+ constructor(opts) {
58386
+ this.opts = opts;
58387
+ this.confirmations = new LaneConfirmations({
58388
+ delaysMs: opts.terminalRetryDelaysMs,
58389
+ log: opts.log,
58390
+ onRecovered: opts.onRecovered,
58391
+ onStale: (token) => {
58392
+ for (const lane of this.lanes.values()) {
58393
+ if (lane.lane === token)
58394
+ this.forgetLane(lane);
58395
+ }
58195
58396
  }
58397
+ });
58398
+ this.inputs = new LaneInputReceipts(opts, this.confirmations);
58399
+ }
58400
+ get contextDir() {
58401
+ return this.opts.contextDir;
58402
+ }
58403
+ /** Message-lane events (chat, channel conversation — lane-target.ts) ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
58404
+ handles(event) {
58405
+ return laneTargetUri(event) !== void 0;
58406
+ }
58407
+ laneKeyFor(event) {
58408
+ const targetUri = laneTargetUri(event);
58409
+ if (!targetUri && event.type !== "message" && event.dispatchEventId) {
58410
+ return laneKeyForTarget(`dsp:${event.dispatchEventId}`);
58196
58411
  }
58197
- return String(a);
58198
- };
58199
- const emit = (level, args) => {
58200
- const msg = args.map(describe).join(" ");
58201
- const key = `${level}:${msg.slice(0, 160)}`;
58202
- const at = now();
58203
- const prev = lastAt.get(key);
58204
- if (prev !== void 0 && at - prev < DIAG_THROTTLE_MS)
58205
- return;
58206
- if (lastAt.size >= DIAG_THROTTLE_KEYS)
58207
- lastAt.clear();
58208
- lastAt.set(key, at);
58209
- console.warn(`${new Date(at).toISOString()} [telemetry] otel ${level}: ${msg}`);
58210
- };
58211
- return {
58212
- verbose: () => {
58213
- },
58214
- debug: () => {
58215
- },
58216
- info: () => {
58217
- },
58218
- warn: (...args) => emit("warn", args),
58219
- error: (...args) => emit("error", args)
58220
- };
58221
- }
58222
- async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
58223
- const noopHandle = { shutdown: async () => {
58224
- } };
58225
- const apiUrl = opts.apiUrl ?? process.env.PRLL_API_URL;
58226
- const apiKey = opts.apiKey ?? process.env.PRLL_API_KEY;
58227
- if (!apiUrl || !apiKey) {
58228
- console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] disabled: no API url/key resolved for ${serviceName} \u2014 nothing will reach SigNoz`);
58229
- return noopHandle;
58412
+ return laneKeyForTarget(targetUri ?? `prll://${event.targetId}`, event.threadRootId);
58230
58413
  }
58231
- const environment = opts.environment ?? resolveTelemetryEnvironment(apiUrl);
58232
- const serviceVersion = opts.serviceVersion ?? process.env.npm_package_version ?? "unknown";
58233
- try {
58234
- const otelEndpoint = apiUrl.replace(/\/$/, "") + "/otel";
58235
- if (!initialized)
58236
- diag2.setLogger(createThrottledDiagLogger(), DiagLogLevel.WARN);
58237
- const { OTLPTraceExporter } = await Promise.resolve().then(() => __toESM(require_src6(), 1));
58238
- const { OTLPMetricExporter } = await Promise.resolve().then(() => __toESM(require_src8(), 1));
58239
- const { OTLPLogExporter } = await Promise.resolve().then(() => __toESM(require_src9(), 1));
58240
- const { NodeTracerProvider, BatchSpanProcessor } = await Promise.resolve().then(() => __toESM(require_src14(), 1));
58241
- const { MeterProvider, PeriodicExportingMetricReader } = await Promise.resolve().then(() => __toESM(require_src4(), 1));
58242
- const { LoggerProvider, BatchLogRecordProcessor } = await Promise.resolve().then(() => __toESM(require_src15(), 1));
58243
- const { Resource } = await Promise.resolve().then(() => __toESM(require_src3(), 1));
58244
- const resource = new Resource({
58245
- "service.name": serviceName,
58246
- "service.version": serviceVersion,
58247
- "deployment.environment.name": environment,
58248
- "parall.runtime_type": runtimeType,
58249
- "parall.agent_id": process.env.PRLL_AGENT_ID || "",
58250
- "parall.machine_id": process.env.PRLL_MACHINE_ID || "",
58251
- "parall.org_id": process.env.PRLL_ORG_ID || "",
58252
- "parall.daemon_mode": process.env.PRLL_DAEMON_MODE === "1"
58253
- });
58254
- const authHeaders = { Authorization: `Bearer ${apiKey}` };
58255
- const spoolDir = (opts.spoolDir ?? process.env.PRLL_OTEL_SPOOL_DIR)?.trim() || void 0;
58256
- const spool = spoolDir ? new OtlpSpoolStore({
58257
- dir: spoolDir,
58258
- endpoint: otelEndpoint,
58259
- headers: authHeaders,
58260
- onEvent: recordSpoolEvent
58261
- }) : null;
58262
- const serializers = spool ? await Promise.resolve().then(() => __toESM(require_src5(), 1)) : null;
58263
- const spooled = (exporter, signal, serializer) => spool && serializer ? new SpoolingExporter(exporter, serializer, signal, spool) : exporter;
58264
- const traceExporter = spooled(new OTLPTraceExporter({ url: `${otelEndpoint}/v1/traces`, headers: authHeaders }), "traces", serializers?.ProtobufTraceSerializer);
58265
- const tracerProvider = new NodeTracerProvider({ resource });
58266
- tracerProvider.addSpanProcessor(new BatchSpanProcessor(traceExporter));
58267
- tracerProvider.register();
58268
- const metricExporter = spooled(new OTLPMetricExporter({ url: `${otelEndpoint}/v1/metrics`, headers: authHeaders }), "metrics", serializers?.ProtobufMetricsSerializer);
58269
- const metricReader = new PeriodicExportingMetricReader({
58270
- exporter: metricExporter,
58271
- exportIntervalMillis: 15e3
58272
- });
58273
- const meterProvider = new MeterProvider({ resource, readers: [metricReader] });
58274
- metrics.setGlobalMeterProvider(meterProvider);
58275
- const logExporter = spooled(new OTLPLogExporter({ url: `${otelEndpoint}/v1/logs`, headers: authHeaders }), "logs", serializers?.ProtobufLogsSerializer);
58276
- const loggerProvider = new LoggerProvider({ resource });
58277
- loggerProvider.addLogRecordProcessor(new BatchLogRecordProcessor(logExporter));
58278
- const meter = metrics.getMeter("parall.agent");
58279
- otelLogger = loggerProvider.getLogger("parall.agent");
58280
- dispatchCounter = meter.createCounter("parall.dispatch.count", {
58281
- description: "Number of dispatch cycles completed"
58282
- });
58283
- dispatchDuration = meter.createHistogram("parall.dispatch.duration", {
58284
- description: "Dispatch cycle duration in milliseconds",
58285
- unit: "ms"
58286
- });
58287
- missingReplyCounter = meter.createCounter("parall.dispatch.missing_reply", {
58288
- description: "Dispatches where agent produced text but sent no reply message"
58289
- });
58290
- turnTokensCounter = meter.createCounter("parall.turn.tokens", {
58291
- description: "LLM tokens consumed per turn, by kind (input/output/cache_read/cache_creation)"
58292
- });
58293
- turnCostCounter = meter.createCounter("parall.turn.cost_usd", {
58294
- description: "LLM cost per turn in USD (when the runtime reports it)"
58295
- });
58296
- if (spool) {
58297
- const spoolMeter = metrics.getMeter("parall.telemetry");
58298
- spoolCounters = {
58299
- queued: spoolMeter.createCounter("parall.telemetry.spool.queued", {
58300
- description: "OTLP batches spooled to disk after a failed export"
58301
- }),
58302
- replayed: spoolMeter.createCounter("parall.telemetry.spool.replayed", {
58303
- description: "Spooled OTLP batches delivered on replay"
58304
- }),
58305
- dropped: spoolMeter.createCounter("parall.telemetry.spool.dropped", {
58306
- description: "OTLP batches dropped instead of spooled or replayed, by reason"
58307
- })
58414
+ getForEvent(event) {
58415
+ return this.lanes.get(this.laneKeyFor(event));
58416
+ }
58417
+ laneContextPath(lane) {
58418
+ return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
58419
+ }
58420
+ /**
58421
+ * Whether the server already rendered this message into a frame the model
58422
+ * saw on its live lane. The row is folded there and resolves with that
58423
+ * lane's turn — a local copy has nothing left to deliver.
58424
+ */
58425
+ seenInFrame(targetId, threadRootId, messageId) {
58426
+ const lane = this.lanes.get(laneKeyForTarget(`prll://${targetId}`, threadRootId));
58427
+ return lane?.seen.has(messageId) ?? false;
58428
+ }
58429
+ /**
58430
+ * Hand the pending frame to the caller (once) with the members it covers
58431
+ * and what the claim said about the wake, and record those members as
58432
+ * seen. Absent frame ⇒ nothing new to render (every member already seen).
58433
+ */
58434
+ takeFrame(lane) {
58435
+ const frame = lane.frame;
58436
+ const ids = lane.framed;
58437
+ for (const id of ids)
58438
+ lane.seen.add(id);
58439
+ lane.frame = void 0;
58440
+ lane.framed = [];
58441
+ const { input, noReply, attachments } = lane;
58442
+ lane.input = void 0;
58443
+ lane.noReply = void 0;
58444
+ lane.attachments = void 0;
58445
+ return { frame, ids, input, noReply, attachments };
58446
+ }
58447
+ /** Record what the claim response said about the wake alongside its frame. */
58448
+ recordWake(lane, res) {
58449
+ if (res.input)
58450
+ lane.input = res.input;
58451
+ if (res.no_reply != null)
58452
+ lane.noReply = res.no_reply;
58453
+ if (res.attachments?.length) {
58454
+ lane.attachments = res.attachments.map((a) => ({
58455
+ id: a.id,
58456
+ fileName: a.file_name ?? "",
58457
+ fileSize: a.file_size ?? 0,
58458
+ mimeType: a.mime_type ?? ""
58459
+ }));
58460
+ }
58461
+ }
58462
+ /** The injection landed: the model has seen these members. */
58463
+ markSeen(event, ids) {
58464
+ const lane = this.lanes.get(this.laneKeyFor(event));
58465
+ if (!lane)
58466
+ return;
58467
+ for (const id of ids)
58468
+ lane.seen.add(id);
58469
+ }
58470
+ /**
58471
+ * The injection did not land (turn already over, process gone): keep the
58472
+ * server's increment as the lane's pending frame so the buffered copy's
58473
+ * drain renders it as its own turn instead of skipping it as seen.
58474
+ */
58475
+ deferFrame(event, frame, ids) {
58476
+ const lane = this.lanes.get(this.laneKeyFor(event));
58477
+ if (!lane)
58478
+ return;
58479
+ this.recordFrame(lane, frame, ids);
58480
+ }
58481
+ recordFrame(lane, frame, ids) {
58482
+ if (!frame)
58483
+ return;
58484
+ lane.frame = lane.frame ? `${lane.frame}
58485
+
58486
+ ${frame}` : frame;
58487
+ lane.framed.push(...ids);
58488
+ }
58489
+ /**
58490
+ * Claim (or reuse) the lane for a group of same-lane message events and
58491
+ * fold every group member into it. Returns 'foreign' when a healthy
58492
+ * incumbent (another pod) holds the resource — the caller must not
58493
+ * dispatch; the events stay pending server-side and re-drive after the
58494
+ * incumbent completes.
58495
+ */
58496
+ async ensureLane(events) {
58497
+ const key = this.laneKeyFor(events[events.length - 1]);
58498
+ const prior = this.claims.get(key);
58499
+ const claim = (prior ? prior.catch(() => null) : Promise.resolve()).then(() => this.ensureLaneAttempt(events, false));
58500
+ this.claims.set(key, claim);
58501
+ try {
58502
+ return await claim;
58503
+ } finally {
58504
+ if (this.claims.get(key) === claim)
58505
+ this.claims.delete(key);
58506
+ }
58507
+ }
58508
+ /**
58509
+ * One ensureLane pass. `reclaimed` marks the arbitration retry: STALE_LANE
58510
+ * on a REUSED cached lane means our cache outlived the server lease (a
58511
+ * missed complete), not that a healthy incumbent holds the resource — claim
58512
+ * is the only ownership arbiter, so ask it once instead of leaving the
58513
+ * members to wait out the renotify pacing. STALE_LANE right after a fresh
58514
+ * claim is a real takeover race and stays foreign. The server's incumbency
58515
+ * check is the only staleness authority — deciding expiry locally from the
58516
+ * bridge wall clock against the server-issued lease_until would let a
58517
+ * clock-skewed host destructively discard a still-current lane's fold/seen
58518
+ * state, so no local pre-check exists on purpose.
58519
+ */
58520
+ async ensureLaneAttempt(events, reclaimed) {
58521
+ const trigger = events[events.length - 1];
58522
+ const laneKey = this.laneKeyFor(trigger);
58523
+ let lane = this.lanes.get(laneKey);
58524
+ if (lane?.settling)
58525
+ return null;
58526
+ const reused = lane != null;
58527
+ if (!lane) {
58528
+ const targetUri = laneTargetUri(trigger) ?? `prll://${trigger.targetId}`;
58529
+ const res = await this.claimRecoverably(laneKey, {
58530
+ target_uri: targetUri,
58531
+ thread_root_id: trigger.threadRootId,
58532
+ limit: 100,
58533
+ coverage_mode: this.opts.coverageMode ?? "implicit",
58534
+ settlement_mode: this.opts.instanceId ? this.opts.settlementMode : void 0,
58535
+ resume_received: this.opts.instanceId ? true : void 0,
58536
+ instance_id: this.opts.instanceId
58537
+ });
58538
+ if (!res)
58539
+ return null;
58540
+ if (!res.claimed || !res.lane) {
58541
+ if (res.reason === "empty") {
58542
+ this.opts.log?.warn(`claim for ${targetUri} came back empty \u2014 nothing foldable; leaving to the reconciler`);
58543
+ } else {
58544
+ this.opts.log?.info(`lane for ${targetUri} held by a healthy incumbent \u2014 leaving events pending for re-drive`);
58545
+ }
58546
+ return null;
58547
+ }
58548
+ const requestedCoverage = this.opts.coverageMode ?? "implicit";
58549
+ const actualCoverage = res.coverage_mode ?? "implicit";
58550
+ if (requestedCoverage === "explicit" && actualCoverage !== "explicit") {
58551
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, res.lane).catch(() => {
58552
+ });
58553
+ throw new Error(`server did not negotiate explicit input coverage for ${targetUri}; lane released`);
58554
+ }
58555
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
58556
+ lane = {
58557
+ laneKey,
58558
+ lane: res.lane,
58559
+ targetUri,
58560
+ threadRootId: trigger.threadRootId,
58561
+ coverageMode: actualCoverage,
58562
+ settlementMode: res.settlement_mode ?? "legacy",
58563
+ folded: /* @__PURE__ */ new Map(),
58564
+ framed: [],
58565
+ seen: /* @__PURE__ */ new Set(),
58566
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
58308
58567
  };
58568
+ for (const ev of res.events ?? []) {
58569
+ lane.folded.set(ev.source_id, ev.id);
58570
+ }
58571
+ this.recordFrame(lane, res.frame, (res.events ?? []).map((ev) => ev.source_id));
58572
+ this.recordWake(lane, res);
58573
+ this.lanes.set(laneKey, lane);
58309
58574
  }
58310
- initialized = true;
58311
- console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] exporting ${serviceName} v${serviceVersion} env=${environment} to ${otelEndpoint}${spoolDir ? ` spool=${spoolDir}` : ""}`);
58312
- shutdownFn = async () => {
58575
+ for (const ev of events) {
58576
+ if (lane.folded.has(ev.messageId))
58577
+ continue;
58313
58578
  try {
58314
- await tracerProvider.forceFlush();
58315
- await meterProvider.forceFlush();
58316
- await loggerProvider.forceFlush();
58317
- await tracerProvider.shutdown();
58318
- await meterProvider.shutdown();
58319
- await loggerProvider.shutdown();
58320
- } finally {
58321
- await spool?.close();
58579
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
58580
+ lane: lane.lane,
58581
+ target_uri: lane.targetUri,
58582
+ thread_root_id: lane.threadRootId,
58583
+ ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: ev.ackSourceType ?? "message", source_id: ev.messageId }
58584
+ });
58585
+ lane.folded.set(ev.messageId, res.dispatch_event_id);
58586
+ this.recordFrame(lane, res.frame, [ev.messageId]);
58587
+ } catch (err) {
58588
+ if (isStaleLane(err)) {
58589
+ this.lanes.delete(laneKey);
58590
+ this.removeLaneContext(lane);
58591
+ if (reused && !reclaimed) {
58592
+ this.opts.log?.info(`cached lane for ${lane.targetUri} is stale \u2014 re-claiming to arbitrate ownership`);
58593
+ return this.ensureLaneAttempt(events, true);
58594
+ }
58595
+ return null;
58596
+ }
58597
+ this.opts.log?.warn(`steer fold failed for ${ev.messageId}; preserving prior members: ${String(err)}`);
58598
+ continue;
58322
58599
  }
58323
- };
58324
- return {
58325
- shutdown: async () => {
58326
- if (shutdownFn)
58327
- await shutdownFn();
58600
+ }
58601
+ return lane;
58602
+ }
58603
+ /**
58604
+ * Fold a live mid-turn message into its active lane BEFORE injecting it
58605
+ * into the running turn. Injection without a successful fold is forbidden —
58606
+ * an un-folded injected message would be re-driven after complete and the
58607
+ * model would handle it twice.
58608
+ */
58609
+ async steerLive(event) {
58610
+ const laneKey = this.laneKeyFor(event);
58611
+ const lane = this.lanes.get(laneKey);
58612
+ if (!lane || lane.settling)
58613
+ return null;
58614
+ if (lane.seen.has(event.messageId))
58615
+ return null;
58616
+ if (lane.folded.has(event.messageId)) {
58617
+ return {
58618
+ inputLifecycle: this.inputLifecycleFor(lane, [event.messageId]),
58619
+ covered: [event.messageId]
58620
+ };
58621
+ }
58622
+ try {
58623
+ const res = await this.opts.client.steerDispatch(this.opts.orgId, {
58624
+ lane: lane.lane,
58625
+ target_uri: lane.targetUri,
58626
+ thread_root_id: lane.threadRootId,
58627
+ ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: event.ackSourceType ?? "message", source_id: event.messageId }
58628
+ });
58629
+ lane.folded.set(event.messageId, res.dispatch_event_id);
58630
+ const covered = [event.messageId];
58631
+ return {
58632
+ inputLifecycle: this.inputLifecycleFor(lane, covered),
58633
+ frame: res.frame,
58634
+ covered
58635
+ };
58636
+ } catch (err) {
58637
+ if (isStaleLane(err)) {
58638
+ this.lanes.delete(laneKey);
58639
+ this.removeLaneContext(lane);
58640
+ } else {
58641
+ this.opts.log?.warn(`live steer failed for ${event.messageId}: ${String(err)}`);
58328
58642
  }
58643
+ return null;
58644
+ }
58645
+ }
58646
+ /**
58647
+ * Build the exact runtime-input lifecycle for one prompt/injection. A
58648
+ * batched prompt covers every WorkItem represented in that single frame.
58649
+ */
58650
+ inputLifecycle(lane, events) {
58651
+ return this.inputLifecycleFor(lane, events.map((event) => event.messageId));
58652
+ }
58653
+ /**
58654
+ * Exact lifecycle over a set of folded members by message id — the set a
58655
+ * prompt or injection actually delivers (frame coverage ∪ buffered group).
58656
+ */
58657
+ inputLifecycleFor(lane, messageIds) {
58658
+ return this.inputs.lifecycle(lane, messageIds);
58659
+ }
58660
+ /** Carry the runtime error into the lane's forced completion. */
58661
+ markTurnError(laneKey, info = {}) {
58662
+ const lane = this.lanes.get(laneKey);
58663
+ if (lane)
58664
+ lane.turnError = info;
58665
+ }
58666
+ /**
58667
+ * Record that the turn on this lane ended on a self-healing usage limit.
58668
+ * Like markTurnError this is transport state for the lane's final
58669
+ * complete; an error bit set on the same lane outranks it.
58670
+ */
58671
+ markTurnDeferred(laneKey, info) {
58672
+ const lane = this.lanes.get(laneKey);
58673
+ if (lane)
58674
+ lane.turnDeferred = info;
58675
+ }
58676
+ /**
58677
+ * Sticky: the server rejected turn_outcome=deferred (predates it). Deferred
58678
+ * completes fall back to the error form for the rest of the process — the
58679
+ * members still release for retry, just on the redrive budget instead of
58680
+ * the reset-time schedule.
58681
+ */
58682
+ deferredUnsupported = false;
58683
+ async completeIfIdle(laneKey, hasMoreLocal) {
58684
+ const lane = this.lanes.get(laneKey);
58685
+ if (!lane || hasMoreLocal)
58686
+ return;
58687
+ if (lane.settling)
58688
+ return;
58689
+ lane.settling = true;
58690
+ const deferred = !lane.turnError && !this.deferredUnsupported ? lane.turnDeferred : void 0;
58691
+ const outcome = lane.turnError ? "error" : lane.turnDeferred ? this.deferredUnsupported ? "error" : "deferred" : "ok";
58692
+ const request3 = {
58693
+ lane: lane.lane,
58694
+ target_uri: lane.targetUri,
58695
+ thread_root_id: lane.threadRootId,
58696
+ // An error turn releases its members for retry; a deferred turn
58697
+ // re-delivers them at retry_at without burning redrive budget
58698
+ // (ignored by older servers, which 400 on the unknown enum — see the
58699
+ // fallback below).
58700
+ turn_outcome: outcome,
58701
+ ...deferred ? {
58702
+ outcome_class: deferred.outcomeClass,
58703
+ ...deferred.retryAt ? { retry_at: deferred.retryAt } : {}
58704
+ } : {},
58705
+ // An error complete carries the bridge's classification and redacted
58706
+ // evidence so the server can persist WHY on the released row
58707
+ // (agent-health-alerting-design.md §4.5). usage_limit never travels
58708
+ // with error: it is the deferred contract, and a server that rejected
58709
+ // deferred (deferredUnsupported) also predates the class field.
58710
+ ...outcome === "error" && lane.turnError ? {
58711
+ ...errorWireClass(lane.turnError.outcomeClass) ? { outcome_class: errorWireClass(lane.turnError.outcomeClass) } : {},
58712
+ ...lane.turnError.detail ? { detail: lane.turnError.detail.slice(0, 500) } : {}
58713
+ } : {},
58714
+ session_id: lane.sessionAmbiguous ? void 0 : lane.sessionId
58329
58715
  };
58330
- } catch (err) {
58331
- console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [telemetry] init failed for ${serviceName}, running without export: ${String(err)}`);
58332
- return noopHandle;
58716
+ let fallback = false;
58717
+ await this.confirmations.submit(lane.lane, {
58718
+ label: "complete",
58719
+ send: async () => {
58720
+ try {
58721
+ await this.opts.client.completeDispatch(this.opts.orgId, fallback ? {
58722
+ lane: request3.lane,
58723
+ target_uri: request3.target_uri,
58724
+ thread_root_id: request3.thread_root_id,
58725
+ turn_outcome: "error"
58726
+ } : request3);
58727
+ } catch (err) {
58728
+ if (!fallback && outcome === "deferred" && err instanceof ApiError && err.status === 400) {
58729
+ this.deferredUnsupported = true;
58730
+ fallback = true;
58731
+ await this.opts.client.completeDispatch(this.opts.orgId, {
58732
+ lane: request3.lane,
58733
+ target_uri: request3.target_uri,
58734
+ thread_root_id: request3.thread_root_id,
58735
+ turn_outcome: "error"
58736
+ });
58737
+ } else
58738
+ throw err;
58739
+ }
58740
+ this.forgetLane(lane);
58741
+ }
58742
+ });
58333
58743
  }
58334
- }
58335
- function dispatchEventAttributes(event, runtimeType, sessionKey) {
58336
- return {
58337
- "dispatch.target_type": resolveTargetType(event.targetId),
58338
- "dispatch.event_type": event.type,
58339
- "dispatch.runtime_type": runtimeType,
58340
- "dispatch.session_key": sessionKey,
58341
- "dispatch.message_id": event.messageId,
58342
- "dispatch.target_id": event.targetId,
58343
- ...event.dispatchEventId ? { "dispatch.event_id": event.dispatchEventId } : {}
58344
- };
58345
- }
58346
- function startDispatchSpan(event, runtimeType, sessionKey) {
58347
- const span = tracer().startSpan("parall.dispatch", {
58348
- root: true,
58349
- attributes: dispatchEventAttributes(event, runtimeType, sessionKey)
58350
- });
58351
- dispatchSpans.add(span);
58352
- return span;
58353
- }
58354
- function startTypedDispatchSpan(dispatchEventId, runtimeType) {
58355
- const span = tracer().startSpan("parall.dispatch", {
58356
- root: true,
58357
- attributes: {
58358
- "dispatch.runtime_type": runtimeType,
58359
- ...dispatchEventId ? { "dispatch.event_id": dispatchEventId } : {}
58360
- }
58361
- });
58362
- dispatchSpans.add(span);
58363
- return span;
58364
- }
58365
- function annotateDispatchSpan(span, metricsSnapshot, error, turnOutcome) {
58366
- if (!span)
58367
- return;
58368
- if (metricsSnapshot) {
58369
- span.setAttributes({
58370
- "dispatch.deliver_text_chunks": metricsSnapshot.deliver_text_chunks,
58371
- "dispatch.deliver_text_chars": metricsSnapshot.deliver_text_chars,
58372
- "dispatch.message_send_attempts": metricsSnapshot.message_send_attempts,
58373
- "dispatch.message_send_successes": metricsSnapshot.message_send_successes,
58374
- "dispatch.no_reply_called": metricsSnapshot.no_reply_called,
58375
- "dispatch.tool_call_count": metricsSnapshot.tool_call_count,
58376
- "dispatch.duration_ms": Date.now() - metricsSnapshot.started_at
58744
+ /**
58745
+ * Renew one lane by its key — the external runtime-activity hook for
58746
+ * adapters whose tool traffic bypasses the RuntimeEvent stream (openclaw
58747
+ * hooks). Scoped to the session's own lane: renewing every lane would let
58748
+ * one busy fork keep an unrelated stalled fork's lane leased forever.
58749
+ */
58750
+ renewByKey(laneKey) {
58751
+ const lane = this.lanes.get(laneKey);
58752
+ if (lane)
58753
+ this.maybeRenew(lane);
58754
+ }
58755
+ /**
58756
+ * Long-turn keepalive: renew the lane's lease on runtime activity, throttled
58757
+ * so a chatty turn doesn't spam the server. Without this, a legitimately
58758
+ * long turn (> lane TTL) would be dethroned mid-flight and every subsequent
58759
+ * write misfired with STALE_LANE — the design doc's "long turns renew via
58760
+ * step writes". Fire-and-forget: a failed renewal is surfaced by the next
58761
+ * write's incumbency check anyway.
58762
+ */
58763
+ maybeRenew(lane) {
58764
+ if (isTurnToken(lane.lane))
58765
+ return;
58766
+ const now = Date.now();
58767
+ const ttl = lane.leaseTtlMs ?? 10 * 6e4;
58768
+ const until = lane.leaseUntilMs ?? now;
58769
+ if (until - now > ttl / 2)
58770
+ return;
58771
+ lane.leaseUntilMs = now + ttl;
58772
+ void this.opts.client.heartbeatDispatchLane(this.opts.orgId, {
58773
+ lane: lane.lane,
58774
+ target_uri: lane.targetUri,
58775
+ thread_root_id: lane.threadRootId
58776
+ }).then((res) => {
58777
+ const until2 = Date.parse(res?.lease_until ?? "");
58778
+ if (!Number.isNaN(until2))
58779
+ lane.leaseUntilMs = until2;
58780
+ }).catch((err) => {
58781
+ if (isStaleLane(err)) {
58782
+ this.lanes.delete(lane.laneKey);
58783
+ this.opts.log?.warn(`lane ${lane.targetUri} was taken over during the turn`);
58784
+ return;
58785
+ }
58786
+ this.opts.log?.warn(`lane heartbeat failed for ${lane.targetUri}: ${String(err)}`);
58377
58787
  });
58378
58788
  }
58379
- if (turnOutcome) {
58380
- span.setAttribute("dispatch.outcome", turnOutcome.outcome);
58381
- if (turnOutcome.detail)
58382
- span.setAttribute("dispatch.outcome_detail", turnOutcome.detail);
58383
- if (turnOutcome.retryAt)
58384
- span.setAttribute("dispatch.retry_at", turnOutcome.retryAt);
58385
- if (turnOutcome.model)
58386
- span.setAttribute("dispatch.model", turnOutcome.model);
58387
- if (turnOutcome.raw && Object.keys(turnOutcome.raw).length > 0) {
58388
- try {
58389
- span.setAttribute("dispatch.outcome_raw", JSON.stringify(turnOutcome.raw));
58390
- } catch {
58789
+ /**
58790
+ * Release a lane's unresolved members back to pending (dispatch error /
58791
+ * shutdown) so the next pod re-claims immediately instead of waiting out
58792
+ * the lease.
58793
+ */
58794
+ async release(laneKey, reason = "unspecified", info) {
58795
+ const lane = this.lanes.get(laneKey);
58796
+ if (!lane || lane.settling)
58797
+ return;
58798
+ lane.settling = true;
58799
+ const wireClass = errorWireClass(info?.outcomeClass);
58800
+ const outcome = info && (wireClass || info.detail) ? {
58801
+ ...wireClass ? { outcome_class: wireClass } : {},
58802
+ ...info.detail ? { detail: redactSecrets(info.detail, this.opts.knownSecrets).slice(0, 500) } : {}
58803
+ } : void 0;
58804
+ await this.confirmations.submit(lane.lane, {
58805
+ label: "release",
58806
+ send: async () => {
58807
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane, reason, outcome);
58808
+ this.forgetLane(lane);
58391
58809
  }
58810
+ });
58811
+ }
58812
+ async releaseAll(reason = "shutdown") {
58813
+ await this.confirmations.retryNow();
58814
+ const keys = [...this.lanes.keys()];
58815
+ for (const key of keys) {
58816
+ await this.release(key, reason);
58392
58817
  }
58393
- const u = turnOutcome.usage;
58394
- if (u) {
58395
- if (u.inputTokens !== void 0)
58396
- span.setAttribute("dispatch.tokens_input", u.inputTokens);
58397
- if (u.outputTokens !== void 0)
58398
- span.setAttribute("dispatch.tokens_output", u.outputTokens);
58399
- if (u.cacheReadTokens !== void 0)
58400
- span.setAttribute("dispatch.tokens_cache_read", u.cacheReadTokens);
58401
- if (u.cacheCreationTokens !== void 0)
58402
- span.setAttribute("dispatch.tokens_cache_creation", u.cacheCreationTokens);
58403
- if (u.costUsd !== void 0)
58404
- span.setAttribute("dispatch.cost_usd", u.costUsd);
58405
- if (u.durationApiMs !== void 0)
58406
- span.setAttribute("dispatch.duration_api_ms", u.durationApiMs);
58818
+ for (const [key, claim] of this.claimResponses) {
58819
+ if (!claim.response?.lane)
58820
+ continue;
58821
+ const token = claim.response.lane;
58822
+ await this.confirmations.submit(token, {
58823
+ label: "unconsumed claim release",
58824
+ send: async () => {
58825
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, token, reason);
58826
+ this.claimResponses.delete(key);
58827
+ }
58828
+ });
58407
58829
  }
58408
58830
  }
58409
- if (error)
58410
- recordDispatchError(span, error);
58411
- }
58412
- function recordDispatchError(span, error) {
58413
- if (typeof error === "object" && error !== null) {
58414
- if (recordedErrors.has(error))
58415
- return;
58416
- recordedErrors.add(error);
58831
+ /** True when any lane is currently active (used by shutdown logging). */
58832
+ get activeCount() {
58833
+ return this.lanes.size;
58417
58834
  }
58418
- const safe = redactSecrets(String(error));
58419
- span.setStatus({ code: SpanStatusCode.ERROR, message: safe });
58420
- span.recordException(new Error(safe));
58421
- }
58422
- function recordDispatchMetric(event, runtimeType, durationMs, outcome = "ok") {
58423
- if (!initialized)
58424
- return;
58425
- const attrs = {
58426
- target_type: resolveTargetType(event.targetId),
58427
- event_type: event.type,
58428
- runtime_type: runtimeType,
58429
- outcome
58430
- };
58431
- dispatchCounter?.add(1, attrs);
58432
- dispatchDuration?.record(durationMs, attrs);
58433
- }
58434
- function recordMissingReply(runtimeType, outcome = "ok") {
58435
- if (!initialized)
58436
- return;
58437
- missingReplyCounter?.add(1, { runtime_type: runtimeType, outcome });
58438
- }
58439
- function recordTurnUsage(usage, runtimeType) {
58440
- if (!initialized || !usage)
58441
- return;
58442
- const kinds = [
58443
- ["input", usage.inputTokens],
58444
- ["output", usage.outputTokens],
58445
- ["cache_read", usage.cacheReadTokens],
58446
- ["cache_creation", usage.cacheCreationTokens]
58447
- ];
58448
- for (const [kind, value] of kinds) {
58449
- if (value !== void 0 && value > 0) {
58450
- turnTokensCounter?.add(value, { kind, runtime_type: runtimeType });
58835
+ /**
58836
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>)
58837
+ * by WorkItem id. The server renders the wake frame on claim (or resolves
58838
+ * the item as stale and answers `claimed: false, reason: "stale"`).
58839
+ * Returns null when a healthy incumbent (another pod) holds it, the
58840
+ * WorkItem is already resolved, or the server found nothing to wake for
58841
+ * — the caller must skip processing.
58842
+ */
58843
+ async claimTyped(ref) {
58844
+ const key = `typed:${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`}`;
58845
+ if (this.claims.has(key))
58846
+ return null;
58847
+ if (ref.dispatchEventId && this.lanes.has(laneKeyForTarget(`dsp:${ref.dispatchEventId}`)))
58848
+ return null;
58849
+ const claim = this.claimTypedAttempt(ref);
58850
+ this.claims.set(key, claim);
58851
+ try {
58852
+ return await claim;
58853
+ } finally {
58854
+ this.claims.delete(key);
58451
58855
  }
58452
58856
  }
58453
- if (usage.costUsd !== void 0 && usage.costUsd > 0) {
58454
- turnCostCounter?.add(usage.costUsd, { runtime_type: runtimeType });
58455
- }
58456
- }
58457
- var dispatchContextStorage = new AsyncLocalStorage();
58458
- function runWithDispatchContext(ctx, fn) {
58459
- return dispatchContextStorage.run({ ...ctx }, fn);
58460
- }
58461
- function patchDispatchContext(patch) {
58462
- const store = dispatchContextStorage.getStore();
58463
- if (store)
58464
- Object.assign(store, patch);
58465
- }
58466
- function dispatchLogAttributes() {
58467
- const store = dispatchContextStorage.getStore();
58468
- if (!store)
58469
- return {};
58470
- const attrs = {};
58471
- const set = (key, value) => {
58472
- if (value)
58473
- attrs[key] = value;
58474
- };
58475
- set("session.key", store.sessionKey);
58476
- set("dispatch.event_id", store.dispatchEventId);
58477
- set("dispatch.lane", store.lane);
58478
- set("dispatch.target_uri", store.targetUri);
58479
- set("dispatch.message_id", store.messageId);
58480
- set("dispatch.thread_root_id", store.threadRootId);
58481
- set("dispatch.event_type", store.eventType);
58482
- return attrs;
58483
- }
58484
- function withActiveSpan(span, fn) {
58485
- if (!span)
58486
- return fn();
58487
- return context.with(trace.setSpan(context.active(), span), fn);
58488
- }
58489
- function runInDispatchScope(span, ctx, fn) {
58490
- return withActiveSpan(span, () => runWithDispatchContext(ctx, fn));
58491
- }
58492
- function dispatchLogContext(event, sessionKey) {
58493
- return {
58494
- sessionKey,
58495
- messageId: event.messageId,
58496
- eventType: event.type,
58497
- dispatchEventId: event.dispatchEventId ?? null,
58498
- threadRootId: event.threadRootId ?? null
58499
- };
58500
- }
58501
- async function runInDispatchTrace(id, fn) {
58502
- const active = trace.getActiveSpan();
58503
- if (active && dispatchSpans.has(active)) {
58504
- if (id.event && id.sessionKey) {
58505
- active.setAttributes(dispatchEventAttributes(id.event, id.runtimeType, id.sessionKey));
58506
- patchDispatchContext(dispatchLogContext(id.event, id.sessionKey));
58857
+ async claimRecoverably(key, request3) {
58858
+ let claim = this.claimResponses.get(key);
58859
+ if (!claim) {
58860
+ claim = { request: request3 };
58861
+ this.claimResponses.set(key, claim);
58862
+ const captured = claim;
58863
+ await this.confirmations.submit(`claim:${key}`, {
58864
+ label: "claim",
58865
+ send: async () => {
58866
+ try {
58867
+ captured.response = await this.opts.client.claimDispatch(this.opts.orgId, request3);
58868
+ } catch (err) {
58869
+ if (isEndpointMissing2(err))
58870
+ captured.unsupported = true;
58871
+ else
58872
+ throw err;
58873
+ }
58874
+ }
58875
+ });
58507
58876
  }
58508
- return fn(active);
58509
- }
58510
- const span = id.event && id.sessionKey ? startDispatchSpan(id.event, id.runtimeType, id.sessionKey) : startTypedDispatchSpan(id.dispatchEventId, id.runtimeType);
58511
- const ctx = id.event && id.sessionKey ? dispatchLogContext(id.event, id.sessionKey) : { sessionKey: "", dispatchEventId: id.dispatchEventId ?? null };
58512
- return runInDispatchScope(span, ctx, async () => {
58513
- try {
58514
- return await fn(span);
58515
- } catch (err) {
58516
- recordDispatchError(span, err);
58517
- throw err;
58518
- } finally {
58519
- span.end();
58877
+ if (claim.unsupported) {
58878
+ this.claimResponses.delete(key);
58879
+ throw new LedgerUnsupportedError("claim endpoint unavailable");
58520
58880
  }
58521
- });
58522
- }
58523
- async function runInPhaseSpan(phase, fn) {
58524
- if (!trace.getActiveSpan())
58525
- return fn();
58526
- return tracer().startActiveSpan(`parall.dispatch.${phase}`, async (span) => {
58527
- try {
58528
- return await fn();
58529
- } catch (err) {
58530
- span.setStatus({ code: SpanStatusCode.ERROR, message: redactSecrets(String(err)) });
58531
- throw err;
58532
- } finally {
58533
- span.end();
58881
+ if (!claim.response)
58882
+ return null;
58883
+ this.claimResponses.delete(key);
58884
+ return claim.response;
58885
+ }
58886
+ async claimTypedAttempt(ref) {
58887
+ const res = await this.claimRecoverably(`typed:${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`}`, {
58888
+ dispatch_event_id: ref.dispatchEventId,
58889
+ source_type: ref.dispatchEventId ? void 0 : ref.sourceType,
58890
+ source_id: ref.dispatchEventId ? void 0 : ref.sourceId,
58891
+ instance_id: this.opts.instanceId
58892
+ });
58893
+ if (!res)
58894
+ return null;
58895
+ if (!res.claimed || !res.lane || !res.events?.length) {
58896
+ if (res.reason === "stale") {
58897
+ this.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} resolved by the server as stale (${res.stale_reason ?? "unspecified"})`);
58898
+ } else if (res.claimed && res.lane) {
58899
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, res.lane).catch(() => {
58900
+ });
58901
+ }
58902
+ return null;
58534
58903
  }
58535
- });
58536
- }
58537
- function runOutsideDispatchScope(fn) {
58538
- return context.with(ROOT_CONTEXT, () => dispatchContextStorage.exit(fn));
58539
- }
58540
- function traceContextHeaders() {
58541
- const carrier = {};
58542
- propagation.inject(context.active(), carrier);
58543
- return Object.keys(carrier).length > 0 ? carrier : void 0;
58544
- }
58545
- function createOtelLogger(layer, prefix) {
58546
- const ts = () => (/* @__PURE__ */ new Date()).toISOString();
58547
- const emit = (severity, msg) => {
58548
- if (!otelLogger)
58549
- return;
58550
- const severityNumber = severity === "ERROR" ? import_api_logs.SeverityNumber.ERROR : severity === "WARN" ? import_api_logs.SeverityNumber.WARN : import_api_logs.SeverityNumber.INFO;
58551
- const attrs = {
58552
- "log.layer": layer,
58553
- "log.prefix": prefix,
58554
- ...dispatchLogAttributes()
58904
+ const workItem = res.events[0];
58905
+ const targetUri = `dsp:${workItem.id}`;
58906
+ if (this.lanes.has(laneKeyForTarget(targetUri)))
58907
+ return null;
58908
+ const leaseUntilMs = Date.parse(res.lease_until ?? "");
58909
+ const lane = {
58910
+ laneKey: laneKeyForTarget(targetUri),
58911
+ lane: res.lane,
58912
+ targetUri,
58913
+ coverageMode: "implicit",
58914
+ folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
58915
+ framed: [],
58916
+ seen: /* @__PURE__ */ new Set(),
58917
+ typedDispatchEventId: workItem.id,
58918
+ ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
58555
58919
  };
58556
- otelLogger.emit({
58557
- severityNumber,
58558
- severityText: severity,
58559
- body: msg,
58560
- attributes: attrs
58920
+ this.recordFrame(lane, res.frame, [workItem.source_id]);
58921
+ this.recordWake(lane, res);
58922
+ this.lanes.set(lane.laneKey, lane);
58923
+ return lane;
58924
+ }
58925
+ /**
58926
+ * Drop a lane's local record without any server call — for a typed lane
58927
+ * whose member the by-id complete just resolved (the server dropped the
58928
+ * vacated lane row in the same transaction). Calling completeIfIdle
58929
+ * instead would fire a lane-form Complete at a lane that no longer exists
58930
+ * and burn an RPC on the guaranteed STALE_LANE answer.
58931
+ */
58932
+ dropLocal(laneKey) {
58933
+ const lane = this.lanes.get(laneKey);
58934
+ if (!lane)
58935
+ return;
58936
+ this.confirmations.forget(lane.lane);
58937
+ this.forgetLane(lane);
58938
+ }
58939
+ syncInputAttribution(lane) {
58940
+ return this.inputs.syncAttribution(lane);
58941
+ }
58942
+ async confirmTyped(lane, send) {
58943
+ if (lane.settling)
58944
+ return;
58945
+ lane.settling = true;
58946
+ await this.confirmations.submit(lane.lane, {
58947
+ label: "typed complete",
58948
+ send: async () => {
58949
+ await send();
58950
+ this.forgetLane(lane);
58951
+ }
58561
58952
  });
58562
- };
58563
- return {
58564
- info: (msg) => {
58565
- console.log(`${ts()} [${prefix}] ${msg}`);
58566
- emit("INFO", msg);
58567
- },
58568
- warn: (msg) => {
58569
- console.warn(`${ts()} [${prefix}] ${msg}`);
58570
- emit("WARN", msg);
58571
- },
58572
- error: (msg) => {
58573
- console.error(`${ts()} [${prefix}] ${msg}`);
58574
- emit("ERROR", msg);
58575
- },
58576
- child: (sub) => createOtelLogger(layer, `${prefix}:${sub}`)
58577
- };
58578
- }
58953
+ }
58954
+ retryConfirmations() {
58955
+ return this.confirmations.retryNow();
58956
+ }
58957
+ dispose() {
58958
+ this.confirmations.dispose();
58959
+ }
58960
+ forgetLane(lane) {
58961
+ if (this.lanes.get(lane.laneKey) !== lane)
58962
+ return;
58963
+ this.lanes.delete(lane.laneKey);
58964
+ this.removeLaneContext(lane);
58965
+ }
58966
+ /**
58967
+ * Remove the per-lane context file (and its CLI sidecar) when the lane
58968
+ * ends. A leftover file would make a later cross-context send to the same
58969
+ * target bind a dead lane token and misfire with STALE_LANE instead of
58970
+ * taking the plain non-ledger path.
58971
+ */
58972
+ removeLaneContext(lane) {
58973
+ const contextPath = this.laneContextPath(lane);
58974
+ for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
58975
+ try {
58976
+ fs3.rmSync(p, { force: true });
58977
+ } catch {
58978
+ }
58979
+ }
58980
+ }
58981
+ };
58579
58982
 
58580
58983
  // ts/agent-core/dist/gateway-lane-flow.js
58581
58984
  function shiftMainBufferGroup(host, groupKey, preserveInjectedFrameBoundary) {
@@ -58598,36 +59001,6 @@ function applyWake(event, wake) {
58598
59001
  if (wake.attachments?.length)
58599
59002
  event.attachments = wake.attachments;
58600
59003
  }
58601
- function hasUninjectedSameLaneEventAhead(host, event) {
58602
- const eventIndex = host.dispatchState.mainBuffer.lastIndexOf(event);
58603
- if (eventIndex <= 0)
58604
- return false;
58605
- const groupKey = host.dispatchGroupKey(event);
58606
- return host.dispatchState.mainBuffer.slice(0, eventIndex).some((buffered) => host.dispatchGroupKey(buffered) === groupKey && !host.injectedMainBufferEvents.has(buffered));
58607
- }
58608
- async function steerLaneMessage(host, event) {
58609
- const { laneLedger: ledger, opts } = host;
58610
- const adapter = opts.dispatchAdapter;
58611
- if (!ledger || !adapter.enqueueDuringDispatch)
58612
- return;
58613
- if (hasUninjectedSameLaneEventAhead(host, event))
58614
- return;
58615
- const folded = await ledger.steerLive(event);
58616
- if (!folded)
58617
- return;
58618
- if (!folded.frame)
58619
- return;
58620
- event.frame = folded.frame;
58621
- const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, eventBody(event), folded.inputLifecycle);
58622
- if (injected) {
58623
- host.injectedMainBufferEvents.add(event);
58624
- ledger.markSeen(event, folded.covered);
58625
- opts.log?.info(`steer folded+injected for ${event.messageId} (will drain for bookkeeping)`);
58626
- } else if (folded.frame) {
58627
- ledger.deferFrame(event, folded.frame, folded.covered);
58628
- opts.log?.info(`steer folded but not injected for ${event.messageId} \u2014 frame deferred to the drain`);
58629
- }
58630
- }
58631
59004
  async function dispatchLaneGroup(host, opts) {
58632
59005
  const event = opts.events[opts.events.length - 1];
58633
59006
  return runInDispatchTrace({
@@ -58679,39 +59052,30 @@ async function dispatchLaneGroupInner(host, opts) {
58679
59052
  const pending = ledger.takeFrame(lane);
58680
59053
  const frame = pending.frame;
58681
59054
  if (!frame && opts.events.every((ev) => lane.seen.has(ev.messageId))) {
58682
- host.opts.log?.info(`lane group for ${event.messageId} already rendered by the server frame \u2014 no turn`);
59055
+ const live = liveSteerMembers(host, opts.sessionKey, lane, opts.events);
59056
+ if (live.length > 0) {
59057
+ const settled2 = await attachLiveSteers(host, opts, lane, live);
59058
+ if (settled2)
59059
+ return settled2;
59060
+ } else {
59061
+ host.opts.log?.info(`lane group for ${event.messageId} already rendered by the server frame \u2014 no turn`);
59062
+ }
58683
59063
  const acknowledge = host.opts.dispatchAdapter.acknowledgeDiscardedInjection?.bind(host.opts.dispatchAdapter);
58684
- const withdrawn = [];
58685
59064
  if (acknowledge) {
58686
59065
  try {
58687
59066
  for (const ev of opts.events) {
58688
59067
  const deliveryKey = lane.folded.get(ev.messageId);
58689
- if (!deliveryKey)
58690
- continue;
58691
- if (await acknowledge(opts.sessionKey, deliveryKey) === "cancelled")
58692
- withdrawn.push(ev);
59068
+ if (deliveryKey)
59069
+ await acknowledge(opts.sessionKey, deliveryKey);
58693
59070
  }
58694
59071
  } catch (err) {
58695
59072
  host.opts.log?.warn(`discarded input acknowledgement failed for ${event.messageId}: ${String(err)}`);
58696
59073
  }
58697
59074
  }
58698
- if (withdrawn.length > 0 && !opts.withdrawnRetry) {
58699
- for (const ev of withdrawn)
58700
- host.dispatchedMessages.delete(ev.messageId);
58701
- await ledger.completeIfIdle(lane.laneKey, unsettledInjections(host, opts.sessionKey));
58702
- if (ledger.getForEvent(event))
58703
- return "no_turn";
58704
- return dispatchLaneGroupInner(host, {
58705
- ...opts,
58706
- events: withdrawn,
58707
- earlier: withdrawn.slice(0, -1),
58708
- withdrawnRetry: true
58709
- });
58710
- }
58711
59075
  for (const ev of opts.events)
58712
59076
  host.dispatchedMessages.delete(ev.messageId);
58713
59077
  await runInPhaseSpan("settle", () => ledger.completeIfIdle(lane.laneKey, unsettledInjections(host, opts.sessionKey) || opts.hasMoreLocal()));
58714
- return "no_turn";
59078
+ return live.length > 0 ? "dispatched" : "no_turn";
58715
59079
  }
58716
59080
  if (!frame) {
58717
59081
  host.opts.log?.warn(`lane group for ${event.messageId} claimed without a frame \u2014 releasing the members instead of running`);
@@ -58733,6 +59097,9 @@ async function dispatchLaneGroupInner(host, opts) {
58733
59097
  ]);
58734
59098
  dispatched = await host.runDispatch(event, opts.sessionKey, opts.bodyPrefix + eventBody(event), opts.earlier, opts.captureText, inputLifecycle);
58735
59099
  } catch (err) {
59100
+ while (opts.sessionKey === host.opts.runtimeKey && hasMainSteers(host.dispatchState)) {
59101
+ await waitForMainSteers(host.dispatchState);
59102
+ }
58736
59103
  host.noteSessionLane(opts.sessionKey, null);
58737
59104
  await runInPhaseSpan("settle", () => ledger.release(lane.laneKey, "runtime_error", releaseErrorInfo(err, [host.opts.config.api_key])).catch(() => {
58738
59105
  }));
@@ -58744,29 +59111,12 @@ async function dispatchLaneGroupInner(host, opts) {
58744
59111
  if (!dispatched) {
58745
59112
  return "shutdown";
58746
59113
  }
58747
- const settled = host.consumeTurnOutcome(opts.sessionKey);
58748
- if (settled) {
58749
- if (settled.kind === "deferred") {
58750
- ledger.markTurnDeferred(lane.laneKey, {
58751
- outcomeClass: settled.outcomeClass,
58752
- ...settled.retryAt ? { retryAt: settled.retryAt } : {}
58753
- });
58754
- } else {
58755
- ledger.markTurnError(lane.laneKey, {
58756
- ...settled.outcomeClass ? { outcomeClass: settled.outcomeClass } : {},
58757
- ...settled.detail ? { detail: settled.detail } : {}
58758
- });
58759
- }
58760
- for (const msgId of lane.folded.keys()) {
58761
- host.dispatchedMessages.delete(msgId);
58762
- }
58763
- try {
58764
- host.opts.dispatchAdapter.abortDispatch?.(opts.sessionKey);
58765
- } catch {
58766
- }
58767
- await runInPhaseSpan("settle", () => ledger.completeIfIdle(lane.laneKey, false));
58768
- return settled.kind === "deferred" ? "deferred" : "failed";
59114
+ while (opts.sessionKey === host.opts.runtimeKey && hasMainSteers(host.dispatchState)) {
59115
+ await waitForMainSteers(host.dispatchState);
58769
59116
  }
59117
+ const settled = await settleNonCleanTurn(host, opts.sessionKey, lane);
59118
+ if (settled)
59119
+ return settled;
58770
59120
  await runInPhaseSpan("settle", () => ledger.completeIfIdle(lane.laneKey, unsettledInjections(host, opts.sessionKey) || opts.hasMoreLocal()));
58771
59121
  return "dispatched";
58772
59122
  }
@@ -59087,6 +59437,19 @@ async function handleCompactSignal(host, data) {
59087
59437
  // ts/agent-core/dist/gateway-runtime-turns.js
59088
59438
  var UNTARGETED_STEP = { target_type: "" };
59089
59439
  function handleRuntimeActivity(host, event) {
59440
+ if (event.kind === "observation") {
59441
+ const binding = host.sessionBindings.get(event.sessionKey);
59442
+ if (!binding || binding.runtimeSessionId !== event.event.runtimeSessionId) {
59443
+ host.opts.log?.warn(`runtime observation has no matching session binding on ${event.sessionKey}`);
59444
+ return;
59445
+ }
59446
+ host.inFlightRuntimeTurns += 1;
59447
+ void persistRuntimeObservation(host.stepPersister, binding.agentSessionId, UNTARGETED_STEP, event.event, host.opts.log, [host.opts.config.api_key]).finally(() => {
59448
+ host.inFlightRuntimeTurns -= 1;
59449
+ host.notifyDrainWaiters();
59450
+ });
59451
+ return;
59452
+ }
59090
59453
  const sessionKey = event.kind === "turn" ? event.turn.sessionKey : event.sessionKey;
59091
59454
  const label = event.kind === "turn" ? `runtime-initiated turn ${event.turn.groupKey} on ${sessionKey}` : `runtime child session close for ${sessionKey}`;
59092
59455
  const prior = host.runtimeActivityChains.get(sessionKey) ?? Promise.resolve();
@@ -59129,7 +59492,8 @@ async function runRuntimeTurn(host, turn) {
59129
59492
  };
59130
59493
  try {
59131
59494
  for await (const runtimeEvent of turn.events) {
59132
- deadline.touch();
59495
+ if (runtimeEvent.type !== "observation")
59496
+ deadline.touch();
59133
59497
  if (runtimeEvent.type === "runtime_session") {
59134
59498
  try {
59135
59499
  binding = await host.bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath);
@@ -59139,7 +59503,7 @@ async function runRuntimeTurn(host, turn) {
59139
59503
  }
59140
59504
  continue;
59141
59505
  }
59142
- if (!binding) {
59506
+ if (!binding || runtimeEvent.type === "observation" && binding.runtimeSessionId !== runtimeEvent.runtimeSessionId) {
59143
59507
  droppedWithoutBinding += 1;
59144
59508
  continue;
59145
59509
  }
@@ -59154,7 +59518,8 @@ async function runRuntimeTurn(host, turn) {
59154
59518
  await host.createRuntimeStep(binding.agentSessionId, UNTARGETED_STEP, { type: "error", message: failure.stepMessage, groupKey }, void 0, contextFilePath);
59155
59519
  continue;
59156
59520
  }
59157
- await ensureBegun();
59521
+ if (runtimeEvent.type !== "observation")
59522
+ await ensureBegun();
59158
59523
  stepCount += 1;
59159
59524
  await host.createRuntimeStep(binding.agentSessionId, UNTARGETED_STEP, runtimeEvent, void 0, contextFilePath);
59160
59525
  }
@@ -60310,11 +60675,11 @@ function parseDispatchDeadlineMs(raw) {
60310
60675
  }
60311
60676
  function inputStepIdempotencyKey(event) {
60312
60677
  if (event.type === "message" || event.type === "channel_message") {
60313
- return event.messageId ? `input:${event.messageId}` : randomUUID2();
60678
+ return event.messageId ? `input:${event.messageId}` : randomUUID4();
60314
60679
  }
60315
60680
  if (event.dispatchEventId)
60316
60681
  return `input:${event.dispatchEventId}`;
60317
- return randomUUID2();
60682
+ return randomUUID4();
60318
60683
  }
60319
60684
  function resolveStepTarget(event) {
60320
60685
  if (event.input?.step_target) {
@@ -60821,100 +61186,7 @@ var ParallAgentGateway = class {
60821
61186
  });
60822
61187
  }
60823
61188
  async createRuntimeStep(sessionId, target, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2) {
60824
- switch (runtimeEvent.type) {
60825
- case "thinking":
60826
- await this.stepPersister.persist(sessionId, "thinking", {
60827
- step_type: "thinking",
60828
- target_type: target.target_type,
60829
- target_id: target.target_id,
60830
- idempotency_key: randomUUID2(),
60831
- content: { text: runtimeEvent.text },
60832
- group_key: runtimeEvent.groupKey
60833
- });
60834
- break;
60835
- case "text":
60836
- await this.stepPersister.persist(sessionId, "text", {
60837
- step_type: "text",
60838
- target_type: target.target_type,
60839
- target_id: target.target_id,
60840
- idempotency_key: randomUUID2(),
60841
- content: {
60842
- text: runtimeEvent.text,
60843
- suppressed: runtimeEvent.project !== true
60844
- },
60845
- projection: runtimeEvent.project === true,
60846
- group_key: runtimeEvent.groupKey
60847
- });
60848
- break;
60849
- case "tool_call": {
60850
- const step = await this.stepPersister.persist(sessionId, "tool_call", {
60851
- step_type: "tool_call",
60852
- target_type: target.target_type,
60853
- target_id: target.target_id,
60854
- // call_id is session-unique for bridge runtimes (server-enforced),
60855
- // so the bare form anchors the tool step pair across retries —
60856
- // unlike parel's turn-scoped `tc:{turnId}:{callId}` (see
60857
- // protocol-vectors/agent-steps.json).
60858
- idempotency_key: `tc:${runtimeEvent.callId}`,
60859
- content: {
60860
- call_id: runtimeEvent.callId,
60861
- tool_name: runtimeEvent.toolName,
60862
- tool_input: runtimeEvent.input,
60863
- status: "running",
60864
- started_at: runtimeEvent.startedAt ?? (/* @__PURE__ */ new Date()).toISOString()
60865
- },
60866
- group_key: runtimeEvent.groupKey,
60867
- runtime_key: runtimeEvent.callId
60868
- });
60869
- if (step) {
60870
- if (contextFilePath) {
60871
- this.updateContextFileStepId(contextFilePath, step.id);
60872
- } else if (stepIdFilePath) {
60873
- this.writeStepIdFile(stepIdFilePath, step.id);
60874
- }
60875
- if (laneContextFilePath2) {
60876
- this.updateContextFileStepId(laneContextFilePath2, step.id);
60877
- }
60878
- }
60879
- break;
60880
- }
60881
- case "tool_result":
60882
- await this.stepPersister.persist(sessionId, "tool_result", {
60883
- step_type: "tool_result",
60884
- target_type: target.target_type,
60885
- target_id: target.target_id,
60886
- idempotency_key: `tr:${runtimeEvent.callId}`,
60887
- content: {
60888
- call_id: runtimeEvent.callId,
60889
- tool_name: runtimeEvent.toolName,
60890
- status: runtimeEvent.error ? "error" : "success",
60891
- output: runtimeEvent.output,
60892
- duration_ms: runtimeEvent.durationMs ?? 0,
60893
- collapsible: true
60894
- },
60895
- group_key: runtimeEvent.groupKey
60896
- });
60897
- if (contextFilePath) {
60898
- this.updateContextFileStepId(contextFilePath, null);
60899
- } else if (stepIdFilePath) {
60900
- this.clearStepIdFile(stepIdFilePath);
60901
- }
60902
- if (laneContextFilePath2) {
60903
- this.updateContextFileStepId(laneContextFilePath2, null);
60904
- }
60905
- break;
60906
- case "error":
60907
- await this.stepPersister.persist(sessionId, "error", {
60908
- step_type: "text",
60909
- target_type: target.target_type,
60910
- target_id: target.target_id,
60911
- idempotency_key: randomUUID2(),
60912
- content: buildErrorStepContent(runtimeEvent.message),
60913
- projection: false,
60914
- group_key: runtimeEvent.groupKey
60915
- });
60916
- break;
60917
- }
61189
+ return createRuntimeStep(this, sessionId, target, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2);
60918
61190
  }
60919
61191
  writeContextFile(filePath, ctx) {
60920
61192
  try {
@@ -61064,7 +61336,8 @@ var ParallAgentGateway = class {
61064
61336
  inputLifecycle,
61065
61337
  noteActivity: dispatchDeadline.touch
61066
61338
  })) {
61067
- dispatchDeadline.touch();
61339
+ if (runtimeEvent.type !== "observation")
61340
+ dispatchDeadline.touch();
61068
61341
  if (runtimeEvent.type === "runtime_session") {
61069
61342
  const priorAgentSessionId = binding?.agentSessionId;
61070
61343
  binding = await runInPhaseSpan("session", () => this.bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2));
@@ -61089,6 +61362,14 @@ var ParallAgentGateway = class {
61089
61362
  }
61090
61363
  continue;
61091
61364
  }
61365
+ if (runtimeEvent.type === "observation") {
61366
+ if (binding?.runtimeSessionId === runtimeEvent.runtimeSessionId) {
61367
+ await this.createRuntimeStep(binding.agentSessionId, stepTarget, runtimeEvent);
61368
+ } else {
61369
+ this.opts.log?.warn("runtime observation has no matching active session binding");
61370
+ }
61371
+ continue;
61372
+ }
61092
61373
  if (runtimeEvent.type === "turn_outcome") {
61093
61374
  const outcomeEvent = redactTurnOutcome(runtimeEvent, [this.opts.config.api_key]);
61094
61375
  turnOutcomeEvent = outcomeEvent;
@@ -61461,6 +61742,8 @@ var ParallAgentGateway = class {
61461
61742
  while (this.idleCompact.inFlight)
61462
61743
  await this.idleCompact.inFlight;
61463
61744
  while (this.dispatchState.mainBuffer.length > 0) {
61745
+ while (hasMainSteers(this.dispatchState))
61746
+ await waitForMainSteers(this.dispatchState);
61464
61747
  if (this.shuttingDown) {
61465
61748
  this.opts.log?.info(`drainMainBuffer halted (shutting down) \u2014 ${this.dispatchState.mainBuffer.length} buffered, ${this.dispatchState.pendingForkResults.length} pending fork results left for catch-up`);
61466
61749
  break;
@@ -62036,13 +62319,9 @@ ${fullSummary}` : fullSummary;
62036
62319
  }
62037
62320
  }
62038
62321
  }
62039
- /**
62040
- * Nothing in flight: no dispatch, no runtime-initiated turn, and the
62041
- * runtime itself reports idle (isBusy — a turn it is executing that has
62042
- * not surfaced yet, or a follow-up hold after background work finished).
62043
- */
62322
+ /** Drain includes in-flight native work and unfinished steer registration. */
62044
62323
  isDrained() {
62045
- return this.inFlightDispatches === 0 && this.inFlightRuntimeTurns === 0 && !this.adapterBusy();
62324
+ return this.inFlightDispatches === 0 && this.inFlightRuntimeTurns === 0 && !hasMainSteers(this.dispatchState) && !this.adapterBusy();
62046
62325
  }
62047
62326
  adapterBusy() {
62048
62327
  try {
@@ -62827,6 +63106,18 @@ A restricted-tier request resolves asynchronously \u2014 you receive an
62827
63106
  \`approval.decided\` event when a manager decides. Private projects are
62828
63107
  invitation-only and do not appear in the library.
62829
63108
 
63109
+ A 403 \`PERMISSION_DENIED\` on a task or project read whose error JSON carries
63110
+ \`details.project\` means the resource exists but you are not on that
63111
+ project's roster. The CLI prints the exact next step under the JSON line \u2014 a
63112
+ \`parall projects join\` or \`parall projects request-join\` command
63113
+ synthesized from the project's visibility, or, for a private project, that a
63114
+ manager must add you. Run that command (or, for private, ask a project manager
63115
+ or org owner/admin to add you) instead of asking a human first. Project
63116
+ admission is self-service, not the approvals flow: \`approvable: false\` on such
63117
+ a denial only says \`parall approvals request\` does not apply \u2014 it is not a
63118
+ reason to stop. A restricted request then resolves via \`approval.decided\` as
63119
+ above.
63120
+
62830
63121
  ## Watching Tasks
62831
63122
 
62832
63123
  Watchers receive dispatch events for a task's new comments. Acting on a task
@@ -62844,15 +63135,54 @@ Creators and assignees are locked subscribers \u2014 \`unwatch\` returns 409 for
62844
63135
  them until the role changes (e.g. reassignment); it works for every other
62845
63136
  watcher.
62846
63137
 
63138
+ ## Blocked Work
63139
+
63140
+ A task can be blocked by other tasks: the task payload carries \`is_blocked\`,
63141
+ and a dispatch frame for a blocked task adds a \`Blocked by:\` segment to its
63142
+ meta line, OPEN blockers only, in three forms: \`KEY-1, KEY-2\` are blockers
63143
+ you can read; \`SEC-17 (not a member)\` is one in a public or restricted
63144
+ project you are not on \u2014 \`parall projects library\` finds that project by
63145
+ its key, then \`projects join\` / \`request-join\`; \`+N not readable\` counts
63146
+ blockers in private projects, which only a project manager or org owner/admin
63147
+ can add you to.
63148
+
63149
+ - \`is_blocked: true\` on the task and \`Blocked by\` in a frame are the same
63150
+ condition. Check it FIRST \u2014 before you comment, change the status or start \u2014
63151
+ with \`parall tasks deps list prll://tsk_xxx\`: readable blockers come whole
63152
+ with their \`status\`; the others come as \`restricted: true\` entries whose
63153
+ \`project\` (\`id\`, \`visibility\`, and \`key\` / \`name\` unless private) says
63154
+ what to join. A blocked task stays in its current status; do not set
63155
+ \`in_progress\` or work on it unless a human explicitly tells you to.
63156
+ - A "No longer blocked" notification means every blocker is done or canceled \u2014
63157
+ that is your signal to pick the task up. "Now blocked" means stop and wait.
63158
+ - Do NOT poll and do NOT create a schedule to re-check blockers: the platform
63159
+ wakes you the moment the last blocker finishes. Waiting costs nothing;
63160
+ polling burns turns.
63161
+ - Declare dependencies from either side; the flag name gives the direction:
63162
+
63163
+ \`\`\`bash
63164
+ parall tasks deps list prll://tsk_xxx # blocked_by / blocking; restricted entries name the project to join
63165
+ parall tasks deps add prll://tsk_xxx --blocked-by prll://tsk_yyy # tsk_yyy must finish before tsk_xxx
63166
+ parall tasks deps add prll://tsk_xxx --blocks prll://tsk_yyy # tsk_xxx must finish before tsk_yyy
63167
+ parall tasks deps remove prll://tsk_xxx --blocked-by prll://tsk_yyy
63168
+ \`\`\`
63169
+
63170
+ The server rejects self-dependencies, cycles and over-deep chains
63171
+ (\`RELATION_SELF\` / \`RELATION_CYCLE\` / \`RELATION_CHAIN_TOO_DEEP\`); report the
63172
+ error instead of working around it.
63173
+
62847
63174
  ## Responding to Task Assignments
62848
63175
 
62849
63176
  When you receive \`[Event: task.assigned]\`:
62850
63177
 
62851
63178
  1. Resolve the project and read its current description as described above
62852
- 2. Acknowledge with a comment: \`tasks comments add prll://tsk_xxx --body "On it"\`
62853
- 3. Update status: \`tasks update prll://tsk_xxx --status in_progress --placement end\`
62854
- 4. Do the work
62855
- 5. Report results in a comment. If a gate remains \u2014 review, merge, deploy,
63179
+ 2. If the task is blocked (\`is_blocked: true\` / \`Blocked by\` in the frame),
63180
+ stop here: comment which blockers you are waiting on, leave the status
63181
+ alone, and wait for the "No longer blocked" wake (see "Blocked Work")
63182
+ 3. Acknowledge with a comment: \`tasks comments add prll://tsk_xxx --body "On it"\`
63183
+ 4. Update status: \`tasks update prll://tsk_xxx --status in_progress --placement end\`
63184
+ 5. Do the work
63185
+ 6. Report results in a comment. If a gate remains \u2014 review, merge, deploy,
62856
63186
  requester acceptance \u2014 set \`in_review\` and name the gate; set \`done\`
62857
63187
  only once the work has actually landed
62858
63188
 
@@ -62865,7 +63195,7 @@ When you receive \`[Event: task.comment.created]\`, someone commented on a task
62865
63195
  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)
62866
63196
  4. If the comment requests status changes, update accordingly
62867
63197
 
62868
- 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.
63198
+ CLI success output is JSON; errors print a JSON line plus optional plain-text next-step lines (\`Request approval:\` on an approvable denial, a \`projects join\` / \`request-join\` command on a project-roster denial) \u2014 read both.
62869
63199
  `;
62870
63200
 
62871
63201
  // ts/agent-core/dist/skills/parall-wiki.js
@@ -63752,7 +64082,7 @@ var SKILLS = [
63752
64082
  },
63753
64083
  {
63754
64084
  name: "parall-tasks",
63755
- description: "Parall task operations: create, update, comment on, and query tasks and projects. Use when: user asks to create a task, update task status, add comments, list tasks, or manage projects.",
64085
+ description: "Parall task operations: create, update, comment on, and query tasks and projects; declare or inspect blocking dependencies between tasks. Use when: user asks to create a task, update task status, add comments, list tasks, mark a task as blocked by another, or manage projects.",
63756
64086
  content: PARALL_TASKS_SKILL
63757
64087
  },
63758
64088
  {
@@ -63927,12 +64257,12 @@ var RuntimeActivityPort = class {
63927
64257
  };
63928
64258
 
63929
64259
  // ts/agent-core/dist/runtime-turn-base.js
63930
- import { randomUUID as randomUUID3 } from "node:crypto";
64260
+ import { randomUUID as randomUUID5 } from "node:crypto";
63931
64261
  var RuntimeTurnBase = class {
63932
64262
  sessionKey;
63933
64263
  trigger;
63934
64264
  onDetach;
63935
- groupKey = randomUUID3();
64265
+ groupKey = randomUUID5();
63936
64266
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
63937
64267
  activityListeners = [];
63938
64268
  detached = false;
@@ -64039,7 +64369,7 @@ function stepIdFilePathForSession(stateDir, sessionKey) {
64039
64369
 
64040
64370
  // ts/claude-agent/dist/dispatch.js
64041
64371
  import { execSync as execSync2, spawn } from "node:child_process";
64042
- import { randomUUID as randomUUID6 } from "node:crypto";
64372
+ import { randomUUID as randomUUID8 } from "node:crypto";
64043
64373
  import * as fs8 from "node:fs";
64044
64374
  import * as path11 from "node:path";
64045
64375
 
@@ -64616,7 +64946,7 @@ function parseContentLength(value) {
64616
64946
  }
64617
64947
 
64618
64948
  // ts/claude-agent/dist/compact.js
64619
- import { randomUUID as randomUUID4 } from "node:crypto";
64949
+ import { randomUUID as randomUUID6 } from "node:crypto";
64620
64950
  async function runClaudeCompact(host, { sessionKey, signal, log: log2 }) {
64621
64951
  if (signal.aborted)
64622
64952
  return { status: "timeout" };
@@ -64630,7 +64960,7 @@ async function runClaudeCompact(host, { sessionKey, signal, log: log2 }) {
64630
64960
  if (state.inputs.hasPendingInjections() || state.inputs.hasUnsettledInjections()) {
64631
64961
  return { status: "failed", detail: "injections still pending on the session" };
64632
64962
  }
64633
- const delivery = state.inputs.register(`compact:${randomUUID4()}`, void 0, false);
64963
+ const delivery = state.inputs.register(`compact:${randomUUID6()}`, void 0, false);
64634
64964
  try {
64635
64965
  host.writeUserMessage(state.handle, "/compact", delivery.commandUuid);
64636
64966
  } catch (err) {
@@ -64814,12 +65144,14 @@ function aggregateBusyState(states) {
64814
65144
  }
64815
65145
 
64816
65146
  // ts/claude-agent/dist/input-lifecycle.js
64817
- import { randomUUID as randomUUID5 } from "node:crypto";
65147
+ import { randomUUID as randomUUID7 } from "node:crypto";
64818
65148
 
64819
65149
  // ts/claude-agent/dist/turn-outcome.js
64820
65150
  var LIMIT_TEXT = /you'?ve (hit|reached) your .*limit|usage limit reached|weekly limit/i;
64821
- var AUTH_TEXT = /not logged in|please run \/login|authentication_error|invalid api key|oauth token (has )?expired|\[action required\]/i;
65151
+ var AUTH_TEXT = /not logged in|please run \/login|authentication_error|authentication_failed|failed to authenticate|invalid api key|oauth (token|session) (has )?expired|\[action required\]/i;
64822
65152
  var CONTEXT_TEXT = /prompt is too long|context (window|length) exceeded|request too large/i;
65153
+ var RATE_LIMIT_ERROR_TEXT = /rate_limit_error/i;
65154
+ var QUOTA_TEXT = /credit balance is too low|insufficient credits|insufficient_quota|payment required/i;
64823
65155
  var DETAIL_MAX = 500;
64824
65156
  function minutesOfDayInZone(fmt, at) {
64825
65157
  const parts = Object.fromEntries(fmt.formatToParts(at).filter((p) => p.type !== "literal").map((p) => [p.type, Number(p.value)]));
@@ -64916,9 +65248,15 @@ function classifyClaudeTurn(meta, noticeTexts, now = /* @__PURE__ */ new Date())
64916
65248
  });
64917
65249
  if (meta.apiErrorStatus === 401 || meta.apiErrorStatus === 403)
64918
65250
  return withDetail("auth");
65251
+ if (meta.apiErrorStatus === 402)
65252
+ return withDetail("quota_exhausted");
64919
65253
  if (meta.apiErrorStatus === 413)
64920
65254
  return withDetail("context_overflow");
64921
65255
  if (meta.apiErrorStatus === 429) {
65256
+ if (QUOTA_TEXT.test(evidence))
65257
+ return withDetail("quota_exhausted");
65258
+ if (RATE_LIMIT_ERROR_TEXT.test(evidence))
65259
+ return withDetail("transient");
64922
65260
  return withDetail("usage_limit", evidence ? parseClaudeResetTime(evidence, now) : void 0);
64923
65261
  }
64924
65262
  const failed = meta.isError || // Claude CLI 2.1.220 sets terminal_reason=completed on clean result
@@ -64931,12 +65269,14 @@ function classifyClaudeTurn(meta, noticeTexts, now = /* @__PURE__ */ new Date())
64931
65269
  if (failed || syntheticQuiet || noticeTexts.length > 0) {
64932
65270
  if (CONTEXT_TEXT.test(evidence))
64933
65271
  return withDetail("context_overflow");
65272
+ if (QUOTA_TEXT.test(evidence))
65273
+ return withDetail("quota_exhausted");
64934
65274
  if (LIMIT_TEXT.test(evidence)) {
64935
65275
  return withDetail("usage_limit", parseClaudeResetTime(evidence, now));
64936
65276
  }
64937
65277
  if (AUTH_TEXT.test(evidence))
64938
65278
  return withDetail("auth");
64939
- return withDetail("api_error");
65279
+ return withDetail("transient");
64940
65280
  }
64941
65281
  return { ...base, outcome: "ok" };
64942
65282
  }
@@ -65056,7 +65396,7 @@ var ClaudeInputRegistry = class {
65056
65396
  if (this.byKey.has(deliveryKey)) {
65057
65397
  throw new Error(`duplicate Claude delivery key ${deliveryKey}`);
65058
65398
  }
65059
- const commandUuid = randomUUID5();
65399
+ const commandUuid = randomUUID7();
65060
65400
  const delivery = {
65061
65401
  deliveryKey,
65062
65402
  commandUuid,
@@ -65137,7 +65477,7 @@ var ClaudeInputRegistry = class {
65137
65477
  detail: detail ?? classified.detail ?? "Claude input failed"
65138
65478
  });
65139
65479
  delivery.reportedState = "failed";
65140
- delivery.terminal = result?.retry === false ? "settled" : "failed";
65480
+ delivery.terminal = result && !result.pending && result.retry === false ? "settled" : "failed";
65141
65481
  }
65142
65482
  } finally {
65143
65483
  delivery.terminal ??= "failed";
@@ -65157,6 +65497,60 @@ var ClaudeInputRegistry = class {
65157
65497
  }
65158
65498
  };
65159
65499
 
65500
+ // ts/claude-agent/dist/runtime-observations.js
65501
+ function claudeObservation(frame) {
65502
+ const sessionId = observationField(frame.session_id);
65503
+ if (!sessionId || frame.parent_tool_use_id)
65504
+ return;
65505
+ const native = {
65506
+ session_id: sessionId,
65507
+ event_id: observationField(frame.uuid)
65508
+ };
65509
+ let event;
65510
+ let status = "unknown";
65511
+ if (frame.type === "result") {
65512
+ event = "request_completed";
65513
+ status = frame.is_error === true ? "failed" : frame.is_error === false ? "completed" : "unknown";
65514
+ native.status = observationField(frame.subtype);
65515
+ if (typeof frame.num_turns === "number" && Number.isSafeInteger(frame.num_turns) && frame.num_turns >= 0) {
65516
+ native.num_turns = frame.num_turns;
65517
+ }
65518
+ } else if (frame.type === "system") {
65519
+ switch (frame.subtype) {
65520
+ case "init":
65521
+ event = "session_initialized";
65522
+ status = "initialized";
65523
+ break;
65524
+ case "hook_started":
65525
+ case "hook_response":
65526
+ event = frame.subtype === "hook_started" ? "hook_started" : "hook_completed";
65527
+ status = frame.subtype === "hook_started" ? "running" : frame.outcome === "success" ? "completed" : frame.outcome === "error" ? "failed" : frame.outcome === "cancelled" ? "stopped" : "unknown";
65528
+ native.hook_id = observationField(frame.hook_id);
65529
+ native.hook_event = observationField(frame.hook_event);
65530
+ native.status = observationField(frame.outcome);
65531
+ break;
65532
+ case "status":
65533
+ case "session_state_changed":
65534
+ event = "session_status";
65535
+ native.status = observationField(frame.status) ?? observationField(frame.state);
65536
+ if (native.status === "compacting" || native.status === "running" || native.status === "idle") {
65537
+ status = native.status;
65538
+ }
65539
+ break;
65540
+ default:
65541
+ return;
65542
+ }
65543
+ } else
65544
+ return;
65545
+ return runtimeObservation(sessionId, {
65546
+ runtime: "claude-code",
65547
+ source: "stream_json",
65548
+ event,
65549
+ status,
65550
+ native
65551
+ });
65552
+ }
65553
+
65160
65554
  // ts/claude-agent/dist/output-parser.js
65161
65555
  var RUNTIME_TASK_SUBTYPES = /* @__PURE__ */ new Set([
65162
65556
  "background_tasks_changed",
@@ -65257,6 +65651,9 @@ async function* parseClaudeStreamJson(readable) {
65257
65651
  const now = Date.now();
65258
65652
  const eventTimestampMs = parseEventTimestampMs(event) ?? now;
65259
65653
  const eventRecord = event;
65654
+ const observation = claudeObservation(eventRecord);
65655
+ if (observation && observation.content.event !== "session_initialized")
65656
+ yield observation;
65260
65657
  if (eventRecord.type === "system" && eventRecord.subtype === "compact_boundary") {
65261
65658
  const meta = eventRecord.compact_metadata && typeof eventRecord.compact_metadata === "object" ? eventRecord.compact_metadata : void 0;
65262
65659
  const trigger = asTrimmedString(meta?.trigger);
@@ -65277,6 +65674,8 @@ async function* parseClaudeStreamJson(readable) {
65277
65674
  ...sessionId ? { sessionId } : {},
65278
65675
  capabilities
65279
65676
  };
65677
+ if (observation)
65678
+ yield observation;
65280
65679
  continue;
65281
65680
  }
65282
65681
  const subtype = asTrimmedString(eventRecord.subtype);
@@ -65569,6 +65968,7 @@ var ClaudeProcessPump = class {
65569
65968
  idleTimer = null;
65570
65969
  activeDrain = null;
65571
65970
  now;
65971
+ pendingObservations = [];
65572
65972
  constructor(opts) {
65573
65973
  this.opts = opts;
65574
65974
  this.now = opts.now ?? Date.now;
@@ -65689,7 +66089,8 @@ var ClaudeProcessPump = class {
65689
66089
  for await (const parsed of parser) {
65690
66090
  if (this.closed)
65691
66091
  break;
65692
- this.touchAll();
66092
+ if (parsed.type !== "observation")
66093
+ this.touchAll();
65693
66094
  await this.route(parsed);
65694
66095
  }
65695
66096
  } catch (err) {
@@ -65702,6 +66103,9 @@ var ClaudeProcessPump = class {
65702
66103
  switch (parsed.type) {
65703
66104
  case "runtime_activity":
65704
66105
  return;
66106
+ case "observation":
66107
+ this.routeObservation(parsed);
66108
+ return;
65705
66109
  case "runtime_init":
65706
66110
  this.handleInit(parsed);
65707
66111
  return;
@@ -65751,6 +66155,24 @@ var ClaudeProcessPump = class {
65751
66155
  }
65752
66156
  this.runtimeTurn?.touch();
65753
66157
  }
66158
+ routeObservation(event) {
66159
+ if (!this.sessionId) {
66160
+ if (this.pendingObservations.length < 64)
66161
+ this.pendingObservations.push(event);
66162
+ else
66163
+ this.opts.log?.warn("Claude startup observation buffer full; dropping observation");
66164
+ return;
66165
+ }
66166
+ if (event.runtimeSessionId !== this.sessionId) {
66167
+ this.opts.log?.warn("Claude observation does not match the initialized session");
66168
+ return;
66169
+ }
66170
+ const owner = this.ownerFor(false) ?? (this.activeDrain && !this.activeDrain.terminal ? this.activeDrain : null);
66171
+ if (owner)
66172
+ owner.sink.push({ kind: "runtime", event });
66173
+ else
66174
+ this.opts.hooks.onObservation?.(event);
66175
+ }
65754
66176
  liveDeliveries() {
65755
66177
  const live = [];
65756
66178
  for (const delivery of this.opts.inputs.values())
@@ -65820,6 +66242,10 @@ var ClaudeProcessPump = class {
65820
66242
  delivery.sessionAnnounced = true;
65821
66243
  delivery.sink.push({ kind: "runtime", event: announce });
65822
66244
  }
66245
+ const pending = this.pendingObservations;
66246
+ this.pendingObservations = [];
66247
+ for (const event of pending)
66248
+ this.routeObservation(event);
65823
66249
  }
65824
66250
  async handleLifecycle(parsed) {
65825
66251
  if (!this.capabilities.has("msg_lifecycle_v1")) {
@@ -65960,6 +66386,9 @@ function buildSpawnEnv(parentEnv, claudeHome, context2, opts) {
65960
66386
  const result = {
65961
66387
  ...env,
65962
66388
  HOME: claudeHome,
66389
+ // Request native state frames for observation without changing user files.
66390
+ // Preserve an operator's explicit opt-out; older CLIs can ignore the flag.
66391
+ CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: env.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS ?? "1",
65963
66392
  PRLL_API_URL: context2.apiUrl,
65964
66393
  PRLL_API_KEY: context2.apiKey,
65965
66394
  PRLL_ORG_ID: context2.orgId,
@@ -66143,32 +66572,34 @@ var ClaudeCodeAdapter = class {
66143
66572
  return false;
66144
66573
  return state.inputs.hasUnsettledInjections();
66145
66574
  }
66575
+ isInjectionLive(sessionKey, deliveryKey) {
66576
+ const state = this.processes.get(sessionKey);
66577
+ if (!state || state.done)
66578
+ return false;
66579
+ const delivery = state.inputs.getByKey(deliveryKey);
66580
+ if (!delivery || delivery.terminal)
66581
+ return false;
66582
+ const { proc } = state.handle;
66583
+ return proc.exitCode === null && proc.signalCode === null;
66584
+ }
66146
66585
  /**
66147
66586
  * The gateway discarded the buffered copy of an injection without a
66148
- * dispatch(). A settled injection only owes bookkeeping. One that has NOT
66149
- * settled is an orphan: nothing will ever drain it, and the CLI does not
66150
- * start a queued input on its own once the turn it was steered into has
66151
- * ended — it works its queue only when the next stdin frame arrives, which
66152
- * would be the batch re-delivering this very member (prod 2026-09-03: lane
66153
- * dethroned after 10 idle minutes, then "refusing duplicate stdin write"
66154
- * on every retry). Withdraw it: kill the process (the session survives via
66155
- * --resume), report the input failed so the server releases the member,
66156
- * and let the gateway run it as a real turn.
66587
+ * dispatch(). A settled injection only owes bookkeeping. A live one never
66588
+ * reaches here (the gateway attaches to it via isInjectionLive); if one
66589
+ * does, it is left registered — byCommand must keep routing its lifecycle
66590
+ * frames and its terminal state drops it (see apply/fail) — and the
66591
+ * anomaly is logged. Killing it is not an option: Claude Code starts a
66592
+ * queued input on its own once the turn it was steered into ends, and the
66593
+ * server, having recorded that `started` as delivered, would never re-run
66594
+ * it (2026-09-17 prod loss).
66157
66595
  */
66158
- async acknowledgeDiscardedInjection(sessionKey, deliveryKey) {
66596
+ acknowledgeDiscardedInjection(sessionKey, deliveryKey) {
66159
66597
  const state = this.processes.get(sessionKey);
66160
66598
  if (!state)
66161
66599
  return "discarded";
66162
66600
  const delivery = state.inputs.getByKey(deliveryKey);
66163
66601
  if (delivery && !delivery.terminal) {
66164
- state.log?.warn?.(`withdrawing orphaned Claude input ${delivery.commandUuid} (${delivery.reportedState ?? "queued"}) on ${sessionKey}: its buffered copy was discarded before the CLI settled it${state.pump.hasOwnWork() ? "; the runtime-initiated turn dies with the process" : ""}`);
66165
- await this.killProcess(sessionKey, state);
66166
- state.inputs.discardBookkeeping(deliveryKey);
66167
- const confirmed = delivery.reportedState === "failed" && delivery.terminal === "failed";
66168
- if (!confirmed) {
66169
- state.log?.warn?.(`withdrawal of Claude input ${delivery.commandUuid} was not confirmed by the server (${delivery.terminal}); leaving the member to the lane complete`);
66170
- }
66171
- return confirmed ? "cancelled" : "discarded";
66602
+ state.log?.warn?.(`buffered copy of Claude input ${delivery.commandUuid} (${delivery.reportedState ?? "queued"}) on ${sessionKey} discarded while still live \u2014 keeping its registration; the runtime runs it as its own turn`);
66172
66603
  }
66173
66604
  state.inputs.discardBookkeeping(deliveryKey);
66174
66605
  this.maybeApplyRestart(sessionKey, state);
@@ -66371,7 +66802,7 @@ var ClaudeCodeAdapter = class {
66371
66802
  async *consumeDelivery(sessionKey, state, target, noteActivity) {
66372
66803
  if (target.terminal)
66373
66804
  return;
66374
- const groupKey = randomUUID6();
66805
+ const groupKey = randomUUID8();
66375
66806
  state.pump.setActiveDrain(target, noteActivity);
66376
66807
  try {
66377
66808
  while (true) {
@@ -66480,10 +66911,9 @@ var ClaudeCodeAdapter = class {
66480
66911
  this.processes.delete(sessionKey);
66481
66912
  this.retiring.delete(state);
66482
66913
  },
66483
- // Main-session turns go to the gateway (steps + session activity);
66484
- // fork-session turns only count as busy (fork-scope invariant).
66485
66914
  onRuntimeTurnOpened: (turn) => this.activity.surfaceTurn(turn, this.opts.sessionManager.isMain(sessionKey), log2),
66486
- onRuntimeTurnClosed: () => this.maybeApplyRestart(sessionKey, state)
66915
+ onRuntimeTurnClosed: () => this.maybeApplyRestart(sessionKey, state),
66916
+ onObservation: (event) => this.activity.emit({ kind: "observation", sessionKey, event }, log2)
66487
66917
  }
66488
66918
  }),
66489
66919
  done: false,
@@ -66572,7 +67002,7 @@ var ClaudeCodeAdapter = class {
66572
67002
  writeCapabilityProbe(handle) {
66573
67003
  const payload = JSON.stringify({
66574
67004
  type: "user",
66575
- uuid: randomUUID6(),
67005
+ uuid: randomUUID8(),
66576
67006
  parent_tool_use_id: null,
66577
67007
  message: { role: "user", content: [] }
66578
67008
  });
@@ -66646,7 +67076,7 @@ var ClaudeCodeAdapter = class {
66646
67076
  // ts/claude-agent/dist/session-manager.js
66647
67077
  import * as fs9 from "node:fs";
66648
67078
  import * as path12 from "node:path";
66649
- import { randomUUID as randomUUID7 } from "node:crypto";
67079
+ import { randomUUID as randomUUID9 } from "node:crypto";
66650
67080
  var ClaudeSessionManager = class _ClaudeSessionManager {
66651
67081
  mainSessionKey;
66652
67082
  stateFilePath;
@@ -66686,7 +67116,7 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
66686
67116
  const parentSessionId = this.sessionIds.get(parentSessionKey);
66687
67117
  if (!parentSessionId)
66688
67118
  return null;
66689
- const sessionKey = `claude-fork:${randomUUID7()}`;
67119
+ const sessionKey = `claude-fork:${randomUUID9()}`;
66690
67120
  this.pendingForkParents.set(sessionKey, parentSessionId);
66691
67121
  return {
66692
67122
  sessionKey,