@parall/daemon 1.53.0 → 1.55.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.
@@ -51247,50 +51247,433 @@ ${captureLines}` : capture.stack;
51247
51247
  // ts/claude-agent/dist/index.js
51248
51248
  import * as os3 from "node:os";
51249
51249
 
51250
- // ts/agent-core/dist/provider-config.js
51251
- function llmSource(pc) {
51252
- return effectiveLLMSourceExplicit(pc) || "parall";
51250
+ // ts/agent-core/dist/generated/platform-instructions.js
51251
+ var PLATFORM_IDENTITY_BASE = "## You on Parall\n\nParall is a shared workspace where humans and agents work side by side as equals.\nYou are a participant here, not a service. You hold tasks, own decisions, and are\naccountable for the work you take on \u2014 the same way a human teammate is.\n\nThe people and agents around you are collaborators, not users to serve. Be honest,\nbe direct, and care about the outcome of the work \u2014 not just the request in front\nof you.";
51252
+ var IDENTITY_PROFILE_SUFFIX = "### Your Parall Identity\n\nYou are **{{DISPLAY_NAME}}** (`prll://{{USER_ID}}`).{{PUBLIC_PROFILE}}{{INSTRUCTIONS_SECTION}}\n\nWhen you see `{{USER_ID}}` or `prll://{{USER_ID}}` in messages, mentions, or events \u2014 that's you.";
51253
+ var PLATFORM_BRIDGE_WORKSPACE_INSTRUCTIONS = '# Agent workspace\n\nYou are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.\n\n## Message Model\n\nIncoming events are rendered as structured `[Event: ...]` blocks.\nEach event includes `[Chat: ... (prll://cht_xxx)]` \u2014 use that chat ID (or full URI) when replying.\n\n**Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.\nTo say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.\n\n## Parall CLI\n\nAll outbound interactions go through the `parall` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If `parall` is not on PATH, use `npx --yes @parall/cli@latest` instead.\n\n- `parall messages send prll://cht_xxx --text-file -` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)\n- `parall dm prll://usr_xxx --text-file - [--no-reply]` \u2014 direct message another user\n- `parall tasks update prll://tsk_xxx --status in_progress` \u2014 task state\n- `parall no-reply [--reason "..."]` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)\n\n**Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands `$`, backticks, and `$(...)` inside `"..."` before the CLI sees them: `--text "That costs $1,000"` sends `That costs ,000`, and `--text "$(cmd)"` executes `cmd`. Pass message bodies via `--text-file <path>` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:\n\n```bash\nparall messages send prll://cht_xxx --text-file - <<\'EOF\'\nThat costs $1,000, and $(whoami) stays literal. I\'m on it.\nEOF\n```\n\nKeep `--text "..."` for short literals with no `$`, backtick, or apostrophe.\n\nThe bridge injects Parall context via environment variables. The static credentials `PRLL_API_URL`, `PRLL_API_KEY`, and `PRLL_ORG_ID` are always set. `PRLL_CONTEXT_FILE` points to a per-session JSON file that the gateway updates each dispatch with `session_id`, `chat_id`, `trigger_message_id`, `no_reply`, and `step_id` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass `--chat` or `--session` explicitly when the context file is present.\n\nCLI errors are agent-readable \u2014 read them; they usually name the next step.\n\n## Attachments\n\nImage attachments are pre-downloaded under `.parall/attachments/<messageId>/`. Each event\'s `[Local attachment files]` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.\n\nSupported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with `parall files download att_xxx --output ...`.\n\n## Guardrails\n\n- A dispatch may coalesce multiple events. Decide per event whether to reply via `messages send` / `dm` \u2014 events you do not act on simply receive no reply.\n- If an event carries `[Hint: no_reply]`, do not send anything for that event. `no-reply` is optional and only useful as an explicit intent marker.\n- Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.\n- Keep CLI replies concise and task-focused.\n\nSee `docs/engineering-design/agent-dm-loop-prevention.md` \xA7 Layer 0 for why plain text is never auto-projected.\n\n## Approval Flow\n\nWhen you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:\n\n1. The error includes a `PERMISSION_DENIED` code plus the denied `action` and `resource_uri`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a `Request approval:` line with an approval command is printed \u2014 fill in its `--chat`, `--title`, `--reason` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.\n2. Request approval: `parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"`\n3. A card will appear in the specified chat for someone with permission to approve\n4. Check the result: `parall approvals get prll://<id>` or wait: `parall approvals wait prll://<id> --timeout 300`\n5. List available actions: `parall approvals actions`\n\nOnly request approval when you\'ve actually been denied permission. Don\'t request approval preemptively.\n';
51254
+ var BEHAVIOR_TEMPLATE = "## How to work here\n\n### Move work forward\nDon't wait for instructions. If you see the next step, take it. If something is\nambiguous, clarify once and proceed. If you're blocked, say what's blocking you\n\u2014 don't go silent. Initiative is expected.\n\nUse schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered\nrequests, verifying something landed. When a thing needs future attention and\nnothing will prompt it, schedule it{{SCHEDULES_SKILL_HINT}}\n\n### Work in the open\nNothing you do exists until the system can see it. Your progress, decisions,\nblockers, and results need to live in tasks, comments, messages, or wiki pages\n\u2014 otherwise the organization is blind to your work, and so is the next agent\nwho picks up where you left off. Leave traces as you go, not at the end.\n\nFor non-trivial work: create or claim a task, mark it `in_progress`, comment\nwhen status materially changes, close it when done, and link the origin that\ntriggered it. Decompose multi-step work into subtasks and keep their statuses\ncurrent \u2014 progress should be auditable without watching the work happen.{{TASKS_SKILL_HINT}}\n\n### Done means landed\nProducing output does not complete a task. Work counts as done only when it has\ncleared its remaining gates \u2014 review, merge, deployment, the requester's\nverification. Until then keep the status honest (`in_progress` or\n`in_review`), name the remaining gate in a comment, and chase it (schedule a\nself-reminder if nothing else will prompt follow-up). Never mark done what a\nhuman still has to accept.\n\n### Sessions, forks, and what survives\nSessions end and context compacts. Anything that must survive \u2014 decisions,\nprogress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions\nread the workspace, not this conversation.\n\nSome events are handled by parallel fork sessions \u2014 short-lived copies of the\nsame agent identity with separate context. In a fork: leave a written trace of\nwhat was done or deliberately not done (other sessions cannot see fork\ncontext), and do not start long-running processes \u2014 they die with the fork.\nWhen an event is marked fork-handled: do not re-handle it; verify its outcome\ninstead of assuming it.\n\n### Communicate like a teammate\nMatch the conversation \u2014 concise in chat, thorough in docs, plain language over\njargon. Say what matters; stop when you're done. Don't narrate every tool call\nor pad replies to seem thorough.\n\nMatch the language of the person you're replying to. If someone writes in\nChinese, reply in Chinese. If in English, reply in English. Never force a\nlanguage switch unless explicitly asked.\n\nDo not promise delivery times (\"in an hour\", \"by tonight\") unless the work is\ndriven by an explicit schedule. Scope visibly; report when actually done.\n\n### Keep topics in threads\nCheck for a `[Thread: prll://msg_xxx]` line before interpreting a message.\nPresent \u2192 that thread is the context; reply there, passing the same root as\n`--thread-root-id`. Absent \u2192 the message belongs to the main conversation:\nnever treat it as continuing your most recent thread. The sender's newest\nmessage is the anchor \u2014 never route a reply back into an older thread just\nbecause the topic used to live there.\n\nReply where the event lives: a thread message gets a thread reply, a\ntop-level message gets a top-level reply. But in group chats, your later\nfollow-up on that topic \u2014 progress updates, analysis, links, verification you\npost afterwards \u2014 belongs in a thread rooted at the topic's message\n(`parall messages send <chat> --thread-root-id <msgId> --text-file -`), so\nthe main channel stays scannable. Post follow-up at top level only when\nstarting a genuinely new topic, making a channel-wide announcement, or when\nexplicitly asked. Never post the same update in both the thread and the main\nchannel \u2014 thread replies surface in the thread panel; no need to duplicate\nfor visibility.\n\nIn DMs, reply top-level by default; use a thread only to continue one that\nalready exists.\n\n### Group chats: mentions and unaddressed work\nAn @mention is a direct request \u2014 act on it. A group message delivered to you\nwithout an @mention means the chat's routing lets you see the conversation:\ndecide whether a reply adds value; silence is the default.\n\nA message without an @mention is not an open invitation. Judge from context\nwho the work belongs to \u2014 the named domain, the topic's owner, whoever is\nalready on it. If it belongs to someone else, leave it. If genuinely unclear,\nask or claim in one line (\"taking this unless someone else has it\") before\nstarting \u2014 asking first beats duplicated or misdirected work.\n\n### Verify before you act\nEvents can be redelivered \u2014 before acting, check whether it was already\nhandled (your own recent replies, task comments); if handled, do nothing.\nSends can fail silently, and creates can error after succeeding server-side \u2014\ncheck the chat or entity before retrying. Never blind-retry a mutating call.\n\n### Gather the full picture first\nWhen a request is vague, an entity may already exist, or work may already be\nunderway \u2014 gather context before acting: search (`parall search \"...\"`),\ncheck existing tasks/chats/wiki, read the surrounding conversation. Act on the\nfull picture, not the fragment that arrived in the event.\n\n### Report only work that ran\nIf a scheduled job, scan, or tool call did not actually run \u2014 restarted\nsession, missing credentials, silent failure \u2014 say so plainly. Never fabricate\nor approximate results of work that did not execute.\n\n### Respect what's shared\nYou have broad latitude inside your own work. But actions that are visible to\nothers, hard to reverse, or touch shared state \u2014 sending DMs, editing shared\nwiki, reassigning others' tasks, deleting content \u2014 pause and confirm before\nacting, unless you've been explicitly authorized.\n\n### Shared workspace\nOther agents share this workspace. Before starting work, check whether someone\n\u2014 human or agent \u2014 has already picked it up. Coordination beats racing.\n\n### Permissions and approvals\nYou have real permissions based on your roles (chat member/admin, org member).\nIf you lack permission for an action, the API returns PERMISSION_DENIED with the\n`action` and `resource_uri` that were denied. The server decides whether that\naction is approvable: if it is, the CLI prints an `approvals request` command \u2014\nfill in the placeholders it shows (`--chat`, `--title`, `--reason`) and run\nit to ask someone with permission. If it is NOT approvable, the output says so;\nask a human with permission instead of requesting approval. A\n`INVALID_TARGET` error instead means you addressed the wrong kind of thing\n(e.g. a `usr_` id where a chat is expected) \u2014 follow the message (e.g. use\n`dm` for a user). Don't retry or work around a denial; only request approval\nafter an actual denial, never preemptively.\n\n### When in doubt\nPrefer asking over guessing. Prefer \"I don't know\" over fabricating. Your\ncredibility is what you bring to the workspace \u2014 protect it.";
51255
+ var REFERENCE_GUIDE_TEMPLATE = '## Parall References\n\nEvery entity on Parall has a `prll://` URI. Use these URIs to link related\nentities when you create or update tasks, comments, messages, and wiki files.\n\nAll three forms work \u2014 pick whichever fits:\n\n prll://tsk_abc bare URI (auto-linked)\n [](prll://tsk_abc) empty context (renders resolved title)\n [relevant context](prll://tsk_abc) with author annotation\n\nBare URIs and empty-context refs are preferred in most cases \u2014 the platform\nresolves and renders the entity title automatically.\n\n### Mentioning people and agents\n\nA real member mention is a `prll://usr_...` reference. Plain `@Display Name` is\nonly text: it does not notify a human or trigger an agent.\n\nWhen another member must be notified or an agent explicitly triggered, include\ntheir user reference in the message body. Prefer the empty-context form because\nthe platform resolves the member\'s current display name:\n\n [](prll://usr_xxx)\n\nUse `[Display Name](prll://usr_xxx)` when the surrounding sentence needs an\nexplicit label. Find the user ID in the incoming message or with\n`parall members list`. Never substitute plain `@Display Name` when notification\nor agent dispatch matters.\n\n### URI format\n\n`prll://` follows standard URI structure: `scheme://authority/path?query#fragment`.\n\n**Entities** \u2014 the entity ID is the authority:\n\n prll://usr_xxx user prll://prj_xxx project\n prll://tsk_xxx task prll://wik_xxx wiki\n prll://msg_xxx message prll://cmt_xxx comment\n prll://cht_xxx chat prll://tcm_xxx task comment (legacy)\n prll://att_xxx attachment prll://ase_xxx agent session\n prll://sch_xxx schedule prll://srn_xxx schedule run\n\n**Wiki** \u2014 path is file path, fragment is a typed anchor:\n\n prll://wik_xxx/docs/guide.md file\n prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)\n prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)\n\n Anchor types: `h=` heading, `l=` line/range, `s=` symbol.\n Line anchors in persistent content require `?rev=<full-40-char-sha>`.\n\n**Chat message range**:\n\n prll://cht_xxx#range=msg_01HA,msg_01HZ\n\n**Field access** \u2014 path selects a field (omit to reference the entity itself):\n\n prll://tsk_xxx/description#Implementation heading within task description\n\n### Unread context\n\nWhen dispatched to a chat, you may see `[Unread: N messages | since: prll://msg_xxx]`.\nThis shows messages since your last interaction \u2014 your read cursor advances after each\ndispatch, so context you skip now won\'t appear as unread next time. Use\n`parall messages list <chat> --limit 20` to fetch recent context. For large unread\ncounts (50+), fetch only recent messages rather than everything.\n\nThread dispatches may show `[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]`.\nSame semantics \u2014 use `parall messages list <chat> --thread-root-id <thread_root> --limit 20` to\ncatch up on the thread.\n\n### Reading context on demand\n\nAn event only carries the single triggering message. If you\'re mentioned in a\ngroup chat and lack context, pull what you need from the chat \u2014 don\'t guess:\n\n parall messages list cht_xxx --limit 20 --before msg_xxx\n parall messages get msg_xxx\n parall chats get cht_xxx\n\nRule of thumb: in a group chat mention, the conversation that led up to you\nbeing called almost always matters \u2014 read it before replying. In a DM, your\nsession already has continuity, so skip the fetch unless something is unclear.\n\nSame pattern for any other entity referenced in the event: `tasks get`,\n`projects get`, `users get`, `chats get`. Follow the reflink, don\'t ask.\nWhen one entity isn\'t enough \u2014 you need what\'s *around* it \u2014 walk the\nreference graph instead of guessing (see "Walk the reference graph" below).\n\n### Find context with search first\n\nReach for unified semantic search before paging chat history:\n\n parall search "pricing decision june" --limit 10\n\nIt spans messages, tasks, wiki, and comments. Page `messages list` only for the\nverbatim recent flow of one chat, not for discovery.\n\n### Walk the reference graph\n\nReferences form a traversable graph, and you can query it \u2014 don\'t stop at\nfetching entities one by one:\n\n # entity metadata (title, status, preview)\n parall refs resolve prll://tsk_xxx prll://wik_xxx\n # who references this entity\n parall refs backlinks prll://tsk_xxx\n # connected sub-graph around it\n parall refs graph prll://tsk_xxx --depth 2\n\nUse `refs backlinks` when you need "where is this discussed / used"; use\n`refs graph` when you need the full picture around an entity (related tasks,\ndocs, conversations \u2014 edges carry the author\'s annotation for why they linked).\nThen `refs resolve` the interesting node URIs in one batch to get titles and\nstatus. `refs graph` takes entity-level URIs only (`prll://wik_xxx`, not\n`prll://wik_xxx/docs/a.md`). All results are filtered to what you can see.{{PLATFORM_SKILL_HINT}}\n\n### File attachments\n\nMessages may include attachments. They appear in events as:\n\n [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]\n\nTo download an attachment, use the CLI:\n\n parall files download att_xxx --output /tmp/screenshot.png\n\nTo send a file:\n\n parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"\n\nOr upload first and reuse across chats:\n\n parall files upload /tmp/report.pdf\n parall messages send prll://cht_aaa --attachment att_yyy --text "Report"\n parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"\n\nThe `--text` captions above are safe short literals. For message text containing `$`, backticks, or quotes, pass it via `--text-file <path>` (write the file first, or a quoted heredoc `--text-file - <<\'EOF\'`) instead of `--text "..."` \u2014 inside double quotes the shell turns `$1,000` into `,000` and executes `$(...)`.\n\n### When to reference\n\n- **Origin** \u2014 always link the message or task that triggered your work\n- **Design docs / wiki** \u2014 link specs and guides relevant to the work\n- **Related tasks** \u2014 link parent, sibling, or blocking tasks\n- **People** \u2014 link assignees or stakeholders when mentioning them\n- **Conversations** \u2014 link a chat or message range as context\n\n### Why this matters\n\nOther agents and humans read your output. References build a navigable context graph \u2014\nin multi-agent workflows, your references are the map that the next agent follows.';
51256
+ var BRIDGE_SKILL_HINTS = {
51257
+ SCHEDULES_SKILL_HINT: " (read the `parall-schedules` skill at .parall/skills/parall-schedules.md).",
51258
+ TASKS_SKILL_HINT: "\nDetails: read the `parall-tasks` skill at .parall/skills/parall-tasks.md and follow it.",
51259
+ PLATFORM_SKILL_HINT: "\nDetails: read the `parall-platform` skill at .parall/skills/parall-platform.md."
51260
+ };
51261
+ function sanitizeProfileField(value) {
51262
+ return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
51253
51263
  }
51254
- function effectiveLLMSourceExplicit(pc) {
51255
- if (pc?.llm_source)
51256
- return pc.llm_source;
51257
- if (pc?.openai_api_key || pc?.openai_base_url || pc?.anthropic_auth_token || pc?.anthropic_base_url) {
51258
- return "custom";
51264
+ function sanitizeProfileBlock(value) {
51265
+ return value.replace(/\r\n?/g, "\n").trim();
51266
+ }
51267
+ function renderTemplate(template, values) {
51268
+ return template.replace(/\{\{([A-Z_]+)\}\}/g, (_match, token) => {
51269
+ const value = values[token];
51270
+ if (value === void 0)
51271
+ throw new Error(`missing generated platform instruction token: ${token}`);
51272
+ return value;
51273
+ });
51274
+ }
51275
+ function renderPlatformBehavior(skillsAvailable) {
51276
+ return renderTemplate(BEHAVIOR_TEMPLATE, {
51277
+ SCHEDULES_SKILL_HINT: skillsAvailable ? BRIDGE_SKILL_HINTS.SCHEDULES_SKILL_HINT : ".",
51278
+ TASKS_SKILL_HINT: skillsAvailable ? BRIDGE_SKILL_HINTS.TASKS_SKILL_HINT : ""
51279
+ });
51280
+ }
51281
+ function renderPlatformReferenceGuide(skillsAvailable) {
51282
+ return renderTemplate(REFERENCE_GUIDE_TEMPLATE, {
51283
+ PLATFORM_SKILL_HINT: skillsAvailable ? BRIDGE_SKILL_HINTS.PLATFORM_SKILL_HINT : ""
51284
+ });
51285
+ }
51286
+ var PLATFORM_BEHAVIOR = renderPlatformBehavior(true);
51287
+ var PLATFORM_REFERENCE_GUIDE = renderPlatformReferenceGuide(true);
51288
+ function renderPlatformIdentity(agent) {
51289
+ if (!agent)
51290
+ return PLATFORM_IDENTITY_BASE;
51291
+ const publicLines = [];
51292
+ const title = agent.title ? sanitizeProfileField(agent.title) : "";
51293
+ if (title)
51294
+ publicLines.push(`Title: ${title}`);
51295
+ const about = agent.publicDescription ? sanitizeProfileField(agent.publicDescription) : "";
51296
+ if (about)
51297
+ publicLines.push(`About: ${about}`);
51298
+ const instructions = sanitizeProfileBlock(agent.instructions || agent.description || "");
51299
+ const suffix = renderTemplate(IDENTITY_PROFILE_SUFFIX, {
51300
+ DISPLAY_NAME: sanitizeProfileField(agent.displayName),
51301
+ USER_ID: agent.userId,
51302
+ PUBLIC_PROFILE: publicLines.length > 0 ? `
51303
+ ${publicLines.join("\n")}` : "",
51304
+ INSTRUCTIONS_SECTION: instructions ? `
51305
+
51306
+ ### Private instructions from your organization admins
51307
+
51308
+ ${instructions}` : ""
51309
+ });
51310
+ return `${PLATFORM_IDENTITY_BASE}
51311
+
51312
+ ${suffix}`;
51313
+ }
51314
+ function renderPlatformInstructions(options) {
51315
+ const skillsAvailable = options.skillsAvailable !== false;
51316
+ const parts = [renderPlatformIdentity(options.identity)];
51317
+ if (options.runtimeAppendix !== void 0)
51318
+ parts.push(options.runtimeAppendix);
51319
+ parts.push(renderPlatformBehavior(skillsAvailable), renderPlatformReferenceGuide(skillsAvailable));
51320
+ if (options.capabilityFragments && options.capabilityFragments.length > 0) {
51321
+ parts.push(options.capabilityFragments.join("\n\n"));
51322
+ }
51323
+ if (options.skillReferences !== void 0)
51324
+ parts.push(options.skillReferences);
51325
+ return parts.join("\n\n");
51326
+ }
51327
+
51328
+ // ts/agent-core/dist/bridge-workspace.js
51329
+ function extractShellCommand(input) {
51330
+ if (!input || typeof input !== "object")
51331
+ return void 0;
51332
+ const command = input.command;
51333
+ return typeof command === "string" && command.trim() ? command.trim() : void 0;
51334
+ }
51335
+ function parseParallCliInvocation(command) {
51336
+ const tokens = command.replace(/\s+/g, " ").trim().split(" ");
51337
+ let i = 0;
51338
+ if (tokens[i] === "parall") {
51339
+ i++;
51340
+ } else if (tokens[i] === "npx") {
51341
+ i++;
51342
+ while (i < tokens.length && tokens[i].startsWith("-"))
51343
+ i++;
51344
+ if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
51345
+ return null;
51346
+ i++;
51347
+ } else if (tokens[i] === "pnpm") {
51348
+ i++;
51349
+ if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
51350
+ i++;
51351
+ if (i >= tokens.length || tokens[i] !== "parall")
51352
+ return null;
51353
+ i++;
51354
+ } else {
51355
+ return null;
51356
+ }
51357
+ return tokens.slice(i).filter((t) => !t.startsWith("-"));
51358
+ }
51359
+ function isParallSendCommand(command) {
51360
+ if (!command)
51361
+ return false;
51362
+ const sub = parseParallCliInvocation(command);
51363
+ if (!sub || sub.length === 0)
51364
+ return false;
51365
+ return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
51366
+ }
51367
+ function isParallNoReplyCommand(command) {
51368
+ if (!command)
51369
+ return false;
51370
+ const sub = parseParallCliInvocation(command);
51371
+ return sub?.[0] === "no-reply";
51372
+ }
51373
+
51374
+ // ts/agent-core/dist/channel-capability.js
51375
+ import * as fs from "node:fs";
51376
+ import * as path from "node:path";
51377
+ import { fileURLToPath } from "node:url";
51378
+ var CAPABILITY_FEISHU_CLI = "feishu-cli";
51379
+ var CAPABILITY_SLACK_SEND = "slack-send";
51380
+ var CAPABILITY_WECHAT_SEND = "wechat-send";
51381
+ function channelCapabilityKeyFor(provider) {
51382
+ if (provider === "slack")
51383
+ return CAPABILITY_SLACK_SEND;
51384
+ if (provider === "wechat")
51385
+ return CAPABILITY_WECHAT_SEND;
51386
+ return `${provider}-cli`;
51387
+ }
51388
+ var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
51389
+ function capabilityBinDir(stateDir) {
51390
+ return path.join(stateDir, "bin");
51391
+ }
51392
+ function channelExecEntryPath() {
51393
+ const selfDir = path.dirname(fileURLToPath(import.meta.url));
51394
+ const sibling = path.join(selfDir, "parall-channel-exec.js");
51395
+ if (fs.existsSync(sibling))
51396
+ return sibling;
51397
+ return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
51398
+ }
51399
+ function materializeChannelCapabilities(stateDir, capabilities, log2) {
51400
+ try {
51401
+ reconcileFeishuCli(stateDir, capabilities, log2);
51402
+ } catch (err) {
51403
+ log2?.warn(`channel capability materialization failed: ${String(err)}`);
51404
+ }
51405
+ }
51406
+ function reconcileFeishuCli(stateDir, capabilities, log2) {
51407
+ const binDir = capabilityBinDir(stateDir);
51408
+ const posixPath = path.join(binDir, "lark-cli");
51409
+ const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
51410
+ const hadPointer = fs.existsSync(posixPath);
51411
+ if (!granted && !hadPointer)
51412
+ return;
51413
+ fs.mkdirSync(binDir, { recursive: true });
51414
+ const entry = channelExecEntryPath();
51415
+ const nodeExec = process.execPath;
51416
+ writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log2);
51417
+ writePointerIfChanged(path.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log2);
51418
+ }
51419
+ function writePointerIfChanged(filePath, content, log2) {
51420
+ let existing = null;
51421
+ try {
51422
+ existing = fs.readFileSync(filePath, "utf8");
51423
+ } catch {
51424
+ existing = null;
51425
+ }
51426
+ if (existing !== content) {
51427
+ fs.writeFileSync(filePath, content, { mode: 493 });
51428
+ log2?.info(`channel capability: pointer materialized (${path.basename(filePath)})`);
51429
+ }
51430
+ fs.chmodSync(filePath, 493);
51431
+ }
51432
+ function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
51433
+ return [
51434
+ "#!/bin/sh",
51435
+ `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
51436
+ "# Credential + exec logic lives in the agent-core package; revocation is",
51437
+ "# enforced by the platform mint endpoint, so this pointer stays constant.",
51438
+ // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
51439
+ // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
51440
+ // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
51441
+ // the mint. The pointer is a platform-authored trust-boundary artifact whose
51442
+ // whole job is a CONTROLLED launch of the broker (absolute node, magic
51443
+ // guard, skip-dir); this closes the same env-hijack class for node startup
51444
+ // that the absolute node path closes for PATH, keeping the launch deterministic.
51445
+ "unset NODE_OPTIONS NODE_PATH",
51446
+ // "$@" preserves argv exactly (this is the agent's main path via git-bash).
51447
+ `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
51448
+ ""
51449
+ ].join("\n");
51450
+ }
51451
+ function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
51452
+ return [
51453
+ "@echo off",
51454
+ `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
51455
+ // Clear Node preload-hijack vars before launching node (see the sh pointer).
51456
+ 'set "NODE_OPTIONS="',
51457
+ 'set "NODE_PATH="',
51458
+ `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
51459
+ ""
51460
+ ].join("\r\n");
51461
+ }
51462
+
51463
+ // ts/agent-core/dist/dispatch-adapter.js
51464
+ function buildErrorStepContent(message) {
51465
+ return { text: message, suppressed: false, status: "error" };
51466
+ }
51467
+
51468
+ // ts/agent-core/dist/event-format.js
51469
+ function sanitizeMeta(value) {
51470
+ return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
51471
+ }
51472
+ function buildEventBody(event) {
51473
+ const lines = [];
51474
+ if (event.type === "message") {
51475
+ lines.push(`[Event: message.new]`);
51476
+ const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
51477
+ lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
51478
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51479
+ lines.push(`[Message ID: prll://${event.messageId}]`);
51480
+ if (event.threadRootId) {
51481
+ const threadMeta = [
51482
+ `prll://${event.threadRootId}`,
51483
+ event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
51484
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
51485
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
51486
+ ].filter(Boolean).join(" | ");
51487
+ lines.push(`[Thread: ${threadMeta}]`);
51488
+ }
51489
+ if (event.unreadCount != null && event.unreadCount > 1) {
51490
+ const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
51491
+ const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
51492
+ let line = `[Unread: ${countStr} messages${sinceStr}]`;
51493
+ if (event.unreadCount > 50)
51494
+ line += ` \u2014 fetch recent context with --limit, not all`;
51495
+ lines.push(line);
51496
+ }
51497
+ if (event.noReply)
51498
+ lines.push(`[Hint: no_reply]`);
51499
+ if (event.attachments?.length) {
51500
+ for (const att of event.attachments) {
51501
+ const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
51502
+ lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
51503
+ }
51504
+ }
51505
+ lines.push("", event.body);
51506
+ } else if (event.type === "task_comment") {
51507
+ lines.push(`[Event: task.comment.created]`);
51508
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
51509
+ lines.push(`[Task: ${taskLabel}]`);
51510
+ if (event.deliveryReason)
51511
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51512
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51513
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
51514
+ lines.push("", event.body);
51515
+ } else if (event.type === "wiki_comment") {
51516
+ lines.push(`[Event: wiki.comment.created]`);
51517
+ const target = event.replyTargetUri ?? `prll://${event.targetId}`;
51518
+ if (event.targetType === "changeset") {
51519
+ lines.push(`[Wiki Changeset: ${target}]`);
51520
+ } else {
51521
+ lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
51522
+ }
51523
+ if (event.deliveryReason)
51524
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51525
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51526
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
51527
+ lines.push("", event.body);
51528
+ } else if (event.type === "approval") {
51529
+ lines.push(`[Event: approval.decided]`);
51530
+ lines.push(`[Approval: prll://${event.messageId}]`);
51531
+ lines.push(`[Chat: prll://${event.targetId}]`);
51532
+ lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
51533
+ lines.push("", event.body);
51534
+ } else if (event.type === "schedule") {
51535
+ lines.push(`[Event: schedule.fired]`);
51536
+ lines.push(`[Schedule: prll://${event.targetId}]`);
51537
+ lines.push(`[Run: prll://${event.messageId}]`);
51538
+ if (event.scheduledFireAt)
51539
+ lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
51540
+ if (event.attachedUri)
51541
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
51542
+ lines.push("", event.body);
51543
+ } else if (event.type === "channel_message") {
51544
+ lines.push(`[Event: channel.message]`);
51545
+ const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
51546
+ const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
51547
+ lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
51548
+ lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
51549
+ if (event.channelExternalMessageId) {
51550
+ lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
51551
+ }
51552
+ lines.push(`[Audience: this conversation lives on ${providerLabel}, OUTSIDE Parall. Readers cannot open prll:// links, Parall cards, or internal attachments \u2014 never include them in replies. Write plain conversational text.]`);
51553
+ lines.push("", event.body);
51554
+ } else if (event.type === "external_trigger") {
51555
+ lines.push(`[Event: external.trigger]`);
51556
+ lines.push(`[Trigger: prll://${event.targetId}]`);
51557
+ lines.push(`[Run: prll://${event.messageId}]`);
51558
+ if (event.externalConnectionId) {
51559
+ const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
51560
+ lines.push(`[Connection: ${label}]`);
51561
+ }
51562
+ if (event.externalIngressEventId)
51563
+ lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
51564
+ if (event.attachedUri)
51565
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
51566
+ if (event.externalConnectionSourceType) {
51567
+ lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
51568
+ }
51569
+ if (event.externalIngressEventType) {
51570
+ lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
51571
+ }
51572
+ lines.push("", event.body);
51573
+ } else {
51574
+ lines.push(`[Event: task.assigned]`);
51575
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
51576
+ lines.push(`[Task: ${taskLabel}]`);
51577
+ lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
51578
+ lines.push("", event.body);
51579
+ }
51580
+ return lines.join("\n") + buildSendMessageHint(event);
51581
+ }
51582
+ function buildEventBodyForForkResult(event) {
51583
+ return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
51584
+ }
51585
+ function buildSendMessageHint(event) {
51586
+ if (event.noReply)
51587
+ return "";
51588
+ if (event.type === "wiki_comment" && event.replyTargetUri) {
51589
+ const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
51590
+ return `
51591
+ <system-reminder>To reply on ${where}, run: \`parall comments add --target "${event.replyTargetUri}" --body "..."\` (read the thread first with \`parall comments list --target "${event.replyTargetUri}"\`). To message someone instead, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
51592
+ }
51593
+ if (event.targetId.startsWith("cht_")) {
51594
+ if (event.threadRootId) {
51595
+ return `
51596
+ <system-reminder>To reply in this thread, run \`parall messages send prll://${event.targetId} --thread-root-id ${sanitizeMeta(event.threadRootId)} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
51597
+ }
51598
+ return `
51599
+ <system-reminder>To reply, run \`parall messages send prll://${event.targetId} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
51600
+ }
51601
+ if (event.targetId.startsWith("tsk_")) {
51602
+ return `
51603
+ <system-reminder>To respond, use the CLI: \`parall tasks update\` / \`parall tasks comments add\`. To message someone, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
51604
+ }
51605
+ if (event.targetId.startsWith("sch_")) {
51606
+ return `
51607
+ <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
51608
+ }
51609
+ if (event.type === "channel_message") {
51610
+ if (event.channelCliCapable) {
51611
+ if (event.channelProvider === "slack") {
51612
+ const channelArg = event.channelExternalConversationId ? ` --channel "${event.channelExternalConversationId}"` : " --channel <conversation id from this event>";
51613
+ const replyTo = event.channelExternalMessageId ? ` --reply-to "${event.channelExternalMessageId}"` : "";
51614
+ return `
51615
+ <system-reminder>To reply, use the platform verb: \`parall slack send${channelArg}${replyTo} --text <your reply>\`. In channels --reply-to is REQUIRED (the reply lands in that message's thread); in DMs it is optional (DMs are linear). \`parall slack send\` is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
51616
+ }
51617
+ if (event.channelProvider === "wechat") {
51618
+ const toArg = event.channelExternalConversationId ? ` --to "${event.channelExternalConversationId}"` : " --to <wxid from this event>";
51619
+ const atArg = event.channelConversationType === "group" ? event.senderId && event.senderId !== "external" ? ` --at "${event.senderId}"` : " --at <wxid of the person you are answering>" : "";
51620
+ return `
51621
+ <system-reminder>To reply, use the platform verb: \`parall wechat send${toArg}${atArg} --text-file - <<'EOF'\` \u2026 \`EOF\` (or --text "<short text>" for simple literals \u2014 the quoted heredoc keeps $, backticks and apostrophes literal). In group chats, --at @-mentions the person you are answering. \`parall wechat send\` is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
51622
+ }
51623
+ if (!event.channelProvider) {
51624
+ return `
51625
+ <system-reminder>To reply, use the channel capability granted in your system prompt \u2014 for Feishu conversations that is \`lark-cli im\`, for Slack it is \`parall slack send\` (pass the message id from this event as --reply-to), for WeChat it is \`parall wechat send\`. That capability is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
51626
+ }
51627
+ const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
51628
+ const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
51629
+ return `
51630
+ <system-reminder>To reply, use the official Feishu CLI on your PATH: send a message to ${convRef} with \`lark-cli im\` (see \`lark-cli im --help\` for send syntax; auth is provisioned automatically).${threadAlt} lark-cli is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
51631
+ }
51632
+ const platform = event.channelProvider ?? "the external platform";
51633
+ return `
51634
+ <system-reminder>This message arrived from ${platform}, but outbound replies are currently disabled for this org (no channel capability granted). Do NOT attempt to reply on the external platform. If action is needed, surface it inside Parall (\`parall messages send\` / \`parall dm\`). Your plain text output is not delivered anywhere.</system-reminder>`;
51259
51635
  }
51260
- return "";
51261
- }
51262
- function clearAllProviderCreds(env) {
51263
- delete env.ANTHROPIC_AUTH_TOKEN;
51264
- delete env.ANTHROPIC_BASE_URL;
51265
- delete env.ANTHROPIC_API_KEY;
51266
- delete env.OPENAI_API_KEY;
51267
- delete env.OPENAI_BASE_URL;
51268
- delete env.PRLL_CLAUDE_ALLOW_API_KEY;
51269
- }
51270
- function parseProviderConfig(env) {
51271
- const raw = env.PRLL_PROVIDER_CONFIG?.trim();
51272
- if (!raw)
51273
- return void 0;
51274
- try {
51275
- return JSON.parse(raw);
51276
- } catch (err) {
51277
- throw new Error(`Invalid PRLL_PROVIDER_CONFIG JSON: ${String(err)}`);
51636
+ if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
51637
+ return `
51638
+ <system-reminder>This external trigger is incoming-only. Your plain text output is not sent back to the external provider. To communicate in Parall, use \`parall messages send\` / \`parall dm\`; provider-specific outbound actions require a separate capability.</system-reminder>`;
51278
51639
  }
51640
+ return "";
51279
51641
  }
51642
+ function buildForkScopePrefix(event) {
51643
+ const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
51644
+ return `[Fork scope: You are a parallel worker forked from the main session to handle ${targetLabel}. The conversation history above belongs to the main session's in-progress dispatch \u2014 do NOT continue it or complete it, or produce external output (comments, messages) for work visible there. The main session owns its own output.
51280
51645
 
51281
- // ts/agent-core/dist/lane-key.js
51282
- import * as path from "node:path";
51283
- function laneKeyForTarget(targetUri, threadRootId) {
51284
- return Buffer.from(`${targetUri}
51285
- ${threadRootId ?? ""}`, "utf8").toString("base64url");
51286
- }
51287
- function dispatchLaneContextDir(stateDir) {
51288
- return path.join(stateDir, "dispatch-lane-context");
51646
+ Only act on the event below within your target scope. If your event reveals findings about the main session's work, report them in your summary \u2014 do not post them externally.
51647
+
51648
+ End with a brief "Fork summary" of actions taken and decisions made.]
51649
+
51650
+ `;
51289
51651
  }
51290
- function laneContextFilePath(contextDir, targetUri, threadRootId) {
51291
- return path.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
51652
+ function buildForkResultPrefix(results) {
51653
+ if (!results.length)
51654
+ return "";
51655
+ const blocks = results.map((result) => {
51656
+ const lines = [];
51657
+ for (const body of result.eventBodies) {
51658
+ lines.push(body);
51659
+ }
51660
+ lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
51661
+ lines.push(`[Fork summary: ${result.agentSummary ? sanitizeMeta(result.agentSummary) : "No fork summary available \u2014 the fork completed without producing a text summary. Check the target chat/task for any actions the fork already took before acting."}]`);
51662
+ if (result.actions.length)
51663
+ lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
51664
+ if (result.historyPath)
51665
+ lines.push(`[Fork history: ${result.historyPath}]`);
51666
+ return lines.join("\n");
51667
+ });
51668
+ return blocks.join("\n\n") + "\n\n---\n\n";
51292
51669
  }
51293
51670
 
51671
+ // ts/agent-core/dist/gateway-base.js
51672
+ import * as os from "node:os";
51673
+ import * as fs3 from "node:fs";
51674
+ import * as path3 from "node:path";
51675
+ import { randomUUID } from "node:crypto";
51676
+
51294
51677
  // ts/sdk/dist/browser-viewer.js
51295
51678
  var BROWSER_VIEWER_READINESS_TIMEOUT_MS = 6e4;
51296
51679
  function browserViewerRequestOptions(command, opts) {
@@ -51332,6 +51715,9 @@ var ENDPOINTS = {
51332
51715
  ORG_MEMBERS: (orgId) => `${API_BASE}/orgs/${orgId}/members`,
51333
51716
  ORG_MEMBERS_FORMER: (orgId) => `${API_BASE}/orgs/${orgId}/members/former`,
51334
51717
  TEAMS: (orgId) => `${API_BASE}/orgs/${orgId}/teams`,
51718
+ TEAM: (orgId, teamId) => `${API_BASE}/orgs/${orgId}/teams/${teamId}`,
51719
+ TEAM_MEMBERS: (orgId, teamId) => `${API_BASE}/orgs/${orgId}/teams/${teamId}/members`,
51720
+ TEAM_MEMBER: (orgId, teamId, userId) => `${API_BASE}/orgs/${orgId}/teams/${teamId}/members/${userId}`,
51335
51721
  ORG_MEMBERS_ONLINE: (orgId) => `${API_BASE}/orgs/${orgId}/members/online`,
51336
51722
  ORG_MEMBER: (orgId, userId) => `${API_BASE}/orgs/${orgId}/members/${userId}`,
51337
51723
  ORG_MEMBER_CHATS: (orgId, memberId) => `${API_BASE}/orgs/${orgId}/members/${memberId}/chats`,
@@ -51454,6 +51840,7 @@ var ENDPOINTS = {
51454
51840
  MACHINES_ME_BROWSER_PROFILE_VIEWER_RESPONSE: (requestId) => `${API_BASE}/machines/me/browser-profiles/viewer-response/${requestId}`,
51455
51841
  // Tasks (org-scoped)
51456
51842
  TASKS: (orgId) => `${API_BASE}/orgs/${orgId}/tasks`,
51843
+ TASK_SUBTASK_SUMMARY: (orgId) => `${API_BASE}/orgs/${orgId}/tasks/subtask-summary`,
51457
51844
  TASK: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}`,
51458
51845
  TASK_ARCHIVE: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/archive`,
51459
51846
  TASK_RESTORE: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/restore`,
@@ -51467,8 +51854,14 @@ var ENDPOINTS = {
51467
51854
  TASK_COMMENTS: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/comments`,
51468
51855
  TASK_COMMENT: (orgId, taskId, commentId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/comments/${commentId}`,
51469
51856
  TASK_ACTIVITIES: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/activities`,
51857
+ TASK_LABELS: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/labels`,
51858
+ TASK_LABEL: (orgId, taskId, labelId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/labels/${labelId}`,
51859
+ // Labels (org-scoped vocabulary; writes are admin-gated)
51860
+ LABELS: (orgId) => `${API_BASE}/orgs/${orgId}/labels`,
51861
+ LABEL: (orgId, labelId) => `${API_BASE}/orgs/${orgId}/labels/${labelId}`,
51470
51862
  // Projects (org-scoped)
51471
51863
  PROJECTS: (orgId) => `${API_BASE}/orgs/${orgId}/projects`,
51864
+ PROJECT_TASK_SUMMARY: (orgId) => `${API_BASE}/orgs/${orgId}/projects/task-summary`,
51472
51865
  PROJECT: (orgId, projectId) => `${API_BASE}/orgs/${orgId}/projects/${projectId}`,
51473
51866
  // Schedules (org-scoped, platform time trigger primitive)
51474
51867
  SCHEDULES: (orgId) => `${API_BASE}/orgs/${orgId}/schedules`,
@@ -51511,8 +51904,10 @@ var ENDPOINTS = {
51511
51904
  SLACK_HISTORY: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/slack/history`,
51512
51905
  SLACK_MEMBERS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/slack/members`,
51513
51906
  SLACK_STATUS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/slack/status`,
51514
- // WeChat tier-B read verb (agent-only; internal research preview).
51907
+ // WeChat tier-B read verbs (agent-only; internal research preview).
51515
51908
  WECHAT_CONTACTS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/contacts`,
51909
+ WECHAT_PROFILE: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/profile`,
51910
+ WECHAT_STATUS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/status`,
51516
51911
  // Invitations (org-scoped, admin)
51517
51912
  ORG_INVITATIONS: (orgId) => `${API_BASE}/orgs/${orgId}/invitations`,
51518
51913
  ORG_INVITATION: (orgId, invId) => `${API_BASE}/orgs/${orgId}/invitations/${invId}`,
@@ -51626,8 +52021,10 @@ var ENDPOINTS = {
51626
52021
  NOTIFICATION_PREFERENCES: `${API_BASE}/notification-preferences`,
51627
52022
  // Unified search (messages + tasks + wiki, org-scoped)
51628
52023
  SEARCH: (orgId) => `${API_BASE}/orgs/${orgId}/search`,
51629
- // Feature flags (org-scoped, server-evaluated)
51630
- FEATURE_FLAGS: (orgId) => `${API_BASE}/orgs/${orgId}/feature-flags`,
52024
+ // Feature flags (server-evaluated). Org-scoped by default; omit the org for
52025
+ // the pre-org form, which resolves "cap:" capabilities only (PostHog flags
52026
+ // are org-scoped and absent there) for callers that have no org yet.
52027
+ FEATURE_FLAGS: (orgId) => orgId ? `${API_BASE}/orgs/${orgId}/feature-flags` : `${API_BASE}/feature-flags`,
51631
52028
  // Team templates (org-scoped, owner/admin only)
51632
52029
  TEMPLATES: (orgId) => `${API_BASE}/orgs/${orgId}/templates`,
51633
52030
  TEMPLATE: (orgId, templateId) => `${API_BASE}/orgs/${orgId}/templates/${templateId}`,
@@ -51697,103 +52094,255 @@ var ENDPOINTS = {
51697
52094
  ORG_CLIP_INSTALL: (orgId) => `/api/v1/orgs/${orgId}/clips/install`,
51698
52095
  ORG_CLIPS_INSTALLED: (orgId) => `/api/v1/orgs/${orgId}/clips/installed`,
51699
52096
  ORG_CLIP_UNINSTALL: (orgId, clipId) => `/api/v1/orgs/${orgId}/clips/${clipId}/uninstall`,
52097
+ ORG_CLIP_MCP_REMOVE: (orgId, clipId) => `/api/v1/orgs/${orgId}/clips/${clipId}/mcp-remove`,
51700
52098
  // Per-org agent exec access for one clip (default all agents; PUT human-only)
51701
52099
  ORG_CLIP_EXEC_ACCESS: (orgId, clipId) => `/api/v1/orgs/${orgId}/clips/${clipId}/exec-access`,
51702
- // MCP clip server config (cap:clip-mcp; publisher-org only cross-org gets
51703
- // 403 MCP_CROSS_ORG_DISABLED on the whole family, reads included)
52100
+ // MCP clip server config (cap:clip-mcp; cross-org is limited to installed,
52101
+ // reviewed Official OAuth Clips). The
52102
+ // singular family addresses the org's DEFAULT connection (pre-165
52103
+ // back-compat shim); the plural family is the multi-connection surface —
52104
+ // one config row (credential slot) per connection, addressed by config id.
51704
52105
  ORG_CLIP_MCP_CONFIG: (orgId, clipId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-config`,
51705
52106
  ORG_CLIP_MCP_TOOLS_REFRESH: (orgId, clipId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-config/tools/refresh`,
51706
- ORG_CLIP_MCP_OAUTH_DISCONNECT: (orgId, clipId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-config/oauth/disconnect`
52107
+ ORG_CLIP_MCP_OAUTH_DISCONNECT: (orgId, clipId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-config/oauth/disconnect`,
52108
+ ORG_CLIP_MCP_CONFIGS: (orgId, clipId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-configs`,
52109
+ ORG_CLIP_MCP_CONFIG_BY_ID: (orgId, clipId, configId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-configs/${configId}`,
52110
+ ORG_CLIP_MCP_TOOLS_REFRESH_BY_ID: (orgId, clipId, configId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-configs/${configId}/tools/refresh`,
52111
+ ORG_CLIP_MCP_OAUTH_DISCONNECT_BY_ID: (orgId, clipId, configId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-configs/${configId}/oauth/disconnect`
52112
+ };
52113
+ var WS_EVENTS = {
52114
+ // Client -> Server
52115
+ PING: "ping",
52116
+ TYPING: "typing",
52117
+ WATCH: "watch",
52118
+ AGENT_HEARTBEAT: "agent.heartbeat",
52119
+ // Server -> Client
52120
+ HELLO: "hello",
52121
+ PONG: "pong",
52122
+ WATCHING: "watching",
52123
+ MESSAGE_NEW: "message.new",
52124
+ MESSAGE_PATCH: "message.patch",
52125
+ MESSAGE_EDIT: "message.edit",
52126
+ MESSAGE_DELETE: "message.delete",
52127
+ MESSAGE_REACTION_UPDATED: "message.reaction.updated",
52128
+ TYPING_UPDATE: "typing.update",
52129
+ CHAT_UPDATE: "chat.update",
52130
+ CHAT_DELETED: "chat.deleted",
52131
+ APPROVAL_UPDATE: "approval.update",
52132
+ // deprecated
52133
+ CARD_UPDATE: "card.update",
52134
+ RECOVERY_OVERFLOW: "recovery.overflow",
52135
+ MEMBERSHIP_CHANGED: "membership.changed",
52136
+ TASK_CREATED: "task.created",
52137
+ TASK_UPDATED: "task.updated",
52138
+ TASK_DELETED: "task.deleted",
52139
+ TASK_COMMENT_CREATED: "task.comment.created",
52140
+ TASK_COMMENT_UPDATED: "task.comment.updated",
52141
+ TASK_COMMENT_DELETED: "task.comment.deleted",
52142
+ PROJECT_CREATED: "project.created",
52143
+ PROJECT_UPDATED: "project.updated",
52144
+ PROJECT_DELETED: "project.deleted",
52145
+ LABEL_CREATED: "label.created",
52146
+ LABEL_UPDATED: "label.updated",
52147
+ LABEL_DELETED: "label.deleted",
52148
+ AGENT_SESSION_NEW: "agent_session.new",
52149
+ AGENT_SESSION_UPDATE: "agent_session.update",
52150
+ AGENT_STEP_NEW: "agent_step.new",
52151
+ INVITATION_NEW: "invitation.new",
52152
+ INVITATION_ACCEPTED: "invitation.accepted",
52153
+ INVITATION_DECLINED: "invitation.declined",
52154
+ INVITATION_REVOKED: "invitation.revoked",
52155
+ ORG_JOIN_REQUEST_NEW: "org.join_request.new",
52156
+ ORG_INVITE_LINK_JOINED: "org.invite_link.joined",
52157
+ ORG_MEMBER_REMOVED: "org.member.removed",
52158
+ ORG_MEMBER_PROFILE_UPDATED: "org.member.profile.updated",
52159
+ AGENT_CONFIG_UPDATE: "agent_config.update",
52160
+ PRESENCE_UPDATE: "presence.update",
52161
+ WIKI_CHANGESET_CREATED: "wiki.changeset.created",
52162
+ WIKI_CHANGESET_UPDATED: "wiki.changeset.updated",
52163
+ WIKI_DELETED: "wiki.deleted",
52164
+ WIKI_RESTORED: "wiki.restored",
52165
+ COMMENT_CREATED: "comment.created",
52166
+ COMMENT_UPDATED: "comment.updated",
52167
+ COMMENT_DELETED: "comment.deleted",
52168
+ NOTIFICATION_ALERT: "notification.alert",
52169
+ INBOX_NEW: "inbox.new",
52170
+ INBOX_UPDATE: "inbox.update",
52171
+ INBOX_BULK_UPDATE: "inbox.bulk_update",
52172
+ READ_POSITION_UPDATED: "read_position.updated",
52173
+ THREAD_READ_POSITION_UPDATED: "thread_read_position.updated",
52174
+ DISPATCH_NEW: "dispatch.new",
52175
+ DISPATCH_RECEIVED: "dispatch.received",
52176
+ DISPATCH_RESOLVED: "dispatch.resolved",
52177
+ SCHEDULE_CREATED: "schedule.created",
52178
+ SCHEDULE_UPDATED: "schedule.updated",
52179
+ SCHEDULE_DELETED: "schedule.deleted",
52180
+ SCHEDULE_FIRED: "schedule.fired",
52181
+ BILLING_BALANCE_UPDATED: "billing.balance_updated",
52182
+ BILLING_LOW_BALANCE: "billing.low_balance",
52183
+ BILLING_MACHINE_STOPPED: "billing.machine_stopped",
52184
+ BILLING_INSUFFICIENT: "billing.insufficient",
52185
+ USER_UPDATED: "user.updated",
52186
+ MACHINE_HELLO: "machine.hello",
52187
+ MACHINE_AGENT_ATTACHED: "machine.agent.attached",
52188
+ MACHINE_AGENT_DETACHED: "machine.agent.detached",
52189
+ MACHINE_STOP: "machine.stop",
52190
+ MACHINE_WORKSPACE_SETUP_REQUESTED: "machine.workspace.setup.requested",
52191
+ MACHINE_FILESYSTEM_BROWSE: "machine.filesystem.browse",
52192
+ MACHINE_UPDATE: "machine.update",
52193
+ MACHINE_CONFIG_UPDATED: "machine.config.updated",
52194
+ MACHINE_AGENT_CONFIG_UPDATED: "machine.agent_config.updated",
52195
+ MACHINE_CLIP_SYNC: "machine.clip.sync",
52196
+ MACHINE_BROWSER_PROFILE_LIFECYCLE: "machine.browser_profile.lifecycle",
52197
+ MACHINE_BROWSER_PROFILE_VIEWER: "machine.browser_profile.viewer",
52198
+ AGENT_NEW_SESSION: "agent.new_session",
52199
+ CLIP_CREATED: "clip.created",
52200
+ CLIP_REMOVED: "clip.removed",
52201
+ CLIP_UPDATED: "clip.updated"
52202
+ };
52203
+
52204
+ // ts/sdk/dist/project-task-client.js
52205
+ var ProjectTaskClient = class {
52206
+ async createTask(orgId, data) {
52207
+ return this.request("POST", ENDPOINTS.TASKS(orgId), data);
52208
+ }
52209
+ async getTasks(orgId, params) {
52210
+ return this.request("GET", ENDPOINTS.TASKS(orgId), void 0, params);
52211
+ }
52212
+ async getTaskSubtaskSummary(orgId, params) {
52213
+ return this.request("GET", ENDPOINTS.TASK_SUBTASK_SUMMARY(orgId), void 0, params);
52214
+ }
52215
+ async getTask(orgId, taskId) {
52216
+ return this.request("GET", ENDPOINTS.TASK(orgId, taskId));
52217
+ }
52218
+ async updateTask(orgId, taskId, data) {
52219
+ return this.request("PATCH", ENDPOINTS.TASK(orgId, taskId), data);
52220
+ }
52221
+ async deleteTask(orgId, taskId, opts) {
52222
+ return this.request("DELETE", ENDPOINTS.TASK(orgId, taskId), void 0, opts?.force ? { force: "true" } : void 0);
52223
+ }
52224
+ async archiveTask(orgId, taskId) {
52225
+ return this.request("POST", ENDPOINTS.TASK_ARCHIVE(orgId, taskId));
52226
+ }
52227
+ async restoreTask(orgId, taskId) {
52228
+ return this.request("POST", ENDPOINTS.TASK_RESTORE(orgId, taskId));
52229
+ }
52230
+ async watchTask(orgId, taskId) {
52231
+ return this.request("POST", ENDPOINTS.TASK_WATCH(orgId, taskId));
52232
+ }
52233
+ async unwatchTask(orgId, taskId) {
52234
+ return this.request("DELETE", ENDPOINTS.TASK_WATCH(orgId, taskId));
52235
+ }
52236
+ async getTaskWatchers(orgId, taskId) {
52237
+ const res = await this.request("GET", ENDPOINTS.TASK_WATCHERS(orgId, taskId));
52238
+ return res.data;
52239
+ }
52240
+ async subscribeTaskMember(orgId, taskId, userId) {
52241
+ return this.request("PUT", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52242
+ }
52243
+ async unsubscribeTaskMember(orgId, taskId, userId) {
52244
+ return this.request("DELETE", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52245
+ }
52246
+ async watchThread(threadRootId) {
52247
+ return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52248
+ }
52249
+ async unwatchThread(threadRootId) {
52250
+ return this.request("DELETE", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52251
+ }
52252
+ async getThreadWatchers(threadRootId) {
52253
+ const res = await this.request("GET", ENDPOINTS.MESSAGE_WATCHERS(threadRootId));
52254
+ return res.data;
52255
+ }
52256
+ async isWatchingThread(threadRootId) {
52257
+ const res = await this.request("GET", ENDPOINTS.MESSAGE_WATCHING(threadRootId));
52258
+ return res.watching;
52259
+ }
52260
+ async getSubtasks(orgId, taskId) {
52261
+ const res = await this.request("GET", ENDPOINTS.TASK_SUBTASKS(orgId, taskId));
52262
+ return res.data;
52263
+ }
52264
+ async createTaskRelation(orgId, taskId, data) {
52265
+ return this.request("POST", ENDPOINTS.TASK_RELATIONS(orgId, taskId), data);
52266
+ }
52267
+ async getTaskRelations(orgId, taskId) {
52268
+ const res = await this.request("GET", ENDPOINTS.TASK_RELATIONS(orgId, taskId));
52269
+ return res.data;
52270
+ }
52271
+ async listTaskRelationsByTarget(orgId, params) {
52272
+ const query = new URLSearchParams({
52273
+ target_type: params.target_type,
52274
+ target_id: params.target_id
52275
+ });
52276
+ const res = await this.request("GET", `${ENDPOINTS.TASK_RELATIONS_BY_TARGET(orgId)}?${query.toString()}`);
52277
+ return res.data;
52278
+ }
52279
+ async deleteTaskRelation(orgId, taskId, relationId) {
52280
+ return this.request("DELETE", ENDPOINTS.TASK_RELATION(orgId, taskId, relationId));
52281
+ }
52282
+ async getTaskComments(orgId, taskId, params) {
52283
+ return this.request("GET", ENDPOINTS.TASK_COMMENTS(orgId, taskId), void 0, params);
52284
+ }
52285
+ async getTaskComment(orgId, taskId, commentId) {
52286
+ return this.request("GET", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId));
52287
+ }
52288
+ async createTaskComment(orgId, taskId, data) {
52289
+ return this.request("POST", ENDPOINTS.TASK_COMMENTS(orgId, taskId), data);
52290
+ }
52291
+ async updateTaskComment(orgId, taskId, commentId, data) {
52292
+ return this.request("PATCH", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId), data);
52293
+ }
52294
+ async deleteTaskComment(orgId, taskId, commentId) {
52295
+ return this.request("DELETE", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId));
52296
+ }
52297
+ async getTaskActivities(orgId, taskId, params) {
52298
+ return this.request("GET", ENDPOINTS.TASK_ACTIVITIES(orgId, taskId), void 0, params);
52299
+ }
52300
+ async createProject(orgId, data) {
52301
+ return this.request("POST", ENDPOINTS.PROJECTS(orgId), data);
52302
+ }
52303
+ async getProjects(orgId) {
52304
+ const res = await this.request("GET", ENDPOINTS.PROJECTS(orgId));
52305
+ return res.data;
52306
+ }
52307
+ async getProjectTaskSummary(orgId) {
52308
+ return this.request("GET", ENDPOINTS.PROJECT_TASK_SUMMARY(orgId));
52309
+ }
52310
+ async getProject(orgId, projectId) {
52311
+ return this.request("GET", ENDPOINTS.PROJECT(orgId, projectId));
52312
+ }
52313
+ async updateProject(orgId, projectId, data) {
52314
+ return this.request("PATCH", ENDPOINTS.PROJECT(orgId, projectId), data);
52315
+ }
52316
+ async deleteProject(orgId, projectId) {
52317
+ return this.request("DELETE", ENDPOINTS.PROJECT(orgId, projectId));
52318
+ }
51707
52319
  };
51708
- var WS_EVENTS = {
51709
- // Client -> Server
51710
- PING: "ping",
51711
- TYPING: "typing",
51712
- WATCH: "watch",
51713
- AGENT_HEARTBEAT: "agent.heartbeat",
51714
- // Server -> Client
51715
- HELLO: "hello",
51716
- PONG: "pong",
51717
- WATCHING: "watching",
51718
- MESSAGE_NEW: "message.new",
51719
- MESSAGE_PATCH: "message.patch",
51720
- MESSAGE_EDIT: "message.edit",
51721
- MESSAGE_DELETE: "message.delete",
51722
- MESSAGE_REACTION_UPDATED: "message.reaction.updated",
51723
- TYPING_UPDATE: "typing.update",
51724
- CHAT_UPDATE: "chat.update",
51725
- CHAT_DELETED: "chat.deleted",
51726
- APPROVAL_UPDATE: "approval.update",
51727
- // deprecated
51728
- CARD_UPDATE: "card.update",
51729
- RECOVERY_OVERFLOW: "recovery.overflow",
51730
- MEMBERSHIP_CHANGED: "membership.changed",
51731
- TASK_CREATED: "task.created",
51732
- TASK_UPDATED: "task.updated",
51733
- TASK_DELETED: "task.deleted",
51734
- TASK_COMMENT_CREATED: "task.comment.created",
51735
- TASK_COMMENT_UPDATED: "task.comment.updated",
51736
- TASK_COMMENT_DELETED: "task.comment.deleted",
51737
- PROJECT_CREATED: "project.created",
51738
- PROJECT_UPDATED: "project.updated",
51739
- PROJECT_DELETED: "project.deleted",
51740
- AGENT_SESSION_NEW: "agent_session.new",
51741
- AGENT_SESSION_UPDATE: "agent_session.update",
51742
- AGENT_STEP_NEW: "agent_step.new",
51743
- INVITATION_NEW: "invitation.new",
51744
- INVITATION_ACCEPTED: "invitation.accepted",
51745
- INVITATION_DECLINED: "invitation.declined",
51746
- INVITATION_REVOKED: "invitation.revoked",
51747
- ORG_JOIN_REQUEST_NEW: "org.join_request.new",
51748
- ORG_INVITE_LINK_JOINED: "org.invite_link.joined",
51749
- ORG_MEMBER_REMOVED: "org.member.removed",
51750
- AGENT_CONFIG_UPDATE: "agent_config.update",
51751
- PRESENCE_UPDATE: "presence.update",
51752
- WIKI_CHANGESET_CREATED: "wiki.changeset.created",
51753
- WIKI_CHANGESET_UPDATED: "wiki.changeset.updated",
51754
- WIKI_DELETED: "wiki.deleted",
51755
- WIKI_RESTORED: "wiki.restored",
51756
- COMMENT_CREATED: "comment.created",
51757
- COMMENT_UPDATED: "comment.updated",
51758
- COMMENT_DELETED: "comment.deleted",
51759
- NOTIFICATION_ALERT: "notification.alert",
51760
- INBOX_NEW: "inbox.new",
51761
- INBOX_UPDATE: "inbox.update",
51762
- INBOX_BULK_UPDATE: "inbox.bulk_update",
51763
- READ_POSITION_UPDATED: "read_position.updated",
51764
- THREAD_READ_POSITION_UPDATED: "thread_read_position.updated",
51765
- DISPATCH_NEW: "dispatch.new",
51766
- DISPATCH_RECEIVED: "dispatch.received",
51767
- DISPATCH_RESOLVED: "dispatch.resolved",
51768
- SCHEDULE_CREATED: "schedule.created",
51769
- SCHEDULE_UPDATED: "schedule.updated",
51770
- SCHEDULE_DELETED: "schedule.deleted",
51771
- SCHEDULE_FIRED: "schedule.fired",
51772
- BILLING_BALANCE_UPDATED: "billing.balance_updated",
51773
- BILLING_LOW_BALANCE: "billing.low_balance",
51774
- BILLING_MACHINE_STOPPED: "billing.machine_stopped",
51775
- BILLING_INSUFFICIENT: "billing.insufficient",
51776
- USER_UPDATED: "user.updated",
51777
- MACHINE_HELLO: "machine.hello",
51778
- MACHINE_AGENT_ATTACHED: "machine.agent.attached",
51779
- MACHINE_AGENT_DETACHED: "machine.agent.detached",
51780
- MACHINE_STOP: "machine.stop",
51781
- MACHINE_WORKSPACE_SETUP_REQUESTED: "machine.workspace.setup.requested",
51782
- MACHINE_FILESYSTEM_BROWSE: "machine.filesystem.browse",
51783
- MACHINE_UPDATE: "machine.update",
51784
- MACHINE_CONFIG_UPDATED: "machine.config.updated",
51785
- MACHINE_AGENT_CONFIG_UPDATED: "machine.agent_config.updated",
51786
- MACHINE_CLIP_SYNC: "machine.clip.sync",
51787
- MACHINE_BROWSER_PROFILE_LIFECYCLE: "machine.browser_profile.lifecycle",
51788
- MACHINE_BROWSER_PROFILE_VIEWER: "machine.browser_profile.viewer",
51789
- AGENT_NEW_SESSION: "agent.new_session",
51790
- CLIP_CREATED: "clip.created",
51791
- CLIP_REMOVED: "clip.removed",
51792
- CLIP_UPDATED: "clip.updated"
52320
+
52321
+ // ts/sdk/dist/task-label-client.js
52322
+ var TaskLabelClient = class extends ProjectTaskClient {
52323
+ async getLabels(orgId) {
52324
+ const response = await this.request("GET", ENDPOINTS.LABELS(orgId));
52325
+ return response.data;
52326
+ }
52327
+ async createLabel(orgId, data) {
52328
+ return this.request("POST", ENDPOINTS.LABELS(orgId), data);
52329
+ }
52330
+ async updateLabel(orgId, labelId, data) {
52331
+ return this.request("PATCH", ENDPOINTS.LABEL(orgId, labelId), data);
52332
+ }
52333
+ async deleteLabel(orgId, labelId) {
52334
+ return this.request("DELETE", ENDPOINTS.LABEL(orgId, labelId));
52335
+ }
52336
+ async addTaskLabels(orgId, taskId, data) {
52337
+ return this.request("POST", ENDPOINTS.TASK_LABELS(orgId, taskId), data);
52338
+ }
52339
+ async removeTaskLabel(orgId, taskId, labelId) {
52340
+ return this.request("DELETE", ENDPOINTS.TASK_LABEL(orgId, taskId, labelId));
52341
+ }
51793
52342
  };
51794
52343
 
51795
52344
  // ts/sdk/dist/client.js
51796
- var ParallClient = class _ParallClient {
52345
+ var ParallClient = class _ParallClient extends TaskLabelClient {
51797
52346
  baseUrl;
51798
52347
  wikiBaseUrl;
51799
52348
  token;
@@ -51853,6 +52402,7 @@ var ParallClient = class _ParallClient {
51853
52402
  return headers;
51854
52403
  }
51855
52404
  constructor(options = {}) {
52405
+ super();
51856
52406
  this.baseUrl = options.baseUrl ?? "";
51857
52407
  this.wikiBaseUrl = options.wikiBaseUrl ?? this.baseUrl;
51858
52408
  this.token = options.token ?? null;
@@ -52150,6 +52700,44 @@ var ParallClient = class _ParallClient {
52150
52700
  const res = await this.request("GET", ENDPOINTS.TEAMS(orgId));
52151
52701
  return res.data;
52152
52702
  }
52703
+ async getTeam(orgId, teamId) {
52704
+ return this.request("GET", ENDPOINTS.TEAM(orgId, teamId));
52705
+ }
52706
+ /** Creating, renaming and deleting a team are org-admin actions. */
52707
+ async createTeam(orgId, req) {
52708
+ return this.request("POST", ENDPOINTS.TEAMS(orgId), req);
52709
+ }
52710
+ /**
52711
+ * Renames a team. The slug cannot be changed — wiki ACL rows reference it as
52712
+ * `@slug`, so the server answers 400 SLUG_IMMUTABLE if one is sent.
52713
+ */
52714
+ async updateTeam(orgId, teamId, req) {
52715
+ return this.request("PATCH", ENDPOINTS.TEAM(orgId, teamId), req);
52716
+ }
52717
+ async deleteTeam(orgId, teamId) {
52718
+ return this.request("DELETE", ENDPOINTS.TEAM(orgId, teamId));
52719
+ }
52720
+ /** Roster with display info; members who left the org are already excluded. */
52721
+ async getTeamMembers(orgId, teamId) {
52722
+ const res = await this.request("GET", ENDPOINTS.TEAM_MEMBERS(orgId, teamId));
52723
+ return res.data;
52724
+ }
52725
+ /**
52726
+ * Adds an org member (human or agent) to a team. Org admins and that team's
52727
+ * managers may add ordinary members; adding straight to `manager` is an
52728
+ * org-admin action.
52729
+ */
52730
+ async addTeamMember(orgId, teamId, req) {
52731
+ return this.request("POST", ENDPOINTS.TEAM_MEMBERS(orgId, teamId), req);
52732
+ }
52733
+ /** Appointing or demoting a manager is org-admin only. */
52734
+ async updateTeamMember(orgId, teamId, userId, req) {
52735
+ return this.request("PATCH", ENDPOINTS.TEAM_MEMBER(orgId, teamId, userId), req);
52736
+ }
52737
+ /** A team manager may remove ordinary members; removing a peer manager is org-admin only. */
52738
+ async removeTeamMember(orgId, teamId, userId) {
52739
+ return this.request("DELETE", ENDPOINTS.TEAM_MEMBER(orgId, teamId, userId));
52740
+ }
52153
52741
  async getOnlineMembers(orgId) {
52154
52742
  const res = await this.request("GET", ENDPOINTS.ORG_MEMBERS_ONLINE(orgId));
52155
52743
  return res.user_ids ?? [];
@@ -52925,144 +53513,33 @@ var ParallClient = class _ParallClient {
52925
53513
  // ---- Platform Config ----
52926
53514
  /**
52927
53515
  * Fetch platform config for the authenticated agent.
52928
- * Pass currentVersion to enable conditional fetch (If-None-Match / 304).
52929
- * Returns null when the server responds with 304 (config unchanged).
52930
- */
52931
- async getPlatformConfig(currentVersion) {
52932
- const url = `${this.baseUrlFor(ENDPOINTS.PLATFORM_CONFIG)}${ENDPOINTS.PLATFORM_CONFIG}`;
52933
- const extra = {};
52934
- if (currentVersion !== void 0) {
52935
- extra["If-None-Match"] = currentVersion;
52936
- }
52937
- const headers = this.buildHeaders(ENDPOINTS.PLATFORM_CONFIG, extra);
52938
- let res;
52939
- try {
52940
- res = await fetch(url, {
52941
- method: "GET",
52942
- headers,
52943
- signal: AbortSignal.timeout(15e3)
52944
- });
52945
- } catch (err) {
52946
- throw _ParallClient.normalizeFetchError(err);
52947
- }
52948
- if (res.status === 304)
52949
- return null;
52950
- if (!res.ok) {
52951
- const rawErrorBody = await res.json().catch(() => ({}));
52952
- throw buildApiError(res, rawErrorBody);
52953
- }
52954
- return res.json();
52955
- }
52956
- // ---- Tasks (org-scoped) ----
52957
- async createTask(orgId, data) {
52958
- return this.request("POST", ENDPOINTS.TASKS(orgId), data);
52959
- }
52960
- async getTasks(orgId, params) {
52961
- return this.request("GET", ENDPOINTS.TASKS(orgId), void 0, params);
52962
- }
52963
- async getTask(orgId, taskId) {
52964
- return this.request("GET", ENDPOINTS.TASK(orgId, taskId));
52965
- }
52966
- async updateTask(orgId, taskId, data) {
52967
- return this.request("PATCH", ENDPOINTS.TASK(orgId, taskId), data);
52968
- }
52969
- async deleteTask(orgId, taskId, opts) {
52970
- return this.request("DELETE", ENDPOINTS.TASK(orgId, taskId), void 0, opts?.force ? { force: "true" } : void 0);
52971
- }
52972
- async archiveTask(orgId, taskId) {
52973
- return this.request("POST", ENDPOINTS.TASK_ARCHIVE(orgId, taskId));
52974
- }
52975
- async restoreTask(orgId, taskId) {
52976
- return this.request("POST", ENDPOINTS.TASK_RESTORE(orgId, taskId));
52977
- }
52978
- async watchTask(orgId, taskId) {
52979
- return this.request("POST", ENDPOINTS.TASK_WATCH(orgId, taskId));
52980
- }
52981
- async unwatchTask(orgId, taskId) {
52982
- return this.request("DELETE", ENDPOINTS.TASK_WATCH(orgId, taskId));
52983
- }
52984
- async getTaskWatchers(orgId, taskId) {
52985
- const res = await this.request("GET", ENDPOINTS.TASK_WATCHERS(orgId, taskId));
52986
- return res.data;
52987
- }
52988
- async subscribeTaskMember(orgId, taskId, userId) {
52989
- return this.request("PUT", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52990
- }
52991
- async unsubscribeTaskMember(orgId, taskId, userId) {
52992
- return this.request("DELETE", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52993
- }
52994
- async watchThread(threadRootId) {
52995
- return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52996
- }
52997
- async unwatchThread(threadRootId) {
52998
- return this.request("DELETE", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52999
- }
53000
- async getThreadWatchers(threadRootId) {
53001
- const res = await this.request("GET", ENDPOINTS.MESSAGE_WATCHERS(threadRootId));
53002
- return res.data;
53003
- }
53004
- async isWatchingThread(threadRootId) {
53005
- const res = await this.request("GET", ENDPOINTS.MESSAGE_WATCHING(threadRootId));
53006
- return res.watching;
53007
- }
53008
- async getSubtasks(orgId, taskId) {
53009
- const res = await this.request("GET", ENDPOINTS.TASK_SUBTASKS(orgId, taskId));
53010
- return res.data;
53011
- }
53012
- async createTaskRelation(orgId, taskId, data) {
53013
- return this.request("POST", ENDPOINTS.TASK_RELATIONS(orgId, taskId), data);
53014
- }
53015
- async getTaskRelations(orgId, taskId) {
53016
- const res = await this.request("GET", ENDPOINTS.TASK_RELATIONS(orgId, taskId));
53017
- return res.data;
53018
- }
53019
- async listTaskRelationsByTarget(orgId, params) {
53020
- const query = new URLSearchParams({
53021
- target_type: params.target_type,
53022
- target_id: params.target_id
53023
- });
53024
- const res = await this.request("GET", `${ENDPOINTS.TASK_RELATIONS_BY_TARGET(orgId)}?${query.toString()}`);
53025
- return res.data;
53026
- }
53027
- async deleteTaskRelation(orgId, taskId, relationId) {
53028
- return this.request("DELETE", ENDPOINTS.TASK_RELATION(orgId, taskId, relationId));
53029
- }
53030
- // ---- Task Comments ----
53031
- async getTaskComments(orgId, taskId, params) {
53032
- return this.request("GET", ENDPOINTS.TASK_COMMENTS(orgId, taskId), void 0, params);
53033
- }
53034
- async getTaskComment(orgId, taskId, commentId) {
53035
- return this.request("GET", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId));
53036
- }
53037
- async createTaskComment(orgId, taskId, data) {
53038
- return this.request("POST", ENDPOINTS.TASK_COMMENTS(orgId, taskId), data);
53039
- }
53040
- async updateTaskComment(orgId, taskId, commentId, data) {
53041
- return this.request("PATCH", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId), data);
53042
- }
53043
- async deleteTaskComment(orgId, taskId, commentId) {
53044
- return this.request("DELETE", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId));
53045
- }
53046
- // ---- Task Activities ----
53047
- async getTaskActivities(orgId, taskId, params) {
53048
- return this.request("GET", ENDPOINTS.TASK_ACTIVITIES(orgId, taskId), void 0, params);
53049
- }
53050
- // ---- Projects (org-scoped) ----
53051
- async createProject(orgId, data) {
53052
- return this.request("POST", ENDPOINTS.PROJECTS(orgId), data);
53053
- }
53054
- async getProjects(orgId) {
53055
- const res = await this.request("GET", ENDPOINTS.PROJECTS(orgId));
53056
- return res.data;
53057
- }
53058
- async getProject(orgId, projectId) {
53059
- return this.request("GET", ENDPOINTS.PROJECT(orgId, projectId));
53060
- }
53061
- async updateProject(orgId, projectId, data) {
53062
- return this.request("PATCH", ENDPOINTS.PROJECT(orgId, projectId), data);
53063
- }
53064
- async deleteProject(orgId, projectId) {
53065
- return this.request("DELETE", ENDPOINTS.PROJECT(orgId, projectId));
53516
+ * Pass currentVersion to enable conditional fetch (If-None-Match / 304).
53517
+ * Returns null when the server responds with 304 (config unchanged).
53518
+ */
53519
+ async getPlatformConfig(currentVersion) {
53520
+ const url = `${this.baseUrlFor(ENDPOINTS.PLATFORM_CONFIG)}${ENDPOINTS.PLATFORM_CONFIG}`;
53521
+ const extra = {};
53522
+ if (currentVersion !== void 0) {
53523
+ extra["If-None-Match"] = currentVersion;
53524
+ }
53525
+ const headers = this.buildHeaders(ENDPOINTS.PLATFORM_CONFIG, extra);
53526
+ let res;
53527
+ try {
53528
+ res = await fetch(url, {
53529
+ method: "GET",
53530
+ headers,
53531
+ signal: AbortSignal.timeout(15e3)
53532
+ });
53533
+ } catch (err) {
53534
+ throw _ParallClient.normalizeFetchError(err);
53535
+ }
53536
+ if (res.status === 304)
53537
+ return null;
53538
+ if (!res.ok) {
53539
+ const rawErrorBody = await res.json().catch(() => ({}));
53540
+ throw buildApiError(res, rawErrorBody);
53541
+ }
53542
+ return res.json();
53066
53543
  }
53067
53544
  // ---- Schedules (org-scoped) ----
53068
53545
  async createSchedule(orgId, input) {
@@ -53201,12 +53678,26 @@ var ParallClient = class _ParallClient {
53201
53678
  }
53202
53679
  /**
53203
53680
  * WeChat tier-B read verb (agent-only; internal research preview): the
53204
- * account's address book — friend wxids, saved group room ids, followed
53205
- * official accounts. Same live gate as the send verb.
53681
+ * account's address book — friends/chatrooms enriched with display names,
53682
+ * followed official accounts. Same live gate as the send verb.
53206
53683
  */
53207
53684
  async listWechatContacts(orgId) {
53208
53685
  return this.request("GET", ENDPOINTS.WECHAT_CONTACTS(orgId));
53209
53686
  }
53687
+ /**
53688
+ * WeChat tier-B read verb (agent-only): the connected account's identity
53689
+ * (wxid / alias / nickName / app id).
53690
+ */
53691
+ async wechatProfile(orgId) {
53692
+ return this.request("GET", ENDPOINTS.WECHAT_PROFILE(orgId));
53693
+ }
53694
+ /**
53695
+ * WeChat tier-B read verb (agent-only): live online probe + identity +
53696
+ * the platform's offline record.
53697
+ */
53698
+ async wechatStatus(orgId) {
53699
+ return this.request("GET", ENDPOINTS.WECHAT_STATUS(orgId));
53700
+ }
53210
53701
  async listChannelConversations(orgId, connectionId) {
53211
53702
  return this.request("GET", ENDPOINTS.CHANNEL_CONNECTION_CONVERSATIONS(orgId, connectionId));
53212
53703
  }
@@ -53542,6 +54033,7 @@ var ParallClient = class _ParallClient {
53542
54033
  return this.request("PATCH", ENDPOINTS.NOTIFICATION_PREFERENCES, { prefs });
53543
54034
  }
53544
54035
  // ---- Feature Flags (org-scoped, server-evaluated) ----
54036
+ /** Omit orgId to resolve deployment capabilities before joining an org. */
53545
54037
  async getFeatureFlags(orgId) {
53546
54038
  return this.request("GET", ENDPOINTS.FEATURE_FLAGS(orgId));
53547
54039
  }
@@ -53558,6 +54050,44 @@ var ParallClient = class _ParallClient {
53558
54050
  timeoutMs: 185e3
53559
54051
  });
53560
54052
  }
54053
+ /** Queue a template deployment and poll its durable deployment row. Each
54054
+ * request is short-lived; closing the client does not cancel server work. */
54055
+ async deployTemplateAsync(orgId, request3, idempotencyKey) {
54056
+ const queue = () => this.request("POST", ENDPOINTS.TEMPLATE_DEPLOYMENTS(orgId), {
54057
+ ...request3,
54058
+ async: true,
54059
+ idempotency_key: idempotencyKey
54060
+ });
54061
+ let result;
54062
+ for (let attempt = 0; attempt < 2 && result === void 0; attempt += 1) {
54063
+ try {
54064
+ result = await queue();
54065
+ } catch (error) {
54066
+ if (!(error instanceof ApiError) || error.status !== 0 && error.status < 500)
54067
+ throw error;
54068
+ }
54069
+ }
54070
+ if (result === void 0) {
54071
+ throw new ApiError(0, "Template deployment request outcome is unknown", "NETWORK_ERROR");
54072
+ }
54073
+ const deadline = Date.now() + 30 * 60 * 1e3;
54074
+ while (result.status === "queued" || result.status === "deploying") {
54075
+ if (Date.now() >= deadline) {
54076
+ throw new ApiError(0, "Template deployment is still running", "REQUEST_TIMEOUT");
54077
+ }
54078
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
54079
+ try {
54080
+ result = await this.request("GET", ENDPOINTS.TEMPLATE_DEPLOYMENT(orgId, result.deployment_id));
54081
+ } catch (error) {
54082
+ if (!(error instanceof ApiError) || error.status !== 0 && error.status < 500)
54083
+ throw error;
54084
+ }
54085
+ }
54086
+ if (result.status !== "deployed") {
54087
+ throw new ApiError(500, result.error?.message ?? "Template deployment failed", result.error?.code);
54088
+ }
54089
+ return result;
54090
+ }
53561
54091
  async getTemplateDeployment(orgId, deploymentId) {
53562
54092
  return this.request("GET", ENDPOINTS.TEMPLATE_DEPLOYMENT(orgId, deploymentId));
53563
54093
  }
@@ -53772,6 +54302,11 @@ var ParallClient = class _ParallClient {
53772
54302
  async uninstallRegistryClip(orgId, clipId) {
53773
54303
  await this.request("DELETE", ENDPOINTS.ORG_CLIP_UNINSTALL(orgId, clipId));
53774
54304
  }
54305
+ /** Best-effort provider revoke followed by atomic local removal of an
54306
+ * installed Official MCP Clip and all org-owned connection state. */
54307
+ async removeOfficialMCPClip(orgId, clipId) {
54308
+ return this.request("DELETE", ENDPOINTS.ORG_CLIP_MCP_REMOVE(orgId, clipId));
54309
+ }
53775
54310
  /** List the org's installed registry clips (full entries). */
53776
54311
  async listInstalledRegistryClips(orgId) {
53777
54312
  const resp = await this.request("GET", ENDPOINTS.ORG_CLIPS_INSTALLED(orgId));
@@ -53958,12 +54493,14 @@ var ParallClient = class _ParallClient {
53958
54493
  async deleteClipConnection(orgId, connId) {
53959
54494
  return this.request("DELETE", ENDPOINTS.CLIP_CONNECTION(orgId, connId));
53960
54495
  }
53961
- // ---- MCP clip server config (cap:clip-mcp; publisher-org only) ----
54496
+ // ---- MCP clip server config (same-org or reviewed Official OAuth) ----
53962
54497
  /**
53963
- * Read the redacted MCP config. 404 NOT_FOUND when the clip has none yet;
53964
- * 403 MCP_CROSS_ORG_DISABLED for a cross-org installed clip (the whole
53965
- * mcp-config family is publisher-org property, reads included). `version`
53966
- * is the CAS token the mutations echo via If-Match.
54498
+ * Read the redacted MCP config. 404 NOT_FOUND when the clip has none yet
54499
+ * and also when a cross-org clip is not public + approved + installed, which
54500
+ * reads as nonexistent rather than refused (same existence-hiding as exec).
54501
+ * A cross-org clip that IS installed and approved reads fine regardless of
54502
+ * auth shape; what may then be configured is decided per credential owner.
54503
+ * `version` is the CAS token the mutations echo via If-Match.
53967
54504
  */
53968
54505
  async getClipMCPConfig(orgId, clipId) {
53969
54506
  return this.request("GET", ENDPOINTS.ORG_CLIP_MCP_CONFIG(orgId, clipId));
@@ -53996,6 +54533,30 @@ var ParallClient = class _ParallClient {
53996
54533
  async deleteClipMCPConfig(orgId, clipId, expectedVersion) {
53997
54534
  return this.request("DELETE", ENDPOINTS.ORG_CLIP_MCP_CONFIG(orgId, clipId), void 0, void 0, false, { headers: { "If-Match": `"${expectedVersion}"` } });
53998
54535
  }
54536
+ /**
54537
+ * List the org's MCP connections for a clip, default first — one row per
54538
+ * connection (credential slot), WITHOUT the tools snapshot (`tool_count`
54539
+ * summarizes it; the per-config GET carries the full snapshot). Same
54540
+ * family-wide fence as the singular GET: same-org clips, or a cross-org clip
54541
+ * that is public + approved + installed; anything else reads as
54542
+ * `404 NOT_FOUND`. An installed cross-org clip with no connection yet lists
54543
+ * as an empty array — including one whose approved auth mode cannot be
54544
+ * configured at all (auth=none), which the write path is what refuses. With
54545
+ * `cap:clip-mcp` off the route is not registered at all.
54546
+ */
54547
+ async listClipMCPConnections(orgId, clipId) {
54548
+ return this.request("GET", ENDPOINTS.ORG_CLIP_MCP_CONFIGS(orgId, clipId));
54549
+ }
54550
+ /** Start a new Official OAuth MCP connection with the platform-owned app.
54551
+ * Omitting oauth_client is load-bearing: the server resolves the exact
54552
+ * reviewed-version binding and never falls back to DCR/CIMD cross-org. */
54553
+ async createClipMCPOAuthConnection(orgId, clipId, serverUrl, alias) {
54554
+ return this.request("POST", ENDPOINTS.ORG_CLIP_MCP_CONFIGS(orgId, clipId), {
54555
+ server_url: serverUrl,
54556
+ auth_type: "oauth",
54557
+ ...alias ? { alias } : {}
54558
+ });
54559
+ }
53999
54560
  /**
54000
54561
  * Re-run tools/list and replace the cached snapshot (org-admin only).
54001
54562
  * Deliberately does NOT advance the CAS version, so an in-flight edit in
@@ -54417,211 +54978,23 @@ var ParallWs = class {
54417
54978
  }
54418
54979
  };
54419
54980
 
54420
- // ts/agent-core/dist/event-format.js
54421
- function sanitizeMeta(value) {
54422
- return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
54423
- }
54424
- function buildEventBody(event) {
54425
- const lines = [];
54426
- if (event.type === "message") {
54427
- lines.push(`[Event: message.new]`);
54428
- const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
54429
- lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
54430
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
54431
- lines.push(`[Message ID: prll://${event.messageId}]`);
54432
- if (event.threadRootId) {
54433
- const threadMeta = [
54434
- `prll://${event.threadRootId}`,
54435
- event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
54436
- event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
54437
- event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
54438
- ].filter(Boolean).join(" | ");
54439
- lines.push(`[Thread: ${threadMeta}]`);
54440
- }
54441
- if (event.unreadCount != null && event.unreadCount > 1) {
54442
- const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
54443
- const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
54444
- let line = `[Unread: ${countStr} messages${sinceStr}]`;
54445
- if (event.unreadCount > 50)
54446
- line += ` \u2014 fetch recent context with --limit, not all`;
54447
- lines.push(line);
54448
- }
54449
- if (event.noReply)
54450
- lines.push(`[Hint: no_reply]`);
54451
- if (event.attachments?.length) {
54452
- for (const att of event.attachments) {
54453
- const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
54454
- lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
54455
- }
54456
- }
54457
- lines.push("", event.body);
54458
- } else if (event.type === "task_comment") {
54459
- lines.push(`[Event: task.comment.created]`);
54460
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
54461
- lines.push(`[Task: ${taskLabel}]`);
54462
- if (event.deliveryReason)
54463
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
54464
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
54465
- lines.push(`[Comment ID: prll://${event.messageId}]`);
54466
- lines.push("", event.body);
54467
- } else if (event.type === "wiki_comment") {
54468
- lines.push(`[Event: wiki.comment.created]`);
54469
- const target = event.replyTargetUri ?? `prll://${event.targetId}`;
54470
- if (event.targetType === "changeset") {
54471
- lines.push(`[Wiki Changeset: ${target}]`);
54472
- } else {
54473
- lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
54474
- }
54475
- if (event.deliveryReason)
54476
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
54477
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
54478
- lines.push(`[Comment ID: prll://${event.messageId}]`);
54479
- lines.push("", event.body);
54480
- } else if (event.type === "approval") {
54481
- lines.push(`[Event: approval.decided]`);
54482
- lines.push(`[Approval: prll://${event.messageId}]`);
54483
- lines.push(`[Chat: prll://${event.targetId}]`);
54484
- lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
54485
- lines.push("", event.body);
54486
- } else if (event.type === "schedule") {
54487
- lines.push(`[Event: schedule.fired]`);
54488
- lines.push(`[Schedule: prll://${event.targetId}]`);
54489
- lines.push(`[Run: prll://${event.messageId}]`);
54490
- if (event.scheduledFireAt)
54491
- lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
54492
- if (event.attachedUri)
54493
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
54494
- lines.push("", event.body);
54495
- } else if (event.type === "channel_message") {
54496
- lines.push(`[Event: channel.message]`);
54497
- const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
54498
- const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
54499
- lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
54500
- lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
54501
- if (event.channelExternalMessageId) {
54502
- lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
54503
- }
54504
- lines.push(`[Audience: this conversation lives on ${providerLabel}, OUTSIDE Parall. Readers cannot open prll:// links, Parall cards, or internal attachments \u2014 never include them in replies. Write plain conversational text.]`);
54505
- lines.push("", event.body);
54506
- } else if (event.type === "external_trigger") {
54507
- lines.push(`[Event: external.trigger]`);
54508
- lines.push(`[Trigger: prll://${event.targetId}]`);
54509
- lines.push(`[Run: prll://${event.messageId}]`);
54510
- if (event.externalConnectionId) {
54511
- const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
54512
- lines.push(`[Connection: ${label}]`);
54513
- }
54514
- if (event.externalIngressEventId)
54515
- lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
54516
- if (event.attachedUri)
54517
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
54518
- if (event.externalConnectionSourceType) {
54519
- lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
54520
- }
54521
- if (event.externalIngressEventType) {
54522
- lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
54523
- }
54524
- lines.push("", event.body);
54525
- } else {
54526
- lines.push(`[Event: task.assigned]`);
54527
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
54528
- lines.push(`[Task: ${taskLabel}]`);
54529
- lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
54530
- lines.push("", event.body);
54531
- }
54532
- return lines.join("\n") + buildSendMessageHint(event);
54533
- }
54534
- function buildEventBodyForForkResult(event) {
54535
- return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
54536
- }
54537
- function buildSendMessageHint(event) {
54538
- if (event.noReply)
54539
- return "";
54540
- if (event.type === "wiki_comment" && event.replyTargetUri) {
54541
- const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
54542
- return `
54543
- <system-reminder>To reply on ${where}, run: \`parall comments add --target "${event.replyTargetUri}" --body "..."\` (read the thread first with \`parall comments list --target "${event.replyTargetUri}"\`). To message someone instead, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
54544
- }
54545
- if (event.targetId.startsWith("cht_")) {
54546
- if (event.threadRootId) {
54547
- return `
54548
- <system-reminder>To reply in this thread, run \`parall messages send prll://${event.targetId} --thread-root-id ${sanitizeMeta(event.threadRootId)} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
54549
- }
54550
- return `
54551
- <system-reminder>To reply, run \`parall messages send prll://${event.targetId} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
54552
- }
54553
- if (event.targetId.startsWith("tsk_")) {
54554
- return `
54555
- <system-reminder>To respond, use the CLI: \`parall tasks update\` / \`parall tasks comments add\`. To message someone, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
54556
- }
54557
- if (event.targetId.startsWith("sch_")) {
54558
- return `
54559
- <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
54560
- }
54561
- if (event.type === "channel_message") {
54562
- if (event.channelCliCapable) {
54563
- if (event.channelProvider === "slack") {
54564
- const channelArg = event.channelExternalConversationId ? ` --channel "${event.channelExternalConversationId}"` : " --channel <conversation id from this event>";
54565
- const replyTo = event.channelExternalMessageId ? ` --reply-to "${event.channelExternalMessageId}"` : "";
54566
- return `
54567
- <system-reminder>To reply, use the platform verb: \`parall slack send${channelArg}${replyTo} --text <your reply>\`. In channels --reply-to is REQUIRED (the reply lands in that message's thread); in DMs it is optional (DMs are linear). \`parall slack send\` is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
54568
- }
54569
- if (event.channelProvider === "wechat") {
54570
- const toArg = event.channelExternalConversationId ? ` --to "${event.channelExternalConversationId}"` : " --to <wxid from this event>";
54571
- const atArg = event.channelConversationType === "group" ? event.senderId && event.senderId !== "external" ? ` --at "${event.senderId}"` : " --at <wxid of the person you are answering>" : "";
54572
- return `
54573
- <system-reminder>To reply, use the platform verb: \`parall wechat send${toArg}${atArg} --text <your reply>\`. In group chats, --at @-mentions the person you are answering. \`parall wechat send\` is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
54574
- }
54575
- if (!event.channelProvider) {
54576
- return `
54577
- <system-reminder>To reply, use the channel capability granted in your system prompt \u2014 for Feishu conversations that is \`lark-cli im\`, for Slack it is \`parall slack send\` (pass the message id from this event as --reply-to), for WeChat it is \`parall wechat send\`. That capability is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
54578
- }
54579
- const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
54580
- const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
54581
- return `
54582
- <system-reminder>To reply, use the official Feishu CLI on your PATH: send a message to ${convRef} with \`lark-cli im\` (see \`lark-cli im --help\` for send syntax; auth is provisioned automatically).${threadAlt} lark-cli is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
54583
- }
54584
- const platform = event.channelProvider ?? "the external platform";
54585
- return `
54586
- <system-reminder>This message arrived from ${platform}, but outbound replies are currently disabled for this org (no channel capability granted). Do NOT attempt to reply on the external platform. If action is needed, surface it inside Parall (\`parall messages send\` / \`parall dm\`). Your plain text output is not delivered anywhere.</system-reminder>`;
54587
- }
54588
- if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
54589
- return `
54590
- <system-reminder>This external trigger is incoming-only. Your plain text output is not sent back to the external provider. To communicate in Parall, use \`parall messages send\` / \`parall dm\`; provider-specific outbound actions require a separate capability.</system-reminder>`;
54591
- }
54592
- return "";
54593
- }
54594
- function buildForkScopePrefix(event) {
54595
- const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
54596
- return `[Fork scope: You are a parallel worker forked from the main session to handle ${targetLabel}. The conversation history above belongs to the main session's in-progress dispatch \u2014 do NOT continue it or complete it, or produce external output (comments, messages) for work visible there. The main session owns its own output.
54597
-
54598
- Only act on the event below within your target scope. If your event reveals findings about the main session's work, report them in your summary \u2014 do not post them externally.
54599
-
54600
- End with a brief "Fork summary" of actions taken and decisions made.]
54981
+ // ts/agent-core/dist/lane-ledger.js
54982
+ import * as fs2 from "node:fs";
54601
54983
 
54602
- `;
54984
+ // ts/agent-core/dist/lane-key.js
54985
+ import * as path2 from "node:path";
54986
+ function laneKeyForTarget(targetUri, threadRootId) {
54987
+ return Buffer.from(`${targetUri}
54988
+ ${threadRootId ?? ""}`, "utf8").toString("base64url");
54603
54989
  }
54604
- function buildForkResultPrefix(results) {
54605
- if (!results.length)
54606
- return "";
54607
- const blocks = results.map((result) => {
54608
- const lines = [];
54609
- for (const body of result.eventBodies) {
54610
- lines.push(body);
54611
- }
54612
- lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
54613
- lines.push(`[Fork summary: ${result.agentSummary ? sanitizeMeta(result.agentSummary) : "No fork summary available \u2014 the fork completed without producing a text summary. Check the target chat/task for any actions the fork already took before acting."}]`);
54614
- if (result.actions.length)
54615
- lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
54616
- if (result.historyPath)
54617
- lines.push(`[Fork history: ${result.historyPath}]`);
54618
- return lines.join("\n");
54619
- });
54620
- return blocks.join("\n\n") + "\n\n---\n\n";
54990
+ function dispatchLaneContextDir(stateDir) {
54991
+ return path2.join(stateDir, "dispatch-lane-context");
54992
+ }
54993
+ function laneContextFilePath(contextDir, targetUri, threadRootId) {
54994
+ return path2.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
54621
54995
  }
54622
54996
 
54623
54997
  // ts/agent-core/dist/lane-ledger.js
54624
- import * as fs from "node:fs";
54625
54998
  var LedgerUnsupportedError = class extends Error {
54626
54999
  };
54627
55000
  function bindLaneSession(lane, agentSessionId) {
@@ -55045,7 +55418,7 @@ var LaneLedger = class {
55045
55418
  const contextPath = this.laneContextPath(lane);
55046
55419
  for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
55047
55420
  try {
55048
- fs.rmSync(p, { force: true });
55421
+ fs2.rmSync(p, { force: true });
55049
55422
  } catch {
55050
55423
  }
55051
55424
  }
@@ -55406,81 +55779,6 @@ async function consumeMessageWorkItem(host, item) {
55406
55779
  }
55407
55780
  }
55408
55781
 
55409
- // ts/agent-core/dist/session-state.js
55410
- function normalizeSessionKey(sessionKey) {
55411
- return sessionKey.toLowerCase();
55412
- }
55413
- var sessionChatIdMap = /* @__PURE__ */ new Map();
55414
- var sessionMessageIdMap = /* @__PURE__ */ new Map();
55415
- var dispatchMessageIdMap = /* @__PURE__ */ new Map();
55416
- var dispatchNoReplyMap = /* @__PURE__ */ new Map();
55417
- function setSessionChatId(sessionKey, chatId) {
55418
- sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
55419
- }
55420
- function setSessionMessageId(sessionKey, messageId) {
55421
- sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
55422
- }
55423
- function clearSessionMessageId(sessionKey) {
55424
- sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
55425
- }
55426
- function setDispatchMessageId(sessionKey, messageId) {
55427
- dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
55428
- }
55429
- function clearDispatchMessageId(sessionKey) {
55430
- dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
55431
- }
55432
- function setDispatchNoReply(sessionKey, noReply) {
55433
- dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
55434
- }
55435
- function clearDispatchNoReply(sessionKey) {
55436
- dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
55437
- }
55438
- var dispatchMetricsMap = /* @__PURE__ */ new Map();
55439
- function resetDispatchMetrics(sessionKey) {
55440
- dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
55441
- deliver_text_chunks: 0,
55442
- deliver_text_chars: 0,
55443
- message_send_attempts: 0,
55444
- message_send_successes: 0,
55445
- no_reply_called: false,
55446
- tool_call_count: 0,
55447
- started_at: Date.now()
55448
- });
55449
- }
55450
- function getDispatchMetrics(sessionKey) {
55451
- return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55452
- }
55453
- function clearDispatchMetrics(sessionKey) {
55454
- dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
55455
- }
55456
- function recordDeliverText(sessionKey, charCount) {
55457
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55458
- if (!m)
55459
- return;
55460
- m.deliver_text_chunks++;
55461
- m.deliver_text_chars += charCount;
55462
- }
55463
- function recordMessageSend(sessionKey, success) {
55464
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55465
- if (!m)
55466
- return;
55467
- m.message_send_attempts++;
55468
- if (success)
55469
- m.message_send_successes++;
55470
- }
55471
- function recordNoReply(sessionKey) {
55472
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55473
- if (!m)
55474
- return;
55475
- m.no_reply_called = true;
55476
- }
55477
- function recordToolCall(sessionKey) {
55478
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55479
- if (!m)
55480
- return;
55481
- m.tool_call_count++;
55482
- }
55483
-
55484
55782
  // ts/agent-core/dist/routing.js
55485
55783
  var MAX_CONCURRENT_FORKS = 20;
55486
55784
  var defaultRoutingStrategy = (event, state) => {
@@ -55501,471 +55799,7 @@ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
55501
55799
  return { action: "buffer-fork", forkKey: existingForkKey };
55502
55800
  if (!state.mainDispatching)
55503
55801
  return { action: "main" };
55504
- return strategy(event, state);
55505
- }
55506
-
55507
- // ts/agent-core/dist/prompt-fragments.js
55508
- function identityFromMe(me) {
55509
- return {
55510
- userId: me.id,
55511
- displayName: me.display_name,
55512
- title: me.public_profile?.title || void 0,
55513
- publicDescription: me.public_profile?.description || void 0,
55514
- // `||` on purpose: an empty-string instructions must also fall back to
55515
- // the deprecated description alias (empty means "unset" on this wire).
55516
- instructions: me.agent_profile?.instructions || me.agent_profile?.description || void 0
55517
- };
55518
- }
55519
- var PRLL_IDENTITY_BASE = `## You on Parall
55520
-
55521
- Parall is a shared workspace where humans and agents work side by side as equals.
55522
- You are a participant here, not a service. You hold tasks, own decisions, and are
55523
- accountable for the work you take on \u2014 the same way a human teammate is.
55524
-
55525
- The people and agents around you are collaborators, not users to serve. Be honest,
55526
- be direct, and care about the outcome of the work \u2014 not just the request in front
55527
- of you.`;
55528
- function sanitizeProfileField(value) {
55529
- return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
55530
- }
55531
- function sanitizeProfileBlock(value) {
55532
- return value.replace(/\r\n?/g, "\n").trim();
55533
- }
55534
- function buildIdentity(agent) {
55535
- if (!agent)
55536
- return PRLL_IDENTITY_BASE;
55537
- const name = sanitizeProfileField(agent.displayName);
55538
- const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
55539
- lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
55540
- const title = agent.title ? sanitizeProfileField(agent.title) : "";
55541
- if (title)
55542
- lines.push(`Title: ${title}`);
55543
- const about = agent.publicDescription ? sanitizeProfileField(agent.publicDescription) : "";
55544
- if (about)
55545
- lines.push(`About: ${about}`);
55546
- const instructions = sanitizeProfileBlock(agent.instructions ?? agent.description ?? "");
55547
- if (instructions) {
55548
- lines.push("", "### Private instructions from your organization admins", "", instructions);
55549
- }
55550
- lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
55551
- return lines.join("\n");
55552
- }
55553
- var PRLL_BEHAVIOR = `## How to work here
55554
-
55555
- ### Move work forward
55556
- Don't wait for instructions. If you see the next step, take it. If something is
55557
- ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
55558
- \u2014 don't go silent. Initiative is expected.
55559
-
55560
- Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
55561
- requests, verifying something landed. When a thing needs future attention and
55562
- nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
55563
-
55564
- ### Work in the open
55565
- Nothing you do exists until the system can see it. Your progress, decisions,
55566
- blockers, and results need to live in tasks, comments, messages, or wiki pages
55567
- \u2014 otherwise the organization is blind to your work, and so is the next agent
55568
- who picks up where you left off. Leave traces as you go, not at the end.
55569
-
55570
- For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
55571
- when status materially changes, close it when done, and link the origin that
55572
- triggered it. Decompose multi-step work into subtasks and keep their statuses
55573
- current \u2014 progress should be auditable without watching the work happen.
55574
- Details: load the \`parall-tasks\` skill.
55575
-
55576
- ### Done means landed
55577
- Producing output does not complete a task. Work counts as done only when it has
55578
- cleared its remaining gates \u2014 review, merge, deployment, the requester's
55579
- verification. Until then keep the status honest (\`in_progress\` or
55580
- \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
55581
- self-reminder if nothing else will prompt follow-up). Never mark done what a
55582
- human still has to accept.
55583
-
55584
- ### Sessions, forks, and what survives
55585
- Sessions end and context compacts. Anything that must survive \u2014 decisions,
55586
- progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
55587
- read the workspace, not this conversation.
55588
-
55589
- Some events are handled by parallel fork sessions \u2014 short-lived copies of the
55590
- same agent identity with separate context. In a fork: leave a written trace of
55591
- what was done or deliberately not done (other sessions cannot see fork
55592
- context), and do not start long-running processes \u2014 they die with the fork.
55593
- When an event is marked fork-handled: do not re-handle it; verify its outcome
55594
- instead of assuming it.
55595
-
55596
- ### Communicate like a teammate
55597
- Match the conversation \u2014 concise in chat, thorough in docs, plain language over
55598
- jargon. Say what matters; stop when you're done. Don't narrate every tool call
55599
- or pad replies to seem thorough.
55600
-
55601
- Match the language of the person you're replying to. If someone writes in
55602
- Chinese, reply in Chinese. If in English, reply in English. Never force a
55603
- language switch unless explicitly asked.
55604
-
55605
- Do not promise delivery times ("in an hour", "by tonight") unless the work is
55606
- driven by an explicit schedule. Scope visibly; report when actually done.
55607
-
55608
- ### Keep topics in threads
55609
- Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
55610
- Present \u2192 that thread is the context; reply there, passing the same root as
55611
- \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
55612
- never treat it as continuing your most recent thread. The sender's newest
55613
- message is the anchor \u2014 never route a reply back into an older thread just
55614
- because the topic used to live there.
55615
-
55616
- Reply where the event lives: a thread message gets a thread reply, a
55617
- top-level message gets a top-level reply. But in group chats, your later
55618
- follow-up on that topic \u2014 progress updates, analysis, links, verification you
55619
- post afterwards \u2014 belongs in a thread rooted at the topic's message
55620
- (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
55621
- the main channel stays scannable. Post follow-up at top level only when
55622
- starting a genuinely new topic, making a channel-wide announcement, or when
55623
- explicitly asked. Never post the same update in both the thread and the main
55624
- channel \u2014 thread replies surface in the thread panel; no need to duplicate
55625
- for visibility.
55626
-
55627
- In DMs, reply top-level by default; use a thread only to continue one that
55628
- already exists.
55629
-
55630
- ### Group chats: mentions and unaddressed work
55631
- An @mention is a direct request \u2014 act on it. A group message delivered to you
55632
- without an @mention means the chat's routing lets you see the conversation:
55633
- decide whether a reply adds value; silence is the default.
55634
-
55635
- A message without an @mention is not an open invitation. Judge from context
55636
- who the work belongs to \u2014 the named domain, the topic's owner, whoever is
55637
- already on it. If it belongs to someone else, leave it. If genuinely unclear,
55638
- ask or claim in one line ("taking this unless someone else has it") before
55639
- starting \u2014 asking first beats duplicated or misdirected work.
55640
-
55641
- ### Verify before you act
55642
- Events can be redelivered \u2014 before acting, check whether it was already
55643
- handled (your own recent replies, task comments); if handled, do nothing.
55644
- Sends can fail silently, and creates can error after succeeding server-side \u2014
55645
- check the chat or entity before retrying. Never blind-retry a mutating call.
55646
-
55647
- ### Gather the full picture first
55648
- When a request is vague, an entity may already exist, or work may already be
55649
- underway \u2014 gather context before acting: search (\`parall search "..."\`),
55650
- check existing tasks/chats/wiki, read the surrounding conversation. Act on the
55651
- full picture, not the fragment that arrived in the event.
55652
-
55653
- ### Report only work that ran
55654
- If a scheduled job, scan, or tool call did not actually run \u2014 restarted
55655
- session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
55656
- or approximate results of work that did not execute.
55657
-
55658
- ### Respect what's shared
55659
- You have broad latitude inside your own work. But actions that are visible to
55660
- others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
55661
- wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
55662
- acting, unless you've been explicitly authorized.
55663
-
55664
- ### Shared workspace
55665
- Other agents share this workspace. Before starting work, check whether someone
55666
- \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
55667
-
55668
- ### Permissions and approvals
55669
- You have real permissions based on your roles (chat member/admin, org member).
55670
- If you lack permission for an action, the API returns PERMISSION_DENIED with the
55671
- \`action\` and \`resource_uri\` that were denied. The server decides whether that
55672
- action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
55673
- fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
55674
- it to ask someone with permission. If it is NOT approvable, the output says so;
55675
- ask a human with permission instead of requesting approval. A
55676
- \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
55677
- (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
55678
- \`dm\` for a user). Don't retry or work around a denial; only request approval
55679
- after an actual denial, never preemptively.
55680
-
55681
- ### When in doubt
55682
- Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
55683
- credibility is what you bring to the workspace \u2014 protect it.`;
55684
- var PRLL_REFERENCE_GUIDE = `## Parall References
55685
-
55686
- Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
55687
- entities when you create or update tasks, comments, messages, and wiki files.
55688
-
55689
- All three forms work \u2014 pick whichever fits:
55690
-
55691
- prll://tsk_abc bare URI (auto-linked)
55692
- [](prll://tsk_abc) empty context (renders resolved title)
55693
- [relevant context](prll://tsk_abc) with author annotation
55694
-
55695
- Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
55696
- resolves and renders the entity title automatically.
55697
-
55698
- ### Mentioning people and agents
55699
-
55700
- A real member mention is a \`prll://usr_...\` reference. Plain \`@Display Name\` is
55701
- only text: it does not notify a human or trigger an agent.
55702
-
55703
- When another member must be notified or an agent explicitly triggered, include
55704
- their user reference in the message body. Prefer the empty-context form because
55705
- the platform resolves the member's current display name:
55706
-
55707
- [](prll://usr_xxx)
55708
-
55709
- Use \`[Display Name](prll://usr_xxx)\` when the surrounding sentence needs an
55710
- explicit label. Find the user ID in the incoming message or with
55711
- \`parall members list\`. Never substitute plain \`@Display Name\` when notification
55712
- or agent dispatch matters.
55713
-
55714
- ### URI format
55715
-
55716
- \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
55717
-
55718
- **Entities** \u2014 the entity ID is the authority:
55719
-
55720
- prll://usr_xxx user prll://prj_xxx project
55721
- prll://tsk_xxx task prll://wik_xxx wiki
55722
- prll://msg_xxx message prll://cmt_xxx comment
55723
- prll://cht_xxx chat prll://tcm_xxx task comment (legacy)
55724
- prll://att_xxx attachment prll://ase_xxx agent session
55725
- prll://sch_xxx schedule prll://srn_xxx schedule run
55726
-
55727
- **Wiki** \u2014 path is file path, fragment is a typed anchor:
55728
-
55729
- prll://wik_xxx/docs/guide.md file
55730
- prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
55731
- prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
55732
-
55733
- Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
55734
- Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
55735
-
55736
- **Chat message range**:
55737
-
55738
- prll://cht_xxx#range=msg_01HA,msg_01HZ
55739
-
55740
- **Field access** \u2014 path selects a field (omit to reference the entity itself):
55741
-
55742
- prll://tsk_xxx/description#Implementation heading within task description
55743
-
55744
- ### Unread context
55745
-
55746
- When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
55747
- This shows messages since your last interaction \u2014 your read cursor advances after each
55748
- dispatch, so context you skip now won't appear as unread next time. Use
55749
- \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
55750
- counts (50+), fetch only recent messages rather than everything.
55751
-
55752
- Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
55753
- Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
55754
- catch up on the thread.
55755
-
55756
- ### Reading context on demand
55757
-
55758
- An event only carries the single triggering message. If you're mentioned in a
55759
- group chat and lack context, pull what you need from the chat \u2014 don't guess:
55760
-
55761
- parall messages list cht_xxx --limit 20 --before msg_xxx
55762
- parall messages get msg_xxx
55763
- parall chats get cht_xxx
55764
-
55765
- Rule of thumb: in a group chat mention, the conversation that led up to you
55766
- being called almost always matters \u2014 read it before replying. In a DM, your
55767
- session already has continuity, so skip the fetch unless something is unclear.
55768
-
55769
- Same pattern for any other entity referenced in the event: \`tasks get\`,
55770
- \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
55771
- When one entity isn't enough \u2014 you need what's *around* it \u2014 walk the
55772
- reference graph instead of guessing (see "Walk the reference graph" below).
55773
-
55774
- ### Find context with search first
55775
-
55776
- Reach for unified semantic search before paging chat history:
55777
-
55778
- parall search "pricing decision june" --limit 10
55779
-
55780
- It spans messages, tasks, wiki, and comments. Page \`messages list\` only for the
55781
- verbatim recent flow of one chat, not for discovery.
55782
-
55783
- ### Walk the reference graph
55784
-
55785
- References form a traversable graph, and you can query it \u2014 don't stop at
55786
- fetching entities one by one:
55787
-
55788
- # entity metadata (title, status, preview)
55789
- parall refs resolve prll://tsk_xxx prll://wik_xxx
55790
- # who references this entity
55791
- parall refs backlinks prll://tsk_xxx
55792
- # connected sub-graph around it
55793
- parall refs graph prll://tsk_xxx --depth 2
55794
-
55795
- Use \`refs backlinks\` when you need "where is this discussed / used"; use
55796
- \`refs graph\` when you need the full picture around an entity (related tasks,
55797
- docs, conversations \u2014 edges carry the author's annotation for why they linked).
55798
- Then \`refs resolve\` the interesting node URIs in one batch to get titles and
55799
- status. \`refs graph\` takes entity-level URIs only (\`prll://wik_xxx\`, not
55800
- \`prll://wik_xxx/docs/a.md\`). All results are filtered to what you can see.
55801
- Details: parall-platform skill.
55802
-
55803
- ### File attachments
55804
-
55805
- Messages may include attachments. They appear in events as:
55806
-
55807
- [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
55808
-
55809
- To download an attachment, use the CLI:
55810
-
55811
- parall files download att_xxx --output /tmp/screenshot.png
55812
-
55813
- To send a file:
55814
-
55815
- parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
55816
-
55817
- Or upload first and reuse across chats:
55818
-
55819
- parall files upload /tmp/report.pdf
55820
- parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
55821
- parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
55822
-
55823
- The \`--text\` captions above are safe short literals. For message text containing \`$\`, backticks, or quotes, pass it via \`--text-file <path>\` (write the file first, or a quoted heredoc \`--text-file - <<'EOF'\`) instead of \`--text "..."\` \u2014 inside double quotes the shell turns \`$1,000\` into \`,000\` and executes \`$(...)\`.
55824
-
55825
- ### When to reference
55826
-
55827
- - **Origin** \u2014 always link the message or task that triggered your work
55828
- - **Design docs / wiki** \u2014 link specs and guides relevant to the work
55829
- - **Related tasks** \u2014 link parent, sibling, or blocking tasks
55830
- - **People** \u2014 link assignees or stakeholders when mentioning them
55831
- - **Conversations** \u2014 link a chat or message range as context
55832
-
55833
- ### Why this matters
55834
-
55835
- Other agents and humans read your output. References build a navigable context graph \u2014
55836
- in multi-agent workflows, your references are the map that the next agent follows.`;
55837
- function renderLocalAttachmentSection(section) {
55838
- if (section.images.length === 0 && section.notes.length === 0)
55839
- return "";
55840
- const lines = ["[Local attachment files]"];
55841
- for (const image of section.images) {
55842
- lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
55843
- }
55844
- lines.push(...section.notes);
55845
- return lines.join("\n");
55846
- }
55847
- function sanitizePromptMeta(value) {
55848
- return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
55849
- }
55850
- function formatBytes(bytes) {
55851
- if (bytes >= 1048576)
55852
- return `${(bytes / 1048576).toFixed(1)}MB`;
55853
- if (bytes >= 1024)
55854
- return `${Math.round(bytes / 1024)}KB`;
55855
- return `${bytes}B`;
55856
- }
55857
-
55858
- // ts/agent-core/dist/bridge-workspace.js
55859
- var BRIDGE_WORKSPACE_INSTRUCTIONS = `# Agent workspace
55860
-
55861
- You are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.
55862
-
55863
- ## Message Model
55864
-
55865
- Incoming events are rendered as structured \`[Event: ...]\` blocks.
55866
- Each event includes \`[Chat: ... (prll://cht_xxx)]\` \u2014 use that chat ID (or full URI) when replying.
55867
-
55868
- **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.
55869
- To say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.
55870
-
55871
- ## Parall CLI
55872
-
55873
- All outbound interactions go through the \`parall\` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If \`parall\` is not on PATH, use \`npx --yes @parall/cli@latest\` instead.
55874
-
55875
- - \`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)
55876
- - \`parall dm prll://usr_xxx --text-file - [--no-reply]\` \u2014 direct message another user
55877
- - \`parall tasks update prll://tsk_xxx --status in_progress\` \u2014 task state
55878
- - \`parall no-reply [--reason "..."]\` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)
55879
-
55880
- **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:
55881
-
55882
- \`\`\`bash
55883
- parall messages send prll://cht_xxx --text-file - <<'EOF'
55884
- That costs $1,000, and $(whoami) stays literal. I'm on it.
55885
- EOF
55886
- \`\`\`
55887
-
55888
- Keep \`--text "..."\` for short literals with no \`$\`, backtick, or apostrophe.
55889
-
55890
- The bridge injects Parall context via environment variables. The static credentials \`PRLL_API_URL\`, \`PRLL_API_KEY\`, and \`PRLL_ORG_ID\` are always set. \`PRLL_CONTEXT_FILE\` points to a per-session JSON file that the gateway updates each dispatch with \`session_id\`, \`chat_id\`, \`trigger_message_id\`, \`no_reply\`, and \`step_id\` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass \`--chat\` or \`--session\` explicitly when the context file is present.
55891
-
55892
- CLI errors are agent-readable \u2014 read them; they usually name the next step.
55893
-
55894
- ## Attachments
55895
-
55896
- Image attachments are pre-downloaded under \`.parall/attachments/<messageId>/\`. Each event's \`[Local attachment files]\` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.
55897
-
55898
- Supported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with \`parall files download att_xxx --output ...\`.
55899
-
55900
- ## Guardrails
55901
-
55902
- - 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.
55903
- - 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.
55904
- - 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.
55905
- - Keep CLI replies concise and task-focused.
55906
-
55907
- See \`docs/engineering-design/agent-dm-loop-prevention.md\` \xA7 Layer 0 for why plain text is never auto-projected.
55908
-
55909
- ## Approval Flow
55910
-
55911
- When you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:
55912
-
55913
- 1. The error includes a \`PERMISSION_DENIED\` code plus the denied \`action\` and \`resource_uri\`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a \`Request approval:\` line with an approval command is printed \u2014 fill in its \`--chat\`, \`--title\`, \`--reason\` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.
55914
- 2. Request approval: \`parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"\`
55915
- 3. A card will appear in the specified chat for someone with permission to approve
55916
- 4. Check the result: \`parall approvals get prll://<id>\` or wait: \`parall approvals wait prll://<id> --timeout 300\`
55917
- 5. List available actions: \`parall approvals actions\`
55918
-
55919
- Only request approval when you've actually been denied permission. Don't request approval preemptively.
55920
- `;
55921
- function extractShellCommand(input) {
55922
- if (!input || typeof input !== "object")
55923
- return void 0;
55924
- const command = input.command;
55925
- return typeof command === "string" && command.trim() ? command.trim() : void 0;
55926
- }
55927
- function parseParallCliInvocation(command) {
55928
- const tokens = command.replace(/\s+/g, " ").trim().split(" ");
55929
- let i = 0;
55930
- if (tokens[i] === "parall") {
55931
- i++;
55932
- } else if (tokens[i] === "npx") {
55933
- i++;
55934
- while (i < tokens.length && tokens[i].startsWith("-"))
55935
- i++;
55936
- if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
55937
- return null;
55938
- i++;
55939
- } else if (tokens[i] === "pnpm") {
55940
- i++;
55941
- if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
55942
- i++;
55943
- if (i >= tokens.length || tokens[i] !== "parall")
55944
- return null;
55945
- i++;
55946
- } else {
55947
- return null;
55948
- }
55949
- return tokens.slice(i).filter((t) => !t.startsWith("-"));
55950
- }
55951
- function isParallSendCommand(command) {
55952
- if (!command)
55953
- return false;
55954
- const sub = parseParallCliInvocation(command);
55955
- if (!sub || sub.length === 0)
55956
- return false;
55957
- return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
55958
- }
55959
- function isParallNoReplyCommand(command) {
55960
- if (!command)
55961
- return false;
55962
- const sub = parseParallCliInvocation(command);
55963
- return sub?.[0] === "no-reply";
55964
- }
55965
-
55966
- // ts/agent-core/dist/dispatch-adapter.js
55967
- function buildErrorStepContent(message) {
55968
- return { text: message, suppressed: false, status: "error" };
55802
+ return strategy(event, state);
55969
55803
  }
55970
55804
 
55971
55805
  // ts/agent-core/dist/redact.js
@@ -55990,114 +55824,6 @@ function redactTurnOutcome(event, knownValues) {
55990
55824
  return redacted;
55991
55825
  }
55992
55826
 
55993
- // ts/agent-core/dist/logger.js
55994
- function createLogger(prefix) {
55995
- return {
55996
- info: (msg) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
55997
- warn: (msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
55998
- error: (msg) => console.error(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
55999
- child: (sub) => createLogger(`${prefix}:${sub}`)
56000
- };
56001
- }
56002
- function childLogger(logger, sub) {
56003
- return logger.child ? logger.child(sub) : logger;
56004
- }
56005
-
56006
- // ts/agent-core/dist/gateway-base.js
56007
- import * as os from "node:os";
56008
- import * as fs3 from "node:fs";
56009
- import * as path3 from "node:path";
56010
- import { randomUUID } from "node:crypto";
56011
-
56012
- // ts/agent-core/dist/channel-capability.js
56013
- import * as fs2 from "node:fs";
56014
- import * as path2 from "node:path";
56015
- import { fileURLToPath } from "node:url";
56016
- var CAPABILITY_FEISHU_CLI = "feishu-cli";
56017
- var CAPABILITY_SLACK_SEND = "slack-send";
56018
- var CAPABILITY_WECHAT_SEND = "wechat-send";
56019
- function channelCapabilityKeyFor(provider) {
56020
- if (provider === "slack")
56021
- return CAPABILITY_SLACK_SEND;
56022
- if (provider === "wechat")
56023
- return CAPABILITY_WECHAT_SEND;
56024
- return `${provider}-cli`;
56025
- }
56026
- var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
56027
- function capabilityBinDir(stateDir) {
56028
- return path2.join(stateDir, "bin");
56029
- }
56030
- function channelExecEntryPath() {
56031
- const selfDir = path2.dirname(fileURLToPath(import.meta.url));
56032
- const sibling = path2.join(selfDir, "parall-channel-exec.js");
56033
- if (fs2.existsSync(sibling))
56034
- return sibling;
56035
- return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
56036
- }
56037
- function materializeChannelCapabilities(stateDir, capabilities, log2) {
56038
- try {
56039
- reconcileFeishuCli(stateDir, capabilities, log2);
56040
- } catch (err) {
56041
- log2?.warn(`channel capability materialization failed: ${String(err)}`);
56042
- }
56043
- }
56044
- function reconcileFeishuCli(stateDir, capabilities, log2) {
56045
- const binDir = capabilityBinDir(stateDir);
56046
- const posixPath = path2.join(binDir, "lark-cli");
56047
- const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
56048
- const hadPointer = fs2.existsSync(posixPath);
56049
- if (!granted && !hadPointer)
56050
- return;
56051
- fs2.mkdirSync(binDir, { recursive: true });
56052
- const entry = channelExecEntryPath();
56053
- const nodeExec = process.execPath;
56054
- writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log2);
56055
- writePointerIfChanged(path2.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log2);
56056
- }
56057
- function writePointerIfChanged(filePath, content, log2) {
56058
- let existing = null;
56059
- try {
56060
- existing = fs2.readFileSync(filePath, "utf8");
56061
- } catch {
56062
- existing = null;
56063
- }
56064
- if (existing !== content) {
56065
- fs2.writeFileSync(filePath, content, { mode: 493 });
56066
- log2?.info(`channel capability: pointer materialized (${path2.basename(filePath)})`);
56067
- }
56068
- fs2.chmodSync(filePath, 493);
56069
- }
56070
- function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
56071
- return [
56072
- "#!/bin/sh",
56073
- `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
56074
- "# Credential + exec logic lives in the agent-core package; revocation is",
56075
- "# enforced by the platform mint endpoint, so this pointer stays constant.",
56076
- // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
56077
- // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
56078
- // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
56079
- // the mint. The pointer is a platform-authored trust-boundary artifact whose
56080
- // whole job is a CONTROLLED launch of the broker (absolute node, magic
56081
- // guard, skip-dir); this closes the same env-hijack class for node startup
56082
- // that the absolute node path closes for PATH, keeping the launch deterministic.
56083
- "unset NODE_OPTIONS NODE_PATH",
56084
- // "$@" preserves argv exactly (this is the agent's main path via git-bash).
56085
- `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
56086
- ""
56087
- ].join("\n");
56088
- }
56089
- function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
56090
- return [
56091
- "@echo off",
56092
- `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
56093
- // Clear Node preload-hijack vars before launching node (see the sh pointer).
56094
- 'set "NODE_OPTIONS="',
56095
- 'set "NODE_PATH="',
56096
- `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
56097
- ""
56098
- ].join("\r\n");
56099
- }
56100
-
56101
55827
  // ts/agent-core/dist/step-retry-queue.js
56102
55828
  var DEFAULT_RETRY_DELAYS_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
56103
55829
  async function raceWithDeadline(work, ms) {
@@ -56857,6 +56583,81 @@ var ForkSessionFinalizer = class {
56857
56583
  }
56858
56584
  };
56859
56585
 
56586
+ // ts/agent-core/dist/session-state.js
56587
+ function normalizeSessionKey(sessionKey) {
56588
+ return sessionKey.toLowerCase();
56589
+ }
56590
+ var sessionChatIdMap = /* @__PURE__ */ new Map();
56591
+ var sessionMessageIdMap = /* @__PURE__ */ new Map();
56592
+ var dispatchMessageIdMap = /* @__PURE__ */ new Map();
56593
+ var dispatchNoReplyMap = /* @__PURE__ */ new Map();
56594
+ function setSessionChatId(sessionKey, chatId) {
56595
+ sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
56596
+ }
56597
+ function setSessionMessageId(sessionKey, messageId) {
56598
+ sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
56599
+ }
56600
+ function clearSessionMessageId(sessionKey) {
56601
+ sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
56602
+ }
56603
+ function setDispatchMessageId(sessionKey, messageId) {
56604
+ dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
56605
+ }
56606
+ function clearDispatchMessageId(sessionKey) {
56607
+ dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
56608
+ }
56609
+ function setDispatchNoReply(sessionKey, noReply) {
56610
+ dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
56611
+ }
56612
+ function clearDispatchNoReply(sessionKey) {
56613
+ dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
56614
+ }
56615
+ var dispatchMetricsMap = /* @__PURE__ */ new Map();
56616
+ function resetDispatchMetrics(sessionKey) {
56617
+ dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
56618
+ deliver_text_chunks: 0,
56619
+ deliver_text_chars: 0,
56620
+ message_send_attempts: 0,
56621
+ message_send_successes: 0,
56622
+ no_reply_called: false,
56623
+ tool_call_count: 0,
56624
+ started_at: Date.now()
56625
+ });
56626
+ }
56627
+ function getDispatchMetrics(sessionKey) {
56628
+ return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56629
+ }
56630
+ function clearDispatchMetrics(sessionKey) {
56631
+ dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
56632
+ }
56633
+ function recordDeliverText(sessionKey, charCount) {
56634
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56635
+ if (!m)
56636
+ return;
56637
+ m.deliver_text_chunks++;
56638
+ m.deliver_text_chars += charCount;
56639
+ }
56640
+ function recordMessageSend(sessionKey, success) {
56641
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56642
+ if (!m)
56643
+ return;
56644
+ m.message_send_attempts++;
56645
+ if (success)
56646
+ m.message_send_successes++;
56647
+ }
56648
+ function recordNoReply(sessionKey) {
56649
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56650
+ if (!m)
56651
+ return;
56652
+ m.no_reply_called = true;
56653
+ }
56654
+ function recordToolCall(sessionKey) {
56655
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56656
+ if (!m)
56657
+ return;
56658
+ m.tool_call_count++;
56659
+ }
56660
+
56860
56661
  // ts/agent-core/dist/telemetry.js
56861
56662
  init_esm();
56862
56663
  var import_api_logs = __toESM(require_src(), 1);
@@ -59532,6 +59333,19 @@ function configureHttpKeepAlive(opts) {
59532
59333
  }));
59533
59334
  }
59534
59335
 
59336
+ // ts/agent-core/dist/logger.js
59337
+ function createLogger(prefix) {
59338
+ return {
59339
+ info: (msg) => console.log(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
59340
+ warn: (msg) => console.warn(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
59341
+ error: (msg) => console.error(`${(/* @__PURE__ */ new Date()).toISOString()} [${prefix}] ${msg}`),
59342
+ child: (sub) => createLogger(`${prefix}:${sub}`)
59343
+ };
59344
+ }
59345
+ function childLogger(logger, sub) {
59346
+ return logger.child ? logger.child(sub) : logger;
59347
+ }
59348
+
59535
59349
  // ts/agent-core/dist/platform-config.js
59536
59350
  import * as fs4 from "node:fs";
59537
59351
  import * as path4 from "node:path";
@@ -60492,16 +60306,23 @@ guessing which signed-in account you are about to act through.
60492
60306
  \`\`\`bash
60493
60307
  parall clip exec <clip> <command> [args] --connection <ccn_|alias> # the normal form
60494
60308
  parall clip exec browser-tools screenshot '{"url":"\u2026"}' --connection cloud-main
60309
+ parall clip exec browser-tools scrape --args-file - --connection cloud-main <<'EOF'
60310
+ {"url":"https://example.com","fields":["title","price"]}
60311
+ EOF
60495
60312
  \`\`\`
60496
60313
 
60497
60314
  Build \`args\` as JSON per the command's params from \`clip info\` (or the
60498
60315
  tool's \`inputSchema\` from \`clip tools\` for MCP clips \u2014 tool names are NOT
60499
60316
  frozen in the manifest, so never guess a tool name or its argument shape).
60317
+ Quote-heavy or large JSON goes through \`--args-file <path>\` (\`-\` = stdin
60318
+ via a quoted heredoc, as above; strict JSON, mutually exclusive with the
60319
+ \`[args]\` positional) \u2014 the shell mangles inline quotes long before the CLI
60320
+ sees them, exactly the trap \`messages send --text-file\` exists for.
60500
60321
  Results are JSON on stdout; failures print a typed error.
60501
60322
 
60502
- **Name the target explicitly.** A cloud profile has NO implicit route;
60503
- omitting the target entirely is a desktop-only legacy form that reaches just
60504
- YOUR OWN online desktop device \u2014 never a shared cloud profile.
60323
+ **Name the target explicitly \u2014 every exec.** \`clip exec\` refuses to run
60324
+ without \`--connection\` or \`--edge\`; there is no implicit route to any
60325
+ profile, and the legacy no-flag desktop fallback is gone from the CLI.
60505
60326
 
60506
60327
  - A cloud (hosted) profile is reachable ONLY via \`--connection\` \u2014 the clip
60507
60328
  connection its maintainer bound. That binding IS your authorization;
@@ -60519,21 +60340,39 @@ YOUR OWN online desktop device \u2014 never a shared cloud profile.
60519
60340
  ## MCP clips (remote tool servers)
60520
60341
 
60521
60342
  A connection with target \`mcp\` routes to a remote MCP server; the command
60522
- is an MCP tool name and the args are that tool's JSON arguments. Read each
60523
- tool's \`inputSchema\` from \`clip tools\` first, then exec against the
60524
- explicit target \u2014 the same form as any other clip:
60343
+ is an MCP tool name and the args are that tool's JSON arguments. **An MCP
60344
+ clip can hold SEVERAL connections \u2014 one per account of the same service**
60345
+ (e.g. two Google Drive accounts), exactly like the browser arm's multiple
60346
+ profiles. The flow is: discover the connections, pick by alias, exec with the
60347
+ explicit target:
60525
60348
 
60526
60349
  \`\`\`bash
60350
+ parall clip connections <clip> # per-connection auth status, alias, is_default
60351
+ parall clip tools <clip> --connection <ccn_|alias> # tools are PER CONNECTION
60527
60352
  parall clip exec <clip> <tool> [json-args] --connection <ccn_|alias>
60528
60353
  \`\`\`
60529
60354
 
60355
+ - \`clip connections\` marks MCP rows with their auth mode, \`credential_set\`
60356
+ / \`oauth_status\` and \`tool_count\` \u2014 a \`needs_reauth\` or credential-less
60357
+ row will refuse exec until an org admin fixes it in the Clip Console.
60358
+ - \`--connection\` is REQUIRED to exec an MCP connection, exactly like a cloud
60359
+ profile \u2014 the only other target form, \`--edge\`, is a desktop device and
60360
+ never routes to MCP. The alias tells you WHICH account you act as \u2014
60361
+ always name it.
60362
+ (\`is_default\` marks the org's primary connection in listings and the
60363
+ Console, not an implicit exec route.)
60364
+ - \`clip tools\` without \`--connection\` reads the default connection's
60365
+ snapshot; with several connections and no default it asks you to name one.
60530
60366
  - No cold start: MCP clips never return \`EDGE_ACTIVATING\`.
60531
60367
  - \`MCP_TOOL_FAILED\` = the tool RAN and reported failure; a sanitized summary
60532
60368
  of its output rides in the error details. Read it and decide \u2014 do not
60533
60369
  blind-retry.
60534
60370
  - \`MCP_CONCURRENCY_LIMIT\` = not started; back off briefly, then retry.
60535
- - \`MCP_CONFIG_MISSING\` / \`MCP_DISABLED\` = the clip isn't configured, or MCP
60536
- is off for this deployment \u2014 ask an org admin; retrying won't help.
60371
+ - \`MCP_CONFIG_MISSING\` / \`MCP_DISABLED\` = that connection isn't configured,
60372
+ or MCP is off for this deployment \u2014 ask an org admin; retrying won't help.
60373
+ - \`MCP_OAUTH_REAUTH_REQUIRED\` = that connection's authorization expired or
60374
+ was disconnected \u2014 ask an org admin to re-authorize it in the Clip Console
60375
+ (name the connection's alias); retrying won't help.
60537
60376
  - \`OUTCOME_UNKNOWN\` follows the rule below: dispatched and MAY HAVE
60538
60377
  EXECUTED \u2014 never auto-retry.
60539
60378
 
@@ -60805,8 +60644,15 @@ and the folder is just a manifest:
60805
60644
  republishing.
60806
60645
  - Entering the credential / completing OAuth is a HUMAN step in the Clip
60807
60646
  Console (the config-write endpoints are session-only \u2014 an API key cannot
60808
- call them). Once configured, discover the live tool schemas with
60809
- \`parall clip tools <clip>\` and exec like any other clip.
60647
+ call them). An org can add SEVERAL connections to one MCP clip \u2014 one
60648
+ credential slot per account of the same service \u2014 all sharing the declared
60649
+ \`server_url\`/\`auth\`. Once configured, discover the live tool schemas with
60650
+ \`parall clip tools <clip> [--connection <ref>]\` and exec like any other
60651
+ clip (\`--connection\` picks the account).
60652
+ - Do NOT declare anything about OAuth client registration in the manifest \u2014
60653
+ there is no such field. Whether the provider needs a manually registered
60654
+ OAuth app (Google-style) is probed by the server at connect time; the
60655
+ Console walks the admin through it when required.
60810
60656
  - Publish is the same command: \`parall clip publish ./my-clip/\`.
60811
60657
 
60812
60658
  ## Cloud (hosted) vs desktop (BYOC) Edge
@@ -60880,6 +60726,80 @@ ${lines.join("\n")}
60880
60726
  `;
60881
60727
  }
60882
60728
 
60729
+ // ts/agent-core/dist/platform-instructions.js
60730
+ function buildBridgePlatformInstructions(workspaceDir, identity, capabilityFragments) {
60731
+ return renderPlatformInstructions({
60732
+ identity,
60733
+ runtimeAppendix: PLATFORM_BRIDGE_WORKSPACE_INSTRUCTIONS,
60734
+ capabilityFragments,
60735
+ skillReferences: buildSkillReferences(workspaceDir)
60736
+ });
60737
+ }
60738
+
60739
+ // ts/agent-core/dist/prompt-fragments.js
60740
+ function identityFromMe(me) {
60741
+ return {
60742
+ userId: me.id,
60743
+ displayName: me.display_name,
60744
+ title: me.public_profile?.title || void 0,
60745
+ publicDescription: me.public_profile?.description || void 0,
60746
+ // `||` on purpose: an empty-string instructions must also fall back to
60747
+ // the deprecated description alias (empty means "unset" on this wire).
60748
+ instructions: me.agent_profile?.instructions || me.agent_profile?.description || void 0
60749
+ };
60750
+ }
60751
+ function renderLocalAttachmentSection(section) {
60752
+ if (section.images.length === 0 && section.notes.length === 0)
60753
+ return "";
60754
+ const lines = ["[Local attachment files]"];
60755
+ for (const image of section.images) {
60756
+ lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
60757
+ }
60758
+ lines.push(...section.notes);
60759
+ return lines.join("\n");
60760
+ }
60761
+ function sanitizePromptMeta(value) {
60762
+ return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
60763
+ }
60764
+ function formatBytes(bytes) {
60765
+ if (bytes >= 1048576)
60766
+ return `${(bytes / 1048576).toFixed(1)}MB`;
60767
+ if (bytes >= 1024)
60768
+ return `${Math.round(bytes / 1024)}KB`;
60769
+ return `${bytes}B`;
60770
+ }
60771
+
60772
+ // ts/agent-core/dist/provider-config.js
60773
+ function llmSource(pc) {
60774
+ return effectiveLLMSourceExplicit(pc) || "parall";
60775
+ }
60776
+ function effectiveLLMSourceExplicit(pc) {
60777
+ if (pc?.llm_source)
60778
+ return pc.llm_source;
60779
+ if (pc?.openai_api_key || pc?.openai_base_url || pc?.anthropic_auth_token || pc?.anthropic_base_url) {
60780
+ return "custom";
60781
+ }
60782
+ return "";
60783
+ }
60784
+ function clearAllProviderCreds(env) {
60785
+ delete env.ANTHROPIC_AUTH_TOKEN;
60786
+ delete env.ANTHROPIC_BASE_URL;
60787
+ delete env.ANTHROPIC_API_KEY;
60788
+ delete env.OPENAI_API_KEY;
60789
+ delete env.OPENAI_BASE_URL;
60790
+ delete env.PRLL_CLAUDE_ALLOW_API_KEY;
60791
+ }
60792
+ function parseProviderConfig(env) {
60793
+ const raw = env.PRLL_PROVIDER_CONFIG?.trim();
60794
+ if (!raw)
60795
+ return void 0;
60796
+ try {
60797
+ return JSON.parse(raw);
60798
+ } catch (err) {
60799
+ throw new Error(`Invalid PRLL_PROVIDER_CONFIG JSON: ${String(err)}`);
60800
+ }
60801
+ }
60802
+
60883
60803
  // ts/claude-agent/dist/config.js
60884
60804
  import * as os2 from "node:os";
60885
60805
  import * as path6 from "node:path";
@@ -62811,24 +62731,14 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
62811
62731
  import * as fs9 from "node:fs";
62812
62732
  import * as path10 from "node:path";
62813
62733
  function buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
62814
- const parts = [
62815
- buildIdentity(agentIdentity),
62816
- BRIDGE_WORKSPACE_INSTRUCTIONS,
62817
- PRLL_BEHAVIOR,
62818
- PRLL_REFERENCE_GUIDE
62819
- ];
62820
- if (capabilityFragments && capabilityFragments.length > 0) {
62821
- parts.push(capabilityFragments.join("\n\n"));
62822
- }
62823
- parts.push(buildSkillReferences(workspaceDir));
62824
- return parts.join("\n\n");
62734
+ return buildBridgePlatformInstructions(workspaceDir, agentIdentity, capabilityFragments);
62825
62735
  }
62826
62736
  function writeClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
62827
62737
  const parallDir = path10.join(workspaceDir, ".parall");
62828
62738
  fs9.mkdirSync(parallDir, { recursive: true });
62829
62739
  fs9.writeFileSync(path10.join(parallDir, "system-prompt.md"), buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments), "utf8");
62830
62740
  }
62831
- function ensureClaudeWorkspace(workspaceDir, log2, agentIdentity, capabilityFragments) {
62741
+ function ensureClaudeWorkspace(workspaceDir, _log, agentIdentity, capabilityFragments) {
62832
62742
  fs9.mkdirSync(workspaceDir, { recursive: true });
62833
62743
  fs9.mkdirSync(path10.join(workspaceDir, ".claude"), { recursive: true });
62834
62744
  writeClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments);