@parall/parall 1.54.0 → 1.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -51276,19 +51276,419 @@ function resolveParallAccount(params) {
51276
51276
  };
51277
51277
  }
51278
51278
 
51279
- // ../agent-core/dist/lane-key.js
51279
+ // ../agent-core/dist/generated/platform-instructions.js
51280
+ var PLATFORM_IDENTITY_BASE = "## You on Parall\n\nParall is a shared workspace where humans and agents work side by side as equals.\nYou are a participant here, not a service. You hold tasks, own decisions, and are\naccountable for the work you take on \u2014 the same way a human teammate is.\n\nThe people and agents around you are collaborators, not users to serve. Be honest,\nbe direct, and care about the outcome of the work \u2014 not just the request in front\nof you.";
51281
+ 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.";
51282
+ var BEHAVIOR_TEMPLATE = "## How to work here\n\n### Move work forward\nDon't wait for instructions. If you see the next step, take it. If something is\nambiguous, clarify once and proceed. If you're blocked, say what's blocking you\n\u2014 don't go silent. Initiative is expected.\n\nUse schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered\nrequests, verifying something landed. When a thing needs future attention and\nnothing will prompt it, schedule it{{SCHEDULES_SKILL_HINT}}\n\n### Work in the open\nNothing you do exists until the system can see it. Your progress, decisions,\nblockers, and results need to live in tasks, comments, messages, or wiki pages\n\u2014 otherwise the organization is blind to your work, and so is the next agent\nwho picks up where you left off. Leave traces as you go, not at the end.\n\nFor non-trivial work: create or claim a task, mark it `in_progress`, comment\nwhen status materially changes, close it when done, and link the origin that\ntriggered it. Decompose multi-step work into subtasks and keep their statuses\ncurrent \u2014 progress should be auditable without watching the work happen.{{TASKS_SKILL_HINT}}\n\n### Done means landed\nProducing output does not complete a task. Work counts as done only when it has\ncleared its remaining gates \u2014 review, merge, deployment, the requester's\nverification. Until then keep the status honest (`in_progress` or\n`in_review`), name the remaining gate in a comment, and chase it (schedule a\nself-reminder if nothing else will prompt follow-up). Never mark done what a\nhuman still has to accept.\n\n### Sessions, forks, and what survives\nSessions end and context compacts. Anything that must survive \u2014 decisions,\nprogress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions\nread the workspace, not this conversation.\n\nSome events are handled by parallel fork sessions \u2014 short-lived copies of the\nsame agent identity with separate context. In a fork: leave a written trace of\nwhat was done or deliberately not done (other sessions cannot see fork\ncontext), and do not start long-running processes \u2014 they die with the fork.\nWhen an event is marked fork-handled: do not re-handle it; verify its outcome\ninstead of assuming it.\n\n### Communicate like a teammate\nMatch the conversation \u2014 concise in chat, thorough in docs, plain language over\njargon. Say what matters; stop when you're done. Don't narrate every tool call\nor pad replies to seem thorough.\n\nMatch the language of the person you're replying to. If someone writes in\nChinese, reply in Chinese. If in English, reply in English. Never force a\nlanguage switch unless explicitly asked.\n\nDo not promise delivery times (\"in an hour\", \"by tonight\") unless the work is\ndriven by an explicit schedule. Scope visibly; report when actually done.\n\n### Keep topics in threads\nCheck for a `[Thread: prll://msg_xxx]` line before interpreting a message.\nPresent \u2192 that thread is the context; reply there, passing the same root as\n`--thread-root-id`. Absent \u2192 the message belongs to the main conversation:\nnever treat it as continuing your most recent thread. The sender's newest\nmessage is the anchor \u2014 never route a reply back into an older thread just\nbecause the topic used to live there.\n\nReply where the event lives: a thread message gets a thread reply, a\ntop-level message gets a top-level reply. But in 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.";
51283
+ var REFERENCE_GUIDE_TEMPLATE = '## Parall References\n\nEvery entity on Parall has a `prll://` URI. Use these URIs to link related\nentities when you create or update tasks, comments, messages, and wiki files.\n\nAll three forms work \u2014 pick whichever fits:\n\n prll://tsk_abc bare URI (auto-linked)\n [](prll://tsk_abc) empty context (renders resolved title)\n [relevant context](prll://tsk_abc) with author annotation\n\nBare URIs and empty-context refs are preferred in most cases \u2014 the platform\nresolves and renders the entity title automatically.\n\n### Mentioning people and agents\n\nA real member mention is a `prll://usr_...` reference. Plain `@Display Name` is\nonly text: it does not notify a human or trigger an agent.\n\nWhen another member must be notified or an agent explicitly triggered, include\ntheir user reference in the message body. Prefer the empty-context form because\nthe platform resolves the member\'s current display name:\n\n [](prll://usr_xxx)\n\nUse `[Display Name](prll://usr_xxx)` when the surrounding sentence needs an\nexplicit label. Find the user ID in the incoming message or with\n`parall members list`. Never substitute plain `@Display Name` when notification\nor agent dispatch matters.\n\n### URI format\n\n`prll://` follows standard URI structure: `scheme://authority/path?query#fragment`.\n\n**Entities** \u2014 the entity ID is the authority:\n\n prll://usr_xxx user prll://prj_xxx project\n prll://tsk_xxx task prll://wik_xxx wiki\n prll://msg_xxx message prll://cmt_xxx comment\n prll://cht_xxx chat prll://tcm_xxx task comment (legacy)\n prll://att_xxx attachment prll://ase_xxx agent session\n prll://sch_xxx schedule prll://srn_xxx schedule run\n\n**Wiki** \u2014 path is file path, fragment is a typed anchor:\n\n prll://wik_xxx/docs/guide.md file\n prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)\n prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)\n\n Anchor types: `h=` heading, `l=` line/range, `s=` symbol.\n Line anchors in persistent content require `?rev=<full-40-char-sha>`.\n\n**Chat message range**:\n\n prll://cht_xxx#range=msg_01HA,msg_01HZ\n\n**Field access** \u2014 path selects a field (omit to reference the entity itself):\n\n prll://tsk_xxx/description#Implementation heading within task description\n\n### Unread context\n\nWhen dispatched to a chat, you may see `[Unread: N messages | since: prll://msg_xxx]`.\nThis shows messages since your last interaction \u2014 your read cursor advances after each\ndispatch, so context you skip now won\'t appear as unread next time. Use\n`parall messages list <chat> --limit 20` to fetch recent context. For large unread\ncounts (50+), fetch only recent messages rather than everything.\n\nThread dispatches may show `[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]`.\nSame semantics \u2014 use `parall messages list <chat> --thread-root-id <thread_root> --limit 20` to\ncatch up on the thread.\n\n### Reading context on demand\n\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.';
51284
+ var BRIDGE_SKILL_HINTS = {
51285
+ SCHEDULES_SKILL_HINT: " (read the `parall-schedules` skill at .parall/skills/parall-schedules.md).",
51286
+ TASKS_SKILL_HINT: "\nDetails: read the `parall-tasks` skill at .parall/skills/parall-tasks.md and follow it.",
51287
+ PLATFORM_SKILL_HINT: "\nDetails: read the `parall-platform` skill at .parall/skills/parall-platform.md."
51288
+ };
51289
+ function sanitizeProfileField(value) {
51290
+ return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
51291
+ }
51292
+ function sanitizeProfileBlock(value) {
51293
+ return value.replace(/\r\n?/g, "\n").trim();
51294
+ }
51295
+ function renderTemplate(template, values) {
51296
+ return template.replace(/\{\{([A-Z_]+)\}\}/g, (_match, token) => {
51297
+ const value = values[token];
51298
+ if (value === void 0)
51299
+ throw new Error(`missing generated platform instruction token: ${token}`);
51300
+ return value;
51301
+ });
51302
+ }
51303
+ function renderPlatformBehavior(skillsAvailable) {
51304
+ return renderTemplate(BEHAVIOR_TEMPLATE, {
51305
+ SCHEDULES_SKILL_HINT: skillsAvailable ? BRIDGE_SKILL_HINTS.SCHEDULES_SKILL_HINT : ".",
51306
+ TASKS_SKILL_HINT: skillsAvailable ? BRIDGE_SKILL_HINTS.TASKS_SKILL_HINT : ""
51307
+ });
51308
+ }
51309
+ function renderPlatformReferenceGuide(skillsAvailable) {
51310
+ return renderTemplate(REFERENCE_GUIDE_TEMPLATE, {
51311
+ PLATFORM_SKILL_HINT: skillsAvailable ? BRIDGE_SKILL_HINTS.PLATFORM_SKILL_HINT : ""
51312
+ });
51313
+ }
51314
+ var PLATFORM_BEHAVIOR = renderPlatformBehavior(true);
51315
+ var PLATFORM_REFERENCE_GUIDE = renderPlatformReferenceGuide(true);
51316
+ function renderPlatformIdentity(agent) {
51317
+ if (!agent)
51318
+ return PLATFORM_IDENTITY_BASE;
51319
+ const publicLines = [];
51320
+ const title = agent.title ? sanitizeProfileField(agent.title) : "";
51321
+ if (title)
51322
+ publicLines.push(`Title: ${title}`);
51323
+ const about = agent.publicDescription ? sanitizeProfileField(agent.publicDescription) : "";
51324
+ if (about)
51325
+ publicLines.push(`About: ${about}`);
51326
+ const instructions = sanitizeProfileBlock(agent.instructions || agent.description || "");
51327
+ const suffix = renderTemplate(IDENTITY_PROFILE_SUFFIX, {
51328
+ DISPLAY_NAME: sanitizeProfileField(agent.displayName),
51329
+ USER_ID: agent.userId,
51330
+ PUBLIC_PROFILE: publicLines.length > 0 ? `
51331
+ ${publicLines.join("\n")}` : "",
51332
+ INSTRUCTIONS_SECTION: instructions ? `
51333
+
51334
+ ### Private instructions from your organization admins
51335
+
51336
+ ${instructions}` : ""
51337
+ });
51338
+ return `${PLATFORM_IDENTITY_BASE}
51339
+
51340
+ ${suffix}`;
51341
+ }
51342
+
51343
+ // ../agent-core/dist/bridge-workspace.js
51344
+ function extractShellCommand(input) {
51345
+ if (!input || typeof input !== "object")
51346
+ return void 0;
51347
+ const command = input.command;
51348
+ return typeof command === "string" && command.trim() ? command.trim() : void 0;
51349
+ }
51350
+ function parseParallCliInvocation(command) {
51351
+ const tokens = command.replace(/\s+/g, " ").trim().split(" ");
51352
+ let i = 0;
51353
+ if (tokens[i] === "parall") {
51354
+ i++;
51355
+ } else if (tokens[i] === "npx") {
51356
+ i++;
51357
+ while (i < tokens.length && tokens[i].startsWith("-"))
51358
+ i++;
51359
+ if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
51360
+ return null;
51361
+ i++;
51362
+ } else if (tokens[i] === "pnpm") {
51363
+ i++;
51364
+ if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
51365
+ i++;
51366
+ if (i >= tokens.length || tokens[i] !== "parall")
51367
+ return null;
51368
+ i++;
51369
+ } else {
51370
+ return null;
51371
+ }
51372
+ return tokens.slice(i).filter((t) => !t.startsWith("-"));
51373
+ }
51374
+ function isParallSendCommand(command) {
51375
+ if (!command)
51376
+ return false;
51377
+ const sub = parseParallCliInvocation(command);
51378
+ if (!sub || sub.length === 0)
51379
+ return false;
51380
+ return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
51381
+ }
51382
+ function isParallNoReplyCommand(command) {
51383
+ if (!command)
51384
+ return false;
51385
+ const sub = parseParallCliInvocation(command);
51386
+ return sub?.[0] === "no-reply";
51387
+ }
51388
+
51389
+ // ../agent-core/dist/channel-capability.js
51390
+ import * as fs from "node:fs";
51280
51391
  import * as path from "node:path";
51281
- function laneKeyForTarget(targetUri, threadRootId) {
51282
- return Buffer.from(`${targetUri}
51283
- ${threadRootId ?? ""}`, "utf8").toString("base64url");
51392
+ import { fileURLToPath } from "node:url";
51393
+ var CAPABILITY_FEISHU_CLI = "feishu-cli";
51394
+ var CAPABILITY_SLACK_SEND = "slack-send";
51395
+ var CAPABILITY_WECHAT_SEND = "wechat-send";
51396
+ function channelCapabilityKeyFor(provider) {
51397
+ if (provider === "slack")
51398
+ return CAPABILITY_SLACK_SEND;
51399
+ if (provider === "wechat")
51400
+ return CAPABILITY_WECHAT_SEND;
51401
+ return `${provider}-cli`;
51402
+ }
51403
+ var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
51404
+ function capabilityBinDir(stateDir) {
51405
+ return path.join(stateDir, "bin");
51406
+ }
51407
+ function channelExecEntryPath() {
51408
+ const selfDir = path.dirname(fileURLToPath(import.meta.url));
51409
+ const sibling = path.join(selfDir, "parall-channel-exec.js");
51410
+ if (fs.existsSync(sibling))
51411
+ return sibling;
51412
+ return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
51413
+ }
51414
+ function materializeChannelCapabilities(stateDir, capabilities, log) {
51415
+ try {
51416
+ reconcileFeishuCli(stateDir, capabilities, log);
51417
+ } catch (err) {
51418
+ log?.warn(`channel capability materialization failed: ${String(err)}`);
51419
+ }
51420
+ }
51421
+ function reconcileFeishuCli(stateDir, capabilities, log) {
51422
+ const binDir = capabilityBinDir(stateDir);
51423
+ const posixPath = path.join(binDir, "lark-cli");
51424
+ const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
51425
+ const hadPointer = fs.existsSync(posixPath);
51426
+ if (!granted && !hadPointer)
51427
+ return;
51428
+ fs.mkdirSync(binDir, { recursive: true });
51429
+ const entry = channelExecEntryPath();
51430
+ const nodeExec = process.execPath;
51431
+ writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log);
51432
+ writePointerIfChanged(path.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log);
51433
+ }
51434
+ function writePointerIfChanged(filePath, content, log) {
51435
+ let existing = null;
51436
+ try {
51437
+ existing = fs.readFileSync(filePath, "utf8");
51438
+ } catch {
51439
+ existing = null;
51440
+ }
51441
+ if (existing !== content) {
51442
+ fs.writeFileSync(filePath, content, { mode: 493 });
51443
+ log?.info(`channel capability: pointer materialized (${path.basename(filePath)})`);
51444
+ }
51445
+ fs.chmodSync(filePath, 493);
51446
+ }
51447
+ function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
51448
+ return [
51449
+ "#!/bin/sh",
51450
+ `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
51451
+ "# Credential + exec logic lives in the agent-core package; revocation is",
51452
+ "# enforced by the platform mint endpoint, so this pointer stays constant.",
51453
+ // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
51454
+ // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
51455
+ // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
51456
+ // the mint. The pointer is a platform-authored trust-boundary artifact whose
51457
+ // whole job is a CONTROLLED launch of the broker (absolute node, magic
51458
+ // guard, skip-dir); this closes the same env-hijack class for node startup
51459
+ // that the absolute node path closes for PATH, keeping the launch deterministic.
51460
+ "unset NODE_OPTIONS NODE_PATH",
51461
+ // "$@" preserves argv exactly (this is the agent's main path via git-bash).
51462
+ `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
51463
+ ""
51464
+ ].join("\n");
51465
+ }
51466
+ function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
51467
+ return [
51468
+ "@echo off",
51469
+ `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
51470
+ // Clear Node preload-hijack vars before launching node (see the sh pointer).
51471
+ 'set "NODE_OPTIONS="',
51472
+ 'set "NODE_PATH="',
51473
+ `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
51474
+ ""
51475
+ ].join("\r\n");
51476
+ }
51477
+
51478
+ // ../agent-core/dist/dispatch-adapter.js
51479
+ function buildErrorStepContent(message) {
51480
+ return { text: message, suppressed: false, status: "error" };
51481
+ }
51482
+
51483
+ // ../agent-core/dist/event-format.js
51484
+ function sanitizeMeta(value) {
51485
+ return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
51486
+ }
51487
+ function buildEventBody(event) {
51488
+ const lines = [];
51489
+ if (event.type === "message") {
51490
+ lines.push(`[Event: message.new]`);
51491
+ const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
51492
+ lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
51493
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51494
+ lines.push(`[Message ID: prll://${event.messageId}]`);
51495
+ if (event.threadRootId) {
51496
+ const threadMeta = [
51497
+ `prll://${event.threadRootId}`,
51498
+ event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
51499
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
51500
+ event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
51501
+ ].filter(Boolean).join(" | ");
51502
+ lines.push(`[Thread: ${threadMeta}]`);
51503
+ }
51504
+ if (event.unreadCount != null && event.unreadCount > 1) {
51505
+ const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
51506
+ const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
51507
+ let line = `[Unread: ${countStr} messages${sinceStr}]`;
51508
+ if (event.unreadCount > 50)
51509
+ line += ` \u2014 fetch recent context with --limit, not all`;
51510
+ lines.push(line);
51511
+ }
51512
+ if (event.noReply)
51513
+ lines.push(`[Hint: no_reply]`);
51514
+ if (event.attachments?.length) {
51515
+ for (const att of event.attachments) {
51516
+ const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
51517
+ lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
51518
+ }
51519
+ }
51520
+ lines.push("", event.body);
51521
+ } else if (event.type === "task_comment") {
51522
+ lines.push(`[Event: task.comment.created]`);
51523
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
51524
+ lines.push(`[Task: ${taskLabel}]`);
51525
+ if (event.deliveryReason)
51526
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51527
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51528
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
51529
+ lines.push("", event.body);
51530
+ } else if (event.type === "wiki_comment") {
51531
+ lines.push(`[Event: wiki.comment.created]`);
51532
+ const target = event.replyTargetUri ?? `prll://${event.targetId}`;
51533
+ if (event.targetType === "changeset") {
51534
+ lines.push(`[Wiki Changeset: ${target}]`);
51535
+ } else {
51536
+ lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
51537
+ }
51538
+ if (event.deliveryReason)
51539
+ lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51540
+ lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51541
+ lines.push(`[Comment ID: prll://${event.messageId}]`);
51542
+ lines.push("", event.body);
51543
+ } else if (event.type === "approval") {
51544
+ lines.push(`[Event: approval.decided]`);
51545
+ lines.push(`[Approval: prll://${event.messageId}]`);
51546
+ lines.push(`[Chat: prll://${event.targetId}]`);
51547
+ lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
51548
+ lines.push("", event.body);
51549
+ } else if (event.type === "schedule") {
51550
+ lines.push(`[Event: schedule.fired]`);
51551
+ lines.push(`[Schedule: prll://${event.targetId}]`);
51552
+ lines.push(`[Run: prll://${event.messageId}]`);
51553
+ if (event.scheduledFireAt)
51554
+ lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
51555
+ if (event.attachedUri)
51556
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
51557
+ lines.push("", event.body);
51558
+ } else if (event.type === "channel_message") {
51559
+ lines.push(`[Event: channel.message]`);
51560
+ const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
51561
+ const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
51562
+ lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
51563
+ lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
51564
+ if (event.channelExternalMessageId) {
51565
+ lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
51566
+ }
51567
+ 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.]`);
51568
+ lines.push("", event.body);
51569
+ } else if (event.type === "external_trigger") {
51570
+ lines.push(`[Event: external.trigger]`);
51571
+ lines.push(`[Trigger: prll://${event.targetId}]`);
51572
+ lines.push(`[Run: prll://${event.messageId}]`);
51573
+ if (event.externalConnectionId) {
51574
+ const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
51575
+ lines.push(`[Connection: ${label}]`);
51576
+ }
51577
+ if (event.externalIngressEventId)
51578
+ lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
51579
+ if (event.attachedUri)
51580
+ lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
51581
+ if (event.externalConnectionSourceType) {
51582
+ lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
51583
+ }
51584
+ if (event.externalIngressEventType) {
51585
+ lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
51586
+ }
51587
+ lines.push("", event.body);
51588
+ } else {
51589
+ lines.push(`[Event: task.assigned]`);
51590
+ const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
51591
+ lines.push(`[Task: ${taskLabel}]`);
51592
+ lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
51593
+ lines.push("", event.body);
51594
+ }
51595
+ return lines.join("\n") + buildSendMessageHint(event);
51596
+ }
51597
+ function buildEventBodyForForkResult(event) {
51598
+ return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
51599
+ }
51600
+ function buildSendMessageHint(event) {
51601
+ if (event.noReply)
51602
+ return "";
51603
+ if (event.type === "wiki_comment" && event.replyTargetUri) {
51604
+ const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
51605
+ return `
51606
+ <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>`;
51607
+ }
51608
+ if (event.targetId.startsWith("cht_")) {
51609
+ if (event.threadRootId) {
51610
+ return `
51611
+ <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>`;
51612
+ }
51613
+ return `
51614
+ <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>`;
51615
+ }
51616
+ if (event.targetId.startsWith("tsk_")) {
51617
+ return `
51618
+ <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>`;
51619
+ }
51620
+ if (event.targetId.startsWith("sch_")) {
51621
+ return `
51622
+ <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
51623
+ }
51624
+ if (event.type === "channel_message") {
51625
+ if (event.channelCliCapable) {
51626
+ if (event.channelProvider === "slack") {
51627
+ const channelArg = event.channelExternalConversationId ? ` --channel "${event.channelExternalConversationId}"` : " --channel <conversation id from this event>";
51628
+ const replyTo = event.channelExternalMessageId ? ` --reply-to "${event.channelExternalMessageId}"` : "";
51629
+ return `
51630
+ <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>`;
51631
+ }
51632
+ if (event.channelProvider === "wechat") {
51633
+ const toArg = event.channelExternalConversationId ? ` --to "${event.channelExternalConversationId}"` : " --to <wxid from this event>";
51634
+ const atArg = event.channelConversationType === "group" ? event.senderId && event.senderId !== "external" ? ` --at "${event.senderId}"` : " --at <wxid of the person you are answering>" : "";
51635
+ return `
51636
+ <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>`;
51637
+ }
51638
+ if (!event.channelProvider) {
51639
+ return `
51640
+ <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>`;
51641
+ }
51642
+ const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
51643
+ const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
51644
+ return `
51645
+ <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>`;
51646
+ }
51647
+ const platform = event.channelProvider ?? "the external platform";
51648
+ return `
51649
+ <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>`;
51650
+ }
51651
+ if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
51652
+ return `
51653
+ <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>`;
51654
+ }
51655
+ return "";
51284
51656
  }
51285
- function dispatchLaneContextDir(stateDir) {
51286
- return path.join(stateDir, "dispatch-lane-context");
51657
+ function buildForkScopePrefix(event) {
51658
+ const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
51659
+ 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.
51660
+
51661
+ 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.
51662
+
51663
+ End with a brief "Fork summary" of actions taken and decisions made.]
51664
+
51665
+ `;
51287
51666
  }
51288
- function laneContextFilePath(contextDir, targetUri, threadRootId) {
51289
- return path.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
51667
+ function buildForkResultPrefix(results) {
51668
+ if (!results.length)
51669
+ return "";
51670
+ const blocks = results.map((result) => {
51671
+ const lines = [];
51672
+ for (const body of result.eventBodies) {
51673
+ lines.push(body);
51674
+ }
51675
+ lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
51676
+ 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."}]`);
51677
+ if (result.actions.length)
51678
+ lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
51679
+ if (result.historyPath)
51680
+ lines.push(`[Fork history: ${result.historyPath}]`);
51681
+ return lines.join("\n");
51682
+ });
51683
+ return blocks.join("\n\n") + "\n\n---\n\n";
51290
51684
  }
51291
51685
 
51686
+ // ../agent-core/dist/gateway-base.js
51687
+ import * as os from "node:os";
51688
+ import * as fs3 from "node:fs";
51689
+ import * as path3 from "node:path";
51690
+ import { randomUUID } from "node:crypto";
51691
+
51292
51692
  // ../sdk/dist/browser-viewer.js
51293
51693
  var BROWSER_VIEWER_READINESS_TIMEOUT_MS = 6e4;
51294
51694
  function browserViewerRequestOptions(command, opts) {
@@ -51330,6 +51730,9 @@ var ENDPOINTS = {
51330
51730
  ORG_MEMBERS: (orgId) => `${API_BASE}/orgs/${orgId}/members`,
51331
51731
  ORG_MEMBERS_FORMER: (orgId) => `${API_BASE}/orgs/${orgId}/members/former`,
51332
51732
  TEAMS: (orgId) => `${API_BASE}/orgs/${orgId}/teams`,
51733
+ TEAM: (orgId, teamId) => `${API_BASE}/orgs/${orgId}/teams/${teamId}`,
51734
+ TEAM_MEMBERS: (orgId, teamId) => `${API_BASE}/orgs/${orgId}/teams/${teamId}/members`,
51735
+ TEAM_MEMBER: (orgId, teamId, userId) => `${API_BASE}/orgs/${orgId}/teams/${teamId}/members/${userId}`,
51333
51736
  ORG_MEMBERS_ONLINE: (orgId) => `${API_BASE}/orgs/${orgId}/members/online`,
51334
51737
  ORG_MEMBER: (orgId, userId) => `${API_BASE}/orgs/${orgId}/members/${userId}`,
51335
51738
  ORG_MEMBER_CHATS: (orgId, memberId) => `${API_BASE}/orgs/${orgId}/members/${memberId}/chats`,
@@ -51452,6 +51855,7 @@ var ENDPOINTS = {
51452
51855
  MACHINES_ME_BROWSER_PROFILE_VIEWER_RESPONSE: (requestId) => `${API_BASE}/machines/me/browser-profiles/viewer-response/${requestId}`,
51453
51856
  // Tasks (org-scoped)
51454
51857
  TASKS: (orgId) => `${API_BASE}/orgs/${orgId}/tasks`,
51858
+ TASK_SUBTASK_SUMMARY: (orgId) => `${API_BASE}/orgs/${orgId}/tasks/subtask-summary`,
51455
51859
  TASK: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}`,
51456
51860
  TASK_ARCHIVE: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/archive`,
51457
51861
  TASK_RESTORE: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/restore`,
@@ -51465,9 +51869,22 @@ var ENDPOINTS = {
51465
51869
  TASK_COMMENTS: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/comments`,
51466
51870
  TASK_COMMENT: (orgId, taskId, commentId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/comments/${commentId}`,
51467
51871
  TASK_ACTIVITIES: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/activities`,
51872
+ TASK_LABELS: (orgId, taskId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/labels`,
51873
+ TASK_LABEL: (orgId, taskId, labelId) => `${API_BASE}/orgs/${orgId}/tasks/${taskId}/labels/${labelId}`,
51874
+ // Labels (org-scoped vocabulary; writes are admin-gated)
51875
+ LABELS: (orgId) => `${API_BASE}/orgs/${orgId}/labels`,
51876
+ LABEL: (orgId, labelId) => `${API_BASE}/orgs/${orgId}/labels/${labelId}`,
51468
51877
  // Projects (org-scoped)
51469
51878
  PROJECTS: (orgId) => `${API_BASE}/orgs/${orgId}/projects`,
51879
+ PROJECT_TASK_SUMMARY: (orgId) => `${API_BASE}/orgs/${orgId}/projects/task-summary`,
51470
51880
  PROJECT: (orgId, projectId) => `${API_BASE}/orgs/${orgId}/projects/${projectId}`,
51881
+ PROJECT_MEMBERS: (orgId, projectId) => `${API_BASE}/orgs/${orgId}/projects/${projectId}/members`,
51882
+ PROJECT_READERS: (orgId, projectId) => `${API_BASE}/orgs/${orgId}/projects/${projectId}/readers`,
51883
+ PROJECT_LIBRARY: (orgId) => `${API_BASE}/orgs/${orgId}/projects/library`,
51884
+ PROJECT_JOIN: (orgId, projectId) => `${API_BASE}/orgs/${orgId}/projects/${projectId}/join`,
51885
+ PROJECT_JOIN_REQUESTS: (orgId, projectId) => `${API_BASE}/orgs/${orgId}/projects/${projectId}/join-requests`,
51886
+ // subject is a bare user ID or a bare team ID; both are path-segment safe.
51887
+ PROJECT_MEMBER: (orgId, projectId, subject) => `${API_BASE}/orgs/${orgId}/projects/${projectId}/members/${subject}`,
51471
51888
  // Schedules (org-scoped, platform time trigger primitive)
51472
51889
  SCHEDULES: (orgId) => `${API_BASE}/orgs/${orgId}/schedules`,
51473
51890
  SCHEDULE: (orgId, id) => `${API_BASE}/orgs/${orgId}/schedules/${id}`,
@@ -51509,8 +51926,10 @@ var ENDPOINTS = {
51509
51926
  SLACK_HISTORY: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/slack/history`,
51510
51927
  SLACK_MEMBERS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/slack/members`,
51511
51928
  SLACK_STATUS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/slack/status`,
51512
- // WeChat tier-B read verb (agent-only; internal research preview).
51929
+ // WeChat tier-B read verbs (agent-only; internal research preview).
51513
51930
  WECHAT_CONTACTS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/contacts`,
51931
+ WECHAT_PROFILE: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/profile`,
51932
+ WECHAT_STATUS: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/wechat/status`,
51514
51933
  // Invitations (org-scoped, admin)
51515
51934
  ORG_INVITATIONS: (orgId) => `${API_BASE}/orgs/${orgId}/invitations`,
51516
51935
  ORG_INVITATION: (orgId, invId) => `${API_BASE}/orgs/${orgId}/invitations/${invId}`,
@@ -51624,8 +52043,10 @@ var ENDPOINTS = {
51624
52043
  NOTIFICATION_PREFERENCES: `${API_BASE}/notification-preferences`,
51625
52044
  // Unified search (messages + tasks + wiki, org-scoped)
51626
52045
  SEARCH: (orgId) => `${API_BASE}/orgs/${orgId}/search`,
51627
- // Feature flags (org-scoped, server-evaluated)
51628
- FEATURE_FLAGS: (orgId) => `${API_BASE}/orgs/${orgId}/feature-flags`,
52046
+ // Feature flags (server-evaluated). Org-scoped by default; omit the org for
52047
+ // the pre-org form, which resolves "cap:" capabilities only (PostHog flags
52048
+ // are org-scoped and absent there) for callers that have no org yet.
52049
+ FEATURE_FLAGS: (orgId) => orgId ? `${API_BASE}/orgs/${orgId}/feature-flags` : `${API_BASE}/feature-flags`,
51629
52050
  // Team templates (org-scoped, owner/admin only)
51630
52051
  TEMPLATES: (orgId) => `${API_BASE}/orgs/${orgId}/templates`,
51631
52052
  TEMPLATE: (orgId, templateId) => `${API_BASE}/orgs/${orgId}/templates/${templateId}`,
@@ -51681,6 +52102,9 @@ var ENDPOINTS = {
51681
52102
  ORG_EDGE_PROFILES: (orgId, edgeId) => `/api/v1/orgs/${orgId}/edge/${edgeId}/profiles`,
51682
52103
  // Per-profile egress proxy (hosted Cloud Profiles; manager-only, human-only).
51683
52104
  ORG_EDGE_PROFILE_PROXY: (orgId, edgeId, profileName) => `/api/v1/orgs/${orgId}/edge/${edgeId}/profiles/${encodeURIComponent(profileName)}/proxy`,
52105
+ // Per-profile one-shot cookie seed (hosted Cloud Profiles; manager-only,
52106
+ // human-only, idle-only). Injected at the next cold start, then consumed.
52107
+ ORG_EDGE_PROFILE_COOKIES: (orgId, edgeId, profileName) => `/api/v1/orgs/${orgId}/edge/${edgeId}/profiles/${encodeURIComponent(profileName)}/cookies`,
51684
52108
  ORG_EDGE_EXEC: (orgId) => `/api/v1/orgs/${orgId}/edge/exec`,
51685
52109
  // Cloud Edge live viewer command (V1b) — api-server, gated on cap:edge-viewer.
51686
52110
  // Same request/reply shape as the v2 browser-profile viewer, on the v3 edge
@@ -51695,10 +52119,11 @@ var ENDPOINTS = {
51695
52119
  ORG_CLIP_INSTALL: (orgId) => `/api/v1/orgs/${orgId}/clips/install`,
51696
52120
  ORG_CLIPS_INSTALLED: (orgId) => `/api/v1/orgs/${orgId}/clips/installed`,
51697
52121
  ORG_CLIP_UNINSTALL: (orgId, clipId) => `/api/v1/orgs/${orgId}/clips/${clipId}/uninstall`,
52122
+ ORG_CLIP_MCP_REMOVE: (orgId, clipId) => `/api/v1/orgs/${orgId}/clips/${clipId}/mcp-remove`,
51698
52123
  // Per-org agent exec access for one clip (default all agents; PUT human-only)
51699
52124
  ORG_CLIP_EXEC_ACCESS: (orgId, clipId) => `/api/v1/orgs/${orgId}/clips/${clipId}/exec-access`,
51700
- // MCP clip server config (cap:clip-mcp; publisher-org only cross-org gets
51701
- // 403 MCP_CROSS_ORG_DISABLED on the whole family, reads included). The
52125
+ // MCP clip server config (cap:clip-mcp; cross-org is limited to installed,
52126
+ // reviewed Official OAuth Clips). The
51702
52127
  // singular family addresses the org's DEFAULT connection (pre-165
51703
52128
  // back-compat shim); the plural family is the multi-connection surface —
51704
52129
  // one config row (credential slot) per connection, addressed by config id.
@@ -51710,95 +52135,296 @@ var ENDPOINTS = {
51710
52135
  ORG_CLIP_MCP_TOOLS_REFRESH_BY_ID: (orgId, clipId, configId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-configs/${configId}/tools/refresh`,
51711
52136
  ORG_CLIP_MCP_OAUTH_DISCONNECT_BY_ID: (orgId, clipId, configId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-configs/${configId}/oauth/disconnect`
51712
52137
  };
51713
- var WS_EVENTS = {
51714
- // Client -> Server
51715
- PING: "ping",
51716
- TYPING: "typing",
51717
- WATCH: "watch",
51718
- AGENT_HEARTBEAT: "agent.heartbeat",
51719
- // Server -> Client
51720
- HELLO: "hello",
51721
- PONG: "pong",
51722
- WATCHING: "watching",
51723
- MESSAGE_NEW: "message.new",
51724
- MESSAGE_PATCH: "message.patch",
51725
- MESSAGE_EDIT: "message.edit",
51726
- MESSAGE_DELETE: "message.delete",
51727
- MESSAGE_REACTION_UPDATED: "message.reaction.updated",
51728
- TYPING_UPDATE: "typing.update",
51729
- CHAT_UPDATE: "chat.update",
51730
- CHAT_DELETED: "chat.deleted",
51731
- APPROVAL_UPDATE: "approval.update",
51732
- // deprecated
51733
- CARD_UPDATE: "card.update",
51734
- RECOVERY_OVERFLOW: "recovery.overflow",
51735
- MEMBERSHIP_CHANGED: "membership.changed",
51736
- TASK_CREATED: "task.created",
51737
- TASK_UPDATED: "task.updated",
51738
- TASK_DELETED: "task.deleted",
51739
- TASK_COMMENT_CREATED: "task.comment.created",
51740
- TASK_COMMENT_UPDATED: "task.comment.updated",
51741
- TASK_COMMENT_DELETED: "task.comment.deleted",
51742
- PROJECT_CREATED: "project.created",
51743
- PROJECT_UPDATED: "project.updated",
51744
- PROJECT_DELETED: "project.deleted",
51745
- AGENT_SESSION_NEW: "agent_session.new",
51746
- AGENT_SESSION_UPDATE: "agent_session.update",
51747
- AGENT_STEP_NEW: "agent_step.new",
51748
- INVITATION_NEW: "invitation.new",
51749
- INVITATION_ACCEPTED: "invitation.accepted",
51750
- INVITATION_DECLINED: "invitation.declined",
51751
- INVITATION_REVOKED: "invitation.revoked",
51752
- ORG_JOIN_REQUEST_NEW: "org.join_request.new",
51753
- ORG_INVITE_LINK_JOINED: "org.invite_link.joined",
51754
- ORG_MEMBER_REMOVED: "org.member.removed",
51755
- AGENT_CONFIG_UPDATE: "agent_config.update",
51756
- PRESENCE_UPDATE: "presence.update",
51757
- WIKI_CHANGESET_CREATED: "wiki.changeset.created",
51758
- WIKI_CHANGESET_UPDATED: "wiki.changeset.updated",
51759
- WIKI_DELETED: "wiki.deleted",
51760
- WIKI_RESTORED: "wiki.restored",
51761
- COMMENT_CREATED: "comment.created",
51762
- COMMENT_UPDATED: "comment.updated",
51763
- COMMENT_DELETED: "comment.deleted",
51764
- NOTIFICATION_ALERT: "notification.alert",
51765
- INBOX_NEW: "inbox.new",
51766
- INBOX_UPDATE: "inbox.update",
51767
- INBOX_BULK_UPDATE: "inbox.bulk_update",
51768
- READ_POSITION_UPDATED: "read_position.updated",
51769
- THREAD_READ_POSITION_UPDATED: "thread_read_position.updated",
51770
- DISPATCH_NEW: "dispatch.new",
51771
- DISPATCH_RECEIVED: "dispatch.received",
51772
- DISPATCH_RESOLVED: "dispatch.resolved",
51773
- SCHEDULE_CREATED: "schedule.created",
51774
- SCHEDULE_UPDATED: "schedule.updated",
51775
- SCHEDULE_DELETED: "schedule.deleted",
51776
- SCHEDULE_FIRED: "schedule.fired",
51777
- BILLING_BALANCE_UPDATED: "billing.balance_updated",
51778
- BILLING_LOW_BALANCE: "billing.low_balance",
51779
- BILLING_MACHINE_STOPPED: "billing.machine_stopped",
51780
- BILLING_INSUFFICIENT: "billing.insufficient",
51781
- USER_UPDATED: "user.updated",
51782
- MACHINE_HELLO: "machine.hello",
51783
- MACHINE_AGENT_ATTACHED: "machine.agent.attached",
51784
- MACHINE_AGENT_DETACHED: "machine.agent.detached",
51785
- MACHINE_STOP: "machine.stop",
51786
- MACHINE_WORKSPACE_SETUP_REQUESTED: "machine.workspace.setup.requested",
51787
- MACHINE_FILESYSTEM_BROWSE: "machine.filesystem.browse",
51788
- MACHINE_UPDATE: "machine.update",
51789
- MACHINE_CONFIG_UPDATED: "machine.config.updated",
51790
- MACHINE_AGENT_CONFIG_UPDATED: "machine.agent_config.updated",
51791
- MACHINE_CLIP_SYNC: "machine.clip.sync",
51792
- MACHINE_BROWSER_PROFILE_LIFECYCLE: "machine.browser_profile.lifecycle",
51793
- MACHINE_BROWSER_PROFILE_VIEWER: "machine.browser_profile.viewer",
51794
- AGENT_NEW_SESSION: "agent.new_session",
51795
- CLIP_CREATED: "clip.created",
51796
- CLIP_REMOVED: "clip.removed",
51797
- CLIP_UPDATED: "clip.updated"
52138
+ var WS_EVENTS = {
52139
+ // Client -> Server
52140
+ PING: "ping",
52141
+ TYPING: "typing",
52142
+ WATCH: "watch",
52143
+ AGENT_HEARTBEAT: "agent.heartbeat",
52144
+ // Server -> Client
52145
+ HELLO: "hello",
52146
+ PONG: "pong",
52147
+ WATCHING: "watching",
52148
+ MESSAGE_NEW: "message.new",
52149
+ /** @deprecated `message.patch` is retired and never published; kept for compile compatibility. */
52150
+ MESSAGE_PATCH: "message.patch",
52151
+ MESSAGE_EDIT: "message.edit",
52152
+ MESSAGE_DELETE: "message.delete",
52153
+ MESSAGE_REACTION_UPDATED: "message.reaction.updated",
52154
+ TYPING_UPDATE: "typing.update",
52155
+ CHAT_UPDATE: "chat.update",
52156
+ CHAT_DELETED: "chat.deleted",
52157
+ APPROVAL_UPDATE: "approval.update",
52158
+ // deprecated
52159
+ CARD_UPDATE: "card.update",
52160
+ RECOVERY_OVERFLOW: "recovery.overflow",
52161
+ MEMBERSHIP_CHANGED: "membership.changed",
52162
+ TASK_CREATED: "task.created",
52163
+ TASK_UPDATED: "task.updated",
52164
+ TASK_DELETED: "task.deleted",
52165
+ TASK_COMMENT_CREATED: "task.comment.created",
52166
+ TASK_COMMENT_UPDATED: "task.comment.updated",
52167
+ TASK_COMMENT_DELETED: "task.comment.deleted",
52168
+ PROJECT_CREATED: "project.created",
52169
+ PROJECT_UPDATED: "project.updated",
52170
+ PROJECT_DELETED: "project.deleted",
52171
+ LABEL_CREATED: "label.created",
52172
+ LABEL_UPDATED: "label.updated",
52173
+ LABEL_DELETED: "label.deleted",
52174
+ AGENT_SESSION_NEW: "agent_session.new",
52175
+ AGENT_SESSION_UPDATE: "agent_session.update",
52176
+ AGENT_STEP_NEW: "agent_step.new",
52177
+ INVITATION_NEW: "invitation.new",
52178
+ INVITATION_ACCEPTED: "invitation.accepted",
52179
+ INVITATION_DECLINED: "invitation.declined",
52180
+ INVITATION_REVOKED: "invitation.revoked",
52181
+ ORG_JOIN_REQUEST_NEW: "org.join_request.new",
52182
+ ORG_INVITE_LINK_JOINED: "org.invite_link.joined",
52183
+ ORG_MEMBER_REMOVED: "org.member.removed",
52184
+ ORG_MEMBER_PROFILE_UPDATED: "org.member.profile.updated",
52185
+ AGENT_CONFIG_UPDATE: "agent_config.update",
52186
+ PRESENCE_UPDATE: "presence.update",
52187
+ WIKI_CHANGESET_CREATED: "wiki.changeset.created",
52188
+ WIKI_CHANGESET_UPDATED: "wiki.changeset.updated",
52189
+ WIKI_DELETED: "wiki.deleted",
52190
+ WIKI_RESTORED: "wiki.restored",
52191
+ COMMENT_CREATED: "comment.created",
52192
+ COMMENT_UPDATED: "comment.updated",
52193
+ COMMENT_DELETED: "comment.deleted",
52194
+ NOTIFICATION_ALERT: "notification.alert",
52195
+ INBOX_NEW: "inbox.new",
52196
+ INBOX_UPDATE: "inbox.update",
52197
+ INBOX_BULK_UPDATE: "inbox.bulk_update",
52198
+ READ_POSITION_UPDATED: "read_position.updated",
52199
+ THREAD_READ_POSITION_UPDATED: "thread_read_position.updated",
52200
+ DISPATCH_NEW: "dispatch.new",
52201
+ DISPATCH_RECEIVED: "dispatch.received",
52202
+ DISPATCH_RESOLVED: "dispatch.resolved",
52203
+ SCHEDULE_CREATED: "schedule.created",
52204
+ SCHEDULE_UPDATED: "schedule.updated",
52205
+ SCHEDULE_DELETED: "schedule.deleted",
52206
+ SCHEDULE_FIRED: "schedule.fired",
52207
+ BILLING_BALANCE_UPDATED: "billing.balance_updated",
52208
+ BILLING_LOW_BALANCE: "billing.low_balance",
52209
+ BILLING_MACHINE_STOPPED: "billing.machine_stopped",
52210
+ BILLING_INSUFFICIENT: "billing.insufficient",
52211
+ USER_UPDATED: "user.updated",
52212
+ MACHINE_HELLO: "machine.hello",
52213
+ MACHINE_AGENT_ATTACHED: "machine.agent.attached",
52214
+ MACHINE_AGENT_DETACHED: "machine.agent.detached",
52215
+ MACHINE_STOP: "machine.stop",
52216
+ MACHINE_WORKSPACE_SETUP_REQUESTED: "machine.workspace.setup.requested",
52217
+ MACHINE_FILESYSTEM_BROWSE: "machine.filesystem.browse",
52218
+ MACHINE_UPDATE: "machine.update",
52219
+ MACHINE_CONFIG_UPDATED: "machine.config.updated",
52220
+ MACHINE_AGENT_CONFIG_UPDATED: "machine.agent_config.updated",
52221
+ MACHINE_CLIP_SYNC: "machine.clip.sync",
52222
+ MACHINE_BROWSER_PROFILE_LIFECYCLE: "machine.browser_profile.lifecycle",
52223
+ MACHINE_BROWSER_PROFILE_VIEWER: "machine.browser_profile.viewer",
52224
+ AGENT_NEW_SESSION: "agent.new_session",
52225
+ CLIP_CREATED: "clip.created",
52226
+ CLIP_REMOVED: "clip.removed",
52227
+ CLIP_UPDATED: "clip.updated"
52228
+ };
52229
+
52230
+ // ../sdk/dist/project-task-client.js
52231
+ var ProjectTaskClient = class {
52232
+ async createTask(orgId, data) {
52233
+ return this.request("POST", ENDPOINTS.TASKS(orgId), data);
52234
+ }
52235
+ async getTasks(orgId, params) {
52236
+ return this.request("GET", ENDPOINTS.TASKS(orgId), void 0, params);
52237
+ }
52238
+ async getTaskSubtaskSummary(orgId, params) {
52239
+ return this.request("GET", ENDPOINTS.TASK_SUBTASK_SUMMARY(orgId), void 0, params);
52240
+ }
52241
+ async getTask(orgId, taskId) {
52242
+ return this.request("GET", ENDPOINTS.TASK(orgId, taskId));
52243
+ }
52244
+ async updateTask(orgId, taskId, data) {
52245
+ return this.request("PATCH", ENDPOINTS.TASK(orgId, taskId), data);
52246
+ }
52247
+ async deleteTask(orgId, taskId, opts) {
52248
+ return this.request("DELETE", ENDPOINTS.TASK(orgId, taskId), void 0, opts?.force ? { force: "true" } : void 0);
52249
+ }
52250
+ async archiveTask(orgId, taskId) {
52251
+ return this.request("POST", ENDPOINTS.TASK_ARCHIVE(orgId, taskId));
52252
+ }
52253
+ async restoreTask(orgId, taskId) {
52254
+ return this.request("POST", ENDPOINTS.TASK_RESTORE(orgId, taskId));
52255
+ }
52256
+ async watchTask(orgId, taskId) {
52257
+ return this.request("POST", ENDPOINTS.TASK_WATCH(orgId, taskId));
52258
+ }
52259
+ async unwatchTask(orgId, taskId) {
52260
+ return this.request("DELETE", ENDPOINTS.TASK_WATCH(orgId, taskId));
52261
+ }
52262
+ async getTaskWatchers(orgId, taskId) {
52263
+ const res = await this.request("GET", ENDPOINTS.TASK_WATCHERS(orgId, taskId));
52264
+ return res.data;
52265
+ }
52266
+ async subscribeTaskMember(orgId, taskId, userId) {
52267
+ return this.request("PUT", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52268
+ }
52269
+ async unsubscribeTaskMember(orgId, taskId, userId) {
52270
+ return this.request("DELETE", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52271
+ }
52272
+ async watchThread(threadRootId) {
52273
+ return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52274
+ }
52275
+ async unwatchThread(threadRootId) {
52276
+ return this.request("DELETE", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52277
+ }
52278
+ async getThreadWatchers(threadRootId) {
52279
+ const res = await this.request("GET", ENDPOINTS.MESSAGE_WATCHERS(threadRootId));
52280
+ return res.data;
52281
+ }
52282
+ async isWatchingThread(threadRootId) {
52283
+ const res = await this.request("GET", ENDPOINTS.MESSAGE_WATCHING(threadRootId));
52284
+ return res.watching;
52285
+ }
52286
+ async getSubtasks(orgId, taskId) {
52287
+ const res = await this.request("GET", ENDPOINTS.TASK_SUBTASKS(orgId, taskId));
52288
+ return res.data;
52289
+ }
52290
+ async createTaskRelation(orgId, taskId, data) {
52291
+ return this.request("POST", ENDPOINTS.TASK_RELATIONS(orgId, taskId), data);
52292
+ }
52293
+ async getTaskRelations(orgId, taskId) {
52294
+ const res = await this.request("GET", ENDPOINTS.TASK_RELATIONS(orgId, taskId));
52295
+ return res.data;
52296
+ }
52297
+ async listTaskRelationsByTarget(orgId, params) {
52298
+ const query = new URLSearchParams({
52299
+ target_type: params.target_type,
52300
+ target_id: params.target_id
52301
+ });
52302
+ const res = await this.request("GET", `${ENDPOINTS.TASK_RELATIONS_BY_TARGET(orgId)}?${query.toString()}`);
52303
+ return res.data;
52304
+ }
52305
+ async deleteTaskRelation(orgId, taskId, relationId) {
52306
+ return this.request("DELETE", ENDPOINTS.TASK_RELATION(orgId, taskId, relationId));
52307
+ }
52308
+ async getTaskComments(orgId, taskId, params) {
52309
+ return this.request("GET", ENDPOINTS.TASK_COMMENTS(orgId, taskId), void 0, params);
52310
+ }
52311
+ async getTaskComment(orgId, taskId, commentId) {
52312
+ return this.request("GET", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId));
52313
+ }
52314
+ async createTaskComment(orgId, taskId, data) {
52315
+ return this.request("POST", ENDPOINTS.TASK_COMMENTS(orgId, taskId), data);
52316
+ }
52317
+ async updateTaskComment(orgId, taskId, commentId, data) {
52318
+ return this.request("PATCH", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId), data);
52319
+ }
52320
+ async deleteTaskComment(orgId, taskId, commentId) {
52321
+ return this.request("DELETE", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId));
52322
+ }
52323
+ async getTaskActivities(orgId, taskId, params) {
52324
+ return this.request("GET", ENDPOINTS.TASK_ACTIVITIES(orgId, taskId), void 0, params);
52325
+ }
52326
+ async createProject(orgId, data) {
52327
+ return this.request("POST", ENDPOINTS.PROJECTS(orgId), data);
52328
+ }
52329
+ async getProjects(orgId) {
52330
+ const res = await this.request("GET", ENDPOINTS.PROJECTS(orgId));
52331
+ return res.data;
52332
+ }
52333
+ async getProjectTaskSummary(orgId) {
52334
+ return this.request("GET", ENDPOINTS.PROJECT_TASK_SUMMARY(orgId));
52335
+ }
52336
+ async getProject(orgId, projectId) {
52337
+ return this.request("GET", ENDPOINTS.PROJECT(orgId, projectId));
52338
+ }
52339
+ async updateProject(orgId, projectId, data) {
52340
+ return this.request("PATCH", ENDPOINTS.PROJECT(orgId, projectId), data);
52341
+ }
52342
+ async deleteProject(orgId, projectId) {
52343
+ return this.request("DELETE", ENDPOINTS.PROJECT(orgId, projectId));
52344
+ }
52345
+ /** Roster with display info; readable by anyone who can read the project. */
52346
+ async getProjectMembers(orgId, projectId) {
52347
+ const res = await this.request("GET", ENDPOINTS.PROJECT_MEMBERS(orgId, projectId));
52348
+ return res.data;
52349
+ }
52350
+ /**
52351
+ * User IDs who may read the project — the assignee-eligibility set. Every
52352
+ * tier answers the roster expansion (direct, team-reached, org
52353
+ * owners/admins); visibility only shapes admission, never reach.
52354
+ */
52355
+ async getProjectReaders(orgId, projectId) {
52356
+ const res = await this.request("GET", ENDPOINTS.PROJECT_READERS(orgId, projectId));
52357
+ return res.data;
52358
+ }
52359
+ /** The join library: every discoverable project (public + restricted, plus
52360
+ * private for org owners/admins) with the caller's admission state. */
52361
+ async getProjectLibrary(orgId) {
52362
+ const res = await this.request("GET", ENDPOINTS.PROJECT_LIBRARY(orgId));
52363
+ return res.data;
52364
+ }
52365
+ /** Public-tier self-admission: writes the caller's own member row.
52366
+ * Other tiers answer `404 PROJECT_NOT_FOUND`; a duplicate answers
52367
+ * `409 MEMBER_EXISTS`. */
52368
+ async joinProject(orgId, projectId) {
52369
+ return this.request("POST", ENDPOINTS.PROJECT_JOIN(orgId, projectId));
52370
+ }
52371
+ /** Restricted-tier admission petition. A pending duplicate answers
52372
+ * `409 REQUEST_EXISTS`; membership answers `409 MEMBER_EXISTS`. */
52373
+ async createProjectJoinRequest(orgId, projectId) {
52374
+ return this.request("POST", ENDPOINTS.PROJECT_JOIN_REQUESTS(orgId, projectId));
52375
+ }
52376
+ /** Pending petitions for one project — manager standing required. */
52377
+ async listProjectJoinRequests(orgId, projectId) {
52378
+ const res = await this.request("GET", ENDPOINTS.PROJECT_JOIN_REQUESTS(orgId, projectId));
52379
+ return res.data;
52380
+ }
52381
+ /** Withdraws the caller's own pending petition. */
52382
+ async cancelProjectJoinRequest(orgId, projectId) {
52383
+ return this.request("DELETE", ENDPOINTS.PROJECT_JOIN_REQUESTS(orgId, projectId));
52384
+ }
52385
+ /**
52386
+ * Adds one subject (user ID or team ID) to the roster. Manager-only,
52387
+ * create-only: an existing row answers `409 MEMBER_EXISTS` — change roles
52388
+ * through updateProjectMember instead.
52389
+ */
52390
+ async addProjectMember(orgId, projectId, req) {
52391
+ return this.request("POST", ENDPOINTS.PROJECT_MEMBERS(orgId, projectId), req);
52392
+ }
52393
+ /** Sets one roster entry's role. Demoting the last manager answers `400 LAST_MANAGER`. */
52394
+ async updateProjectMember(orgId, projectId, subject, req) {
52395
+ return this.request("PATCH", ENDPOINTS.PROJECT_MEMBER(orgId, projectId, subject), req);
52396
+ }
52397
+ /** Removes one roster entry. Removing the last manager answers `400 LAST_MANAGER`. */
52398
+ async removeProjectMember(orgId, projectId, subject) {
52399
+ return this.request("DELETE", ENDPOINTS.PROJECT_MEMBER(orgId, projectId, subject));
52400
+ }
52401
+ };
52402
+
52403
+ // ../sdk/dist/task-label-client.js
52404
+ var TaskLabelClient = class extends ProjectTaskClient {
52405
+ async getLabels(orgId) {
52406
+ const response = await this.request("GET", ENDPOINTS.LABELS(orgId));
52407
+ return response.data;
52408
+ }
52409
+ async createLabel(orgId, data) {
52410
+ return this.request("POST", ENDPOINTS.LABELS(orgId), data);
52411
+ }
52412
+ async updateLabel(orgId, labelId, data) {
52413
+ return this.request("PATCH", ENDPOINTS.LABEL(orgId, labelId), data);
52414
+ }
52415
+ async deleteLabel(orgId, labelId) {
52416
+ return this.request("DELETE", ENDPOINTS.LABEL(orgId, labelId));
52417
+ }
52418
+ async addTaskLabels(orgId, taskId, data) {
52419
+ return this.request("POST", ENDPOINTS.TASK_LABELS(orgId, taskId), data);
52420
+ }
52421
+ async removeTaskLabel(orgId, taskId, labelId) {
52422
+ return this.request("DELETE", ENDPOINTS.TASK_LABEL(orgId, taskId, labelId));
52423
+ }
51798
52424
  };
51799
52425
 
51800
52426
  // ../sdk/dist/client.js
51801
- var ParallClient = class _ParallClient {
52427
+ var ParallClient = class _ParallClient extends TaskLabelClient {
51802
52428
  baseUrl;
51803
52429
  wikiBaseUrl;
51804
52430
  token;
@@ -51858,6 +52484,7 @@ var ParallClient = class _ParallClient {
51858
52484
  return headers;
51859
52485
  }
51860
52486
  constructor(options = {}) {
52487
+ super();
51861
52488
  this.baseUrl = options.baseUrl ?? "";
51862
52489
  this.wikiBaseUrl = options.wikiBaseUrl ?? this.baseUrl;
51863
52490
  this.token = options.token ?? null;
@@ -52155,6 +52782,45 @@ var ParallClient = class _ParallClient {
52155
52782
  const res = await this.request("GET", ENDPOINTS.TEAMS(orgId));
52156
52783
  return res.data;
52157
52784
  }
52785
+ async getTeam(orgId, teamId) {
52786
+ return this.request("GET", ENDPOINTS.TEAM(orgId, teamId));
52787
+ }
52788
+ /** Creating, renaming and deleting a team are org-admin actions. */
52789
+ async createTeam(orgId, req) {
52790
+ return this.request("POST", ENDPOINTS.TEAMS(orgId), req);
52791
+ }
52792
+ /**
52793
+ * Renames a team. Renaming is an ordinary edit: ACL rows reference teams by
52794
+ * ID. Names are org-unique (case-insensitive); a duplicate answers 409
52795
+ * NAME_TAKEN.
52796
+ */
52797
+ async updateTeam(orgId, teamId, req) {
52798
+ return this.request("PATCH", ENDPOINTS.TEAM(orgId, teamId), req);
52799
+ }
52800
+ async deleteTeam(orgId, teamId) {
52801
+ return this.request("DELETE", ENDPOINTS.TEAM(orgId, teamId));
52802
+ }
52803
+ /** Roster with display info; members who left the org are already excluded. */
52804
+ async getTeamMembers(orgId, teamId) {
52805
+ const res = await this.request("GET", ENDPOINTS.TEAM_MEMBERS(orgId, teamId));
52806
+ return res.data;
52807
+ }
52808
+ /**
52809
+ * Adds an org member (human or agent) to a team. Org admins and that team's
52810
+ * managers may add ordinary members; adding straight to `manager` is an
52811
+ * org-admin action.
52812
+ */
52813
+ async addTeamMember(orgId, teamId, req) {
52814
+ return this.request("POST", ENDPOINTS.TEAM_MEMBERS(orgId, teamId), req);
52815
+ }
52816
+ /** Appointing or demoting a manager is org-admin only. */
52817
+ async updateTeamMember(orgId, teamId, userId, req) {
52818
+ return this.request("PATCH", ENDPOINTS.TEAM_MEMBER(orgId, teamId, userId), req);
52819
+ }
52820
+ /** A team manager may remove ordinary members; removing a peer manager is org-admin only. */
52821
+ async removeTeamMember(orgId, teamId, userId) {
52822
+ return this.request("DELETE", ENDPOINTS.TEAM_MEMBER(orgId, teamId, userId));
52823
+ }
52158
52824
  async getOnlineMembers(orgId) {
52159
52825
  const res = await this.request("GET", ENDPOINTS.ORG_MEMBERS_ONLINE(orgId));
52160
52826
  return res.user_ids ?? [];
@@ -52940,134 +53606,23 @@ var ParallClient = class _ParallClient {
52940
53606
  extra["If-None-Match"] = currentVersion;
52941
53607
  }
52942
53608
  const headers = this.buildHeaders(ENDPOINTS.PLATFORM_CONFIG, extra);
52943
- let res;
52944
- try {
52945
- res = await fetch(url, {
52946
- method: "GET",
52947
- headers,
52948
- signal: AbortSignal.timeout(15e3)
52949
- });
52950
- } catch (err) {
52951
- throw _ParallClient.normalizeFetchError(err);
52952
- }
52953
- if (res.status === 304)
52954
- return null;
52955
- if (!res.ok) {
52956
- const rawErrorBody = await res.json().catch(() => ({}));
52957
- throw buildApiError(res, rawErrorBody);
52958
- }
52959
- return res.json();
52960
- }
52961
- // ---- Tasks (org-scoped) ----
52962
- async createTask(orgId, data) {
52963
- return this.request("POST", ENDPOINTS.TASKS(orgId), data);
52964
- }
52965
- async getTasks(orgId, params) {
52966
- return this.request("GET", ENDPOINTS.TASKS(orgId), void 0, params);
52967
- }
52968
- async getTask(orgId, taskId) {
52969
- return this.request("GET", ENDPOINTS.TASK(orgId, taskId));
52970
- }
52971
- async updateTask(orgId, taskId, data) {
52972
- return this.request("PATCH", ENDPOINTS.TASK(orgId, taskId), data);
52973
- }
52974
- async deleteTask(orgId, taskId, opts) {
52975
- return this.request("DELETE", ENDPOINTS.TASK(orgId, taskId), void 0, opts?.force ? { force: "true" } : void 0);
52976
- }
52977
- async archiveTask(orgId, taskId) {
52978
- return this.request("POST", ENDPOINTS.TASK_ARCHIVE(orgId, taskId));
52979
- }
52980
- async restoreTask(orgId, taskId) {
52981
- return this.request("POST", ENDPOINTS.TASK_RESTORE(orgId, taskId));
52982
- }
52983
- async watchTask(orgId, taskId) {
52984
- return this.request("POST", ENDPOINTS.TASK_WATCH(orgId, taskId));
52985
- }
52986
- async unwatchTask(orgId, taskId) {
52987
- return this.request("DELETE", ENDPOINTS.TASK_WATCH(orgId, taskId));
52988
- }
52989
- async getTaskWatchers(orgId, taskId) {
52990
- const res = await this.request("GET", ENDPOINTS.TASK_WATCHERS(orgId, taskId));
52991
- return res.data;
52992
- }
52993
- async subscribeTaskMember(orgId, taskId, userId) {
52994
- return this.request("PUT", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52995
- }
52996
- async unsubscribeTaskMember(orgId, taskId, userId) {
52997
- return this.request("DELETE", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52998
- }
52999
- async watchThread(threadRootId) {
53000
- return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId));
53001
- }
53002
- async unwatchThread(threadRootId) {
53003
- return this.request("DELETE", ENDPOINTS.MESSAGE_WATCH(threadRootId));
53004
- }
53005
- async getThreadWatchers(threadRootId) {
53006
- const res = await this.request("GET", ENDPOINTS.MESSAGE_WATCHERS(threadRootId));
53007
- return res.data;
53008
- }
53009
- async isWatchingThread(threadRootId) {
53010
- const res = await this.request("GET", ENDPOINTS.MESSAGE_WATCHING(threadRootId));
53011
- return res.watching;
53012
- }
53013
- async getSubtasks(orgId, taskId) {
53014
- const res = await this.request("GET", ENDPOINTS.TASK_SUBTASKS(orgId, taskId));
53015
- return res.data;
53016
- }
53017
- async createTaskRelation(orgId, taskId, data) {
53018
- return this.request("POST", ENDPOINTS.TASK_RELATIONS(orgId, taskId), data);
53019
- }
53020
- async getTaskRelations(orgId, taskId) {
53021
- const res = await this.request("GET", ENDPOINTS.TASK_RELATIONS(orgId, taskId));
53022
- return res.data;
53023
- }
53024
- async listTaskRelationsByTarget(orgId, params) {
53025
- const query = new URLSearchParams({
53026
- target_type: params.target_type,
53027
- target_id: params.target_id
53028
- });
53029
- const res = await this.request("GET", `${ENDPOINTS.TASK_RELATIONS_BY_TARGET(orgId)}?${query.toString()}`);
53030
- return res.data;
53031
- }
53032
- async deleteTaskRelation(orgId, taskId, relationId) {
53033
- return this.request("DELETE", ENDPOINTS.TASK_RELATION(orgId, taskId, relationId));
53034
- }
53035
- // ---- Task Comments ----
53036
- async getTaskComments(orgId, taskId, params) {
53037
- return this.request("GET", ENDPOINTS.TASK_COMMENTS(orgId, taskId), void 0, params);
53038
- }
53039
- async getTaskComment(orgId, taskId, commentId) {
53040
- return this.request("GET", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId));
53041
- }
53042
- async createTaskComment(orgId, taskId, data) {
53043
- return this.request("POST", ENDPOINTS.TASK_COMMENTS(orgId, taskId), data);
53044
- }
53045
- async updateTaskComment(orgId, taskId, commentId, data) {
53046
- return this.request("PATCH", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId), data);
53047
- }
53048
- async deleteTaskComment(orgId, taskId, commentId) {
53049
- return this.request("DELETE", ENDPOINTS.TASK_COMMENT(orgId, taskId, commentId));
53050
- }
53051
- // ---- Task Activities ----
53052
- async getTaskActivities(orgId, taskId, params) {
53053
- return this.request("GET", ENDPOINTS.TASK_ACTIVITIES(orgId, taskId), void 0, params);
53054
- }
53055
- // ---- Projects (org-scoped) ----
53056
- async createProject(orgId, data) {
53057
- return this.request("POST", ENDPOINTS.PROJECTS(orgId), data);
53058
- }
53059
- async getProjects(orgId) {
53060
- const res = await this.request("GET", ENDPOINTS.PROJECTS(orgId));
53061
- return res.data;
53062
- }
53063
- async getProject(orgId, projectId) {
53064
- return this.request("GET", ENDPOINTS.PROJECT(orgId, projectId));
53065
- }
53066
- async updateProject(orgId, projectId, data) {
53067
- return this.request("PATCH", ENDPOINTS.PROJECT(orgId, projectId), data);
53068
- }
53069
- async deleteProject(orgId, projectId) {
53070
- return this.request("DELETE", ENDPOINTS.PROJECT(orgId, projectId));
53609
+ let res;
53610
+ try {
53611
+ res = await fetch(url, {
53612
+ method: "GET",
53613
+ headers,
53614
+ signal: AbortSignal.timeout(15e3)
53615
+ });
53616
+ } catch (err) {
53617
+ throw _ParallClient.normalizeFetchError(err);
53618
+ }
53619
+ if (res.status === 304)
53620
+ return null;
53621
+ if (!res.ok) {
53622
+ const rawErrorBody = await res.json().catch(() => ({}));
53623
+ throw buildApiError(res, rawErrorBody);
53624
+ }
53625
+ return res.json();
53071
53626
  }
53072
53627
  // ---- Schedules (org-scoped) ----
53073
53628
  async createSchedule(orgId, input) {
@@ -53206,12 +53761,26 @@ var ParallClient = class _ParallClient {
53206
53761
  }
53207
53762
  /**
53208
53763
  * WeChat tier-B read verb (agent-only; internal research preview): the
53209
- * account's address book — friend wxids, saved group room ids, followed
53210
- * official accounts. Same live gate as the send verb.
53764
+ * account's address book — friends/chatrooms enriched with display names,
53765
+ * followed official accounts. Same live gate as the send verb.
53211
53766
  */
53212
53767
  async listWechatContacts(orgId) {
53213
53768
  return this.request("GET", ENDPOINTS.WECHAT_CONTACTS(orgId));
53214
53769
  }
53770
+ /**
53771
+ * WeChat tier-B read verb (agent-only): the connected account's identity
53772
+ * (wxid / alias / nickName / app id).
53773
+ */
53774
+ async wechatProfile(orgId) {
53775
+ return this.request("GET", ENDPOINTS.WECHAT_PROFILE(orgId));
53776
+ }
53777
+ /**
53778
+ * WeChat tier-B read verb (agent-only): live online probe + identity +
53779
+ * the platform's offline record.
53780
+ */
53781
+ async wechatStatus(orgId) {
53782
+ return this.request("GET", ENDPOINTS.WECHAT_STATUS(orgId));
53783
+ }
53215
53784
  async listChannelConversations(orgId, connectionId) {
53216
53785
  return this.request("GET", ENDPOINTS.CHANNEL_CONNECTION_CONVERSATIONS(orgId, connectionId));
53217
53786
  }
@@ -53547,6 +54116,7 @@ var ParallClient = class _ParallClient {
53547
54116
  return this.request("PATCH", ENDPOINTS.NOTIFICATION_PREFERENCES, { prefs });
53548
54117
  }
53549
54118
  // ---- Feature Flags (org-scoped, server-evaluated) ----
54119
+ /** Omit orgId to resolve deployment capabilities before joining an org. */
53550
54120
  async getFeatureFlags(orgId) {
53551
54121
  return this.request("GET", ENDPOINTS.FEATURE_FLAGS(orgId));
53552
54122
  }
@@ -53563,6 +54133,44 @@ var ParallClient = class _ParallClient {
53563
54133
  timeoutMs: 185e3
53564
54134
  });
53565
54135
  }
54136
+ /** Queue a template deployment and poll its durable deployment row. Each
54137
+ * request is short-lived; closing the client does not cancel server work. */
54138
+ async deployTemplateAsync(orgId, request3, idempotencyKey) {
54139
+ const queue = () => this.request("POST", ENDPOINTS.TEMPLATE_DEPLOYMENTS(orgId), {
54140
+ ...request3,
54141
+ async: true,
54142
+ idempotency_key: idempotencyKey
54143
+ });
54144
+ let result;
54145
+ for (let attempt = 0; attempt < 2 && result === void 0; attempt += 1) {
54146
+ try {
54147
+ result = await queue();
54148
+ } catch (error) {
54149
+ if (!(error instanceof ApiError) || error.status !== 0 && error.status < 500)
54150
+ throw error;
54151
+ }
54152
+ }
54153
+ if (result === void 0) {
54154
+ throw new ApiError(0, "Template deployment request outcome is unknown", "NETWORK_ERROR");
54155
+ }
54156
+ const deadline = Date.now() + 30 * 60 * 1e3;
54157
+ while (result.status === "queued" || result.status === "deploying") {
54158
+ if (Date.now() >= deadline) {
54159
+ throw new ApiError(0, "Template deployment is still running", "REQUEST_TIMEOUT");
54160
+ }
54161
+ await new Promise((resolve3) => setTimeout(resolve3, 2e3));
54162
+ try {
54163
+ result = await this.request("GET", ENDPOINTS.TEMPLATE_DEPLOYMENT(orgId, result.deployment_id));
54164
+ } catch (error) {
54165
+ if (!(error instanceof ApiError) || error.status !== 0 && error.status < 500)
54166
+ throw error;
54167
+ }
54168
+ }
54169
+ if (result.status !== "deployed") {
54170
+ throw new ApiError(500, result.error?.message ?? "Template deployment failed", result.error?.code);
54171
+ }
54172
+ return result;
54173
+ }
53566
54174
  async getTemplateDeployment(orgId, deploymentId) {
53567
54175
  return this.request("GET", ENDPOINTS.TEMPLATE_DEPLOYMENT(orgId, deploymentId));
53568
54176
  }
@@ -53777,6 +54385,11 @@ var ParallClient = class _ParallClient {
53777
54385
  async uninstallRegistryClip(orgId, clipId) {
53778
54386
  await this.request("DELETE", ENDPOINTS.ORG_CLIP_UNINSTALL(orgId, clipId));
53779
54387
  }
54388
+ /** Best-effort provider revoke followed by atomic local removal of an
54389
+ * installed Official MCP Clip and all org-owned connection state. */
54390
+ async removeOfficialMCPClip(orgId, clipId) {
54391
+ return this.request("DELETE", ENDPOINTS.ORG_CLIP_MCP_REMOVE(orgId, clipId));
54392
+ }
53780
54393
  /** List the org's installed registry clips (full entries). */
53781
54394
  async listInstalledRegistryClips(orgId) {
53782
54395
  const resp = await this.request("GET", ENDPOINTS.ORG_CLIPS_INSTALLED(orgId));
@@ -53808,15 +54421,18 @@ var ParallClient = class _ParallClient {
53808
54421
  /**
53809
54422
  * Read a clip's per-org agent exec access. Org-member readable (agents
53810
54423
  * included, so a denied agent can learn why exec answered
53811
- * `CLIP_AGENT_NOT_ALLOWED`).
54424
+ * `CLIP_AGENT_NOT_ALLOWED` / `CLIP_AGENT_CONNECTION_NOT_ALLOWED`).
53812
54425
  */
53813
54426
  async getClipAgentExecAccess(orgId, clipId) {
53814
54427
  return this.request("GET", ENDPOINTS.ORG_CLIP_EXEC_ACCESS(orgId, clipId));
53815
54428
  }
53816
54429
  /**
53817
54430
  * Replace a clip's per-org agent exec access. Human-only (agent principals
53818
- * get 403); under `all_agents` the `agent_ids` must be empty. Every granted
53819
- * id must be an active agent of this org (else `400 INVALID_INPUT`).
54431
+ * get 403); under `all_agents` both lists must be empty; pass either
54432
+ * `agent_ids` (legacy flat form every agent gets `connection_scope: 'all'`)
54433
+ * or `grants` (connection-scoped), never both. Every granted id must be an
54434
+ * active agent of this org, and every `connection_ids` entry a connection of
54435
+ * THIS clip in this org (else `400 INVALID_INPUT`).
53820
54436
  */
53821
54437
  async putClipAgentExecAccess(orgId, clipId, access) {
53822
54438
  return this.request("PUT", ENDPOINTS.ORG_CLIP_EXEC_ACCESS(orgId, clipId), access);
@@ -53902,6 +54518,41 @@ var ParallClient = class _ParallClient {
53902
54518
  headers: expectedVersion ? { "If-Match": `"proxy-${expectedVersion}"` } : void 0
53903
54519
  });
53904
54520
  }
54521
+ /**
54522
+ * Read a hosted Cloud Profile's one-shot cookie-seed status (manager-only:
54523
+ * hosted human maintainer or org admin). Sanitized — cookie VALUES never come
54524
+ * back, only `cookie_count` and the distinct target `domains`. `can_mutate` /
54525
+ * `lease_status` are the authoritative idle gate. Typed errors: `EDGE_NOT_HOSTED`
54526
+ * (BYOC device), `NOT_FOUND` (unknown profile).
54527
+ */
54528
+ async getEdgeProfileCookieSeed(orgId, edgeId, profileName) {
54529
+ return this.request("GET", ENDPOINTS.ORG_EDGE_PROFILE_COOKIES(orgId, edgeId, profileName));
54530
+ }
54531
+ /**
54532
+ * Set/replace the profile's one-shot cookie seed (the full normalized cookie
54533
+ * array every time) — IDLE ONLY: while the profile's hosted browser is running
54534
+ * the server answers 409 `EDGE_PROFILE_IN_USE`; close the viewer, wait for idle
54535
+ * scale-to-zero, and retry. The next cold start injects the cookies into the
54536
+ * profile partition and consumes the seed. Other typed errors:
54537
+ * `EDGE_COOKIE_SEED_STALE` (409 — expectedVersion lost a tab race, sent as the
54538
+ * `cookieseed-<version>` If-Match), `EDGE_DELETING` (409), and
54539
+ * `SECRETBOX_UNCONFIGURED` (503 — server cannot store cookies safely).
54540
+ */
54541
+ async setEdgeProfileCookieSeed(orgId, edgeId, profileName, req, expectedVersion) {
54542
+ return this.request("PUT", ENDPOINTS.ORG_EDGE_PROFILE_COOKIES(orgId, edgeId, profileName), req, void 0, false, {
54543
+ headers: expectedVersion ? { "If-Match": `"cookieseed-${expectedVersion}"` } : void 0
54544
+ });
54545
+ }
54546
+ /**
54547
+ * Clear the pending cookie seed (does NOT sign the profile out — cookies
54548
+ * already injected into the partition stay). Idle-only like set — 409
54549
+ * `EDGE_PROFILE_IN_USE` while the browser is live.
54550
+ */
54551
+ async clearEdgeProfileCookieSeed(orgId, edgeId, profileName, expectedVersion) {
54552
+ return this.request("DELETE", ENDPOINTS.ORG_EDGE_PROFILE_COOKIES(orgId, edgeId, profileName), void 0, void 0, false, {
54553
+ headers: expectedVersion ? { "If-Match": `"cookieseed-${expectedVersion}"` } : void 0
54554
+ });
54555
+ }
53905
54556
  /**
53906
54557
  * Execute a registry clip command on an Edge device.
53907
54558
  *
@@ -53963,12 +54614,14 @@ var ParallClient = class _ParallClient {
53963
54614
  async deleteClipConnection(orgId, connId) {
53964
54615
  return this.request("DELETE", ENDPOINTS.CLIP_CONNECTION(orgId, connId));
53965
54616
  }
53966
- // ---- MCP clip server config (cap:clip-mcp; publisher-org only) ----
54617
+ // ---- MCP clip server config (same-org or reviewed Official OAuth) ----
53967
54618
  /**
53968
- * Read the redacted MCP config. 404 NOT_FOUND when the clip has none yet;
53969
- * 403 MCP_CROSS_ORG_DISABLED for a cross-org installed clip (the whole
53970
- * mcp-config family is publisher-org property, reads included). `version`
53971
- * is the CAS token the mutations echo via If-Match.
54619
+ * Read the redacted MCP config. 404 NOT_FOUND when the clip has none yet
54620
+ * and also when a cross-org clip is not public + approved + installed, which
54621
+ * reads as nonexistent rather than refused (same existence-hiding as exec).
54622
+ * A cross-org clip that IS installed and approved reads fine regardless of
54623
+ * auth shape; what may then be configured is decided per credential owner.
54624
+ * `version` is the CAS token the mutations echo via If-Match.
53972
54625
  */
53973
54626
  async getClipMCPConfig(orgId, clipId) {
53974
54627
  return this.request("GET", ENDPOINTS.ORG_CLIP_MCP_CONFIG(orgId, clipId));
@@ -54005,13 +54658,26 @@ var ParallClient = class _ParallClient {
54005
54658
  * List the org's MCP connections for a clip, default first — one row per
54006
54659
  * connection (credential slot), WITHOUT the tools snapshot (`tool_count`
54007
54660
  * summarizes it; the per-config GET carries the full snapshot). Same
54008
- * family-wide fence as the singular GET: publisher-org members only
54009
- * cross-org installs get `403 MCP_CROSS_ORG_DISABLED`, and with
54661
+ * family-wide fence as the singular GET: same-org clips, or a cross-org clip
54662
+ * that is public + approved + installed; anything else reads as
54663
+ * `404 NOT_FOUND`. An installed cross-org clip with no connection yet lists
54664
+ * as an empty array — including one whose approved auth mode cannot be
54665
+ * configured at all (auth=none), which the write path is what refuses. With
54010
54666
  * `cap:clip-mcp` off the route is not registered at all.
54011
54667
  */
54012
54668
  async listClipMCPConnections(orgId, clipId) {
54013
54669
  return this.request("GET", ENDPOINTS.ORG_CLIP_MCP_CONFIGS(orgId, clipId));
54014
54670
  }
54671
+ /** Start a new Official OAuth MCP connection with the platform-owned app.
54672
+ * Omitting oauth_client is load-bearing: the server resolves the exact
54673
+ * reviewed-version binding and never falls back to DCR/CIMD cross-org. */
54674
+ async createClipMCPOAuthConnection(orgId, clipId, serverUrl, alias) {
54675
+ return this.request("POST", ENDPOINTS.ORG_CLIP_MCP_CONFIGS(orgId, clipId), {
54676
+ server_url: serverUrl,
54677
+ auth_type: "oauth",
54678
+ ...alias ? { alias } : {}
54679
+ });
54680
+ }
54015
54681
  /**
54016
54682
  * Re-run tools/list and replace the cached snapshot (org-admin only).
54017
54683
  * Deliberately does NOT advance the CAS version, so an in-flight edit in
@@ -54433,211 +55099,23 @@ var ParallWs = class {
54433
55099
  }
54434
55100
  };
54435
55101
 
54436
- // ../agent-core/dist/event-format.js
54437
- function sanitizeMeta(value) {
54438
- return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
54439
- }
54440
- function buildEventBody(event) {
54441
- const lines = [];
54442
- if (event.type === "message") {
54443
- lines.push(`[Event: message.new]`);
54444
- const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
54445
- lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
54446
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
54447
- lines.push(`[Message ID: prll://${event.messageId}]`);
54448
- if (event.threadRootId) {
54449
- const threadMeta = [
54450
- `prll://${event.threadRootId}`,
54451
- event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
54452
- event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
54453
- event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
54454
- ].filter(Boolean).join(" | ");
54455
- lines.push(`[Thread: ${threadMeta}]`);
54456
- }
54457
- if (event.unreadCount != null && event.unreadCount > 1) {
54458
- const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
54459
- const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
54460
- let line = `[Unread: ${countStr} messages${sinceStr}]`;
54461
- if (event.unreadCount > 50)
54462
- line += ` \u2014 fetch recent context with --limit, not all`;
54463
- lines.push(line);
54464
- }
54465
- if (event.noReply)
54466
- lines.push(`[Hint: no_reply]`);
54467
- if (event.attachments?.length) {
54468
- for (const att of event.attachments) {
54469
- const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
54470
- lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
54471
- }
54472
- }
54473
- lines.push("", event.body);
54474
- } else if (event.type === "task_comment") {
54475
- lines.push(`[Event: task.comment.created]`);
54476
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
54477
- lines.push(`[Task: ${taskLabel}]`);
54478
- if (event.deliveryReason)
54479
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
54480
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
54481
- lines.push(`[Comment ID: prll://${event.messageId}]`);
54482
- lines.push("", event.body);
54483
- } else if (event.type === "wiki_comment") {
54484
- lines.push(`[Event: wiki.comment.created]`);
54485
- const target = event.replyTargetUri ?? `prll://${event.targetId}`;
54486
- if (event.targetType === "changeset") {
54487
- lines.push(`[Wiki Changeset: ${target}]`);
54488
- } else {
54489
- lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
54490
- }
54491
- if (event.deliveryReason)
54492
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
54493
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
54494
- lines.push(`[Comment ID: prll://${event.messageId}]`);
54495
- lines.push("", event.body);
54496
- } else if (event.type === "approval") {
54497
- lines.push(`[Event: approval.decided]`);
54498
- lines.push(`[Approval: prll://${event.messageId}]`);
54499
- lines.push(`[Chat: prll://${event.targetId}]`);
54500
- lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
54501
- lines.push("", event.body);
54502
- } else if (event.type === "schedule") {
54503
- lines.push(`[Event: schedule.fired]`);
54504
- lines.push(`[Schedule: prll://${event.targetId}]`);
54505
- lines.push(`[Run: prll://${event.messageId}]`);
54506
- if (event.scheduledFireAt)
54507
- lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
54508
- if (event.attachedUri)
54509
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
54510
- lines.push("", event.body);
54511
- } else if (event.type === "channel_message") {
54512
- lines.push(`[Event: channel.message]`);
54513
- const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
54514
- const convLabel = event.channelExternalConversationId ? `${sanitizeMeta(event.channelExternalConversationId)} (${sanitizeMeta(event.channelConversationType ?? "conversation")})` : sanitizeMeta(event.channelConversationType ?? "conversation");
54515
- lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
54516
- lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
54517
- if (event.channelExternalMessageId) {
54518
- lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
54519
- }
54520
- 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.]`);
54521
- lines.push("", event.body);
54522
- } else if (event.type === "external_trigger") {
54523
- lines.push(`[Event: external.trigger]`);
54524
- lines.push(`[Trigger: prll://${event.targetId}]`);
54525
- lines.push(`[Run: prll://${event.messageId}]`);
54526
- if (event.externalConnectionId) {
54527
- const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
54528
- lines.push(`[Connection: ${label}]`);
54529
- }
54530
- if (event.externalIngressEventId)
54531
- lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
54532
- if (event.attachedUri)
54533
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
54534
- if (event.externalConnectionSourceType) {
54535
- lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
54536
- }
54537
- if (event.externalIngressEventType) {
54538
- lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
54539
- }
54540
- lines.push("", event.body);
54541
- } else {
54542
- lines.push(`[Event: task.assigned]`);
54543
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
54544
- lines.push(`[Task: ${taskLabel}]`);
54545
- lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
54546
- lines.push("", event.body);
54547
- }
54548
- return lines.join("\n") + buildSendMessageHint(event);
54549
- }
54550
- function buildEventBodyForForkResult(event) {
54551
- return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
54552
- }
54553
- function buildSendMessageHint(event) {
54554
- if (event.noReply)
54555
- return "";
54556
- if (event.type === "wiki_comment" && event.replyTargetUri) {
54557
- const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
54558
- return `
54559
- <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>`;
54560
- }
54561
- if (event.targetId.startsWith("cht_")) {
54562
- if (event.threadRootId) {
54563
- return `
54564
- <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>`;
54565
- }
54566
- return `
54567
- <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>`;
54568
- }
54569
- if (event.targetId.startsWith("tsk_")) {
54570
- return `
54571
- <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>`;
54572
- }
54573
- if (event.targetId.startsWith("sch_")) {
54574
- return `
54575
- <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
54576
- }
54577
- if (event.type === "channel_message") {
54578
- if (event.channelCliCapable) {
54579
- if (event.channelProvider === "slack") {
54580
- const channelArg = event.channelExternalConversationId ? ` --channel "${event.channelExternalConversationId}"` : " --channel <conversation id from this event>";
54581
- const replyTo = event.channelExternalMessageId ? ` --reply-to "${event.channelExternalMessageId}"` : "";
54582
- return `
54583
- <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>`;
54584
- }
54585
- if (event.channelProvider === "wechat") {
54586
- const toArg = event.channelExternalConversationId ? ` --to "${event.channelExternalConversationId}"` : " --to <wxid from this event>";
54587
- const atArg = event.channelConversationType === "group" ? event.senderId && event.senderId !== "external" ? ` --at "${event.senderId}"` : " --at <wxid of the person you are answering>" : "";
54588
- return `
54589
- <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>`;
54590
- }
54591
- if (!event.channelProvider) {
54592
- return `
54593
- <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>`;
54594
- }
54595
- const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
54596
- const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
54597
- return `
54598
- <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>`;
54599
- }
54600
- const platform = event.channelProvider ?? "the external platform";
54601
- return `
54602
- <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>`;
54603
- }
54604
- if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
54605
- return `
54606
- <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>`;
54607
- }
54608
- return "";
54609
- }
54610
- function buildForkScopePrefix(event) {
54611
- const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
54612
- 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.
54613
-
54614
- 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.
54615
-
54616
- End with a brief "Fork summary" of actions taken and decisions made.]
55102
+ // ../agent-core/dist/lane-ledger.js
55103
+ import * as fs2 from "node:fs";
54617
55104
 
54618
- `;
55105
+ // ../agent-core/dist/lane-key.js
55106
+ import * as path2 from "node:path";
55107
+ function laneKeyForTarget(targetUri, threadRootId) {
55108
+ return Buffer.from(`${targetUri}
55109
+ ${threadRootId ?? ""}`, "utf8").toString("base64url");
54619
55110
  }
54620
- function buildForkResultPrefix(results) {
54621
- if (!results.length)
54622
- return "";
54623
- const blocks = results.map((result) => {
54624
- const lines = [];
54625
- for (const body of result.eventBodies) {
54626
- lines.push(body);
54627
- }
54628
- lines.push(`[This event was handled by a parallel fork session. Do NOT re-handle, re-reply, or duplicate work for it.]`);
54629
- 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."}]`);
54630
- if (result.actions.length)
54631
- lines.push(`[Fork actions: ${result.actions.join("; ")}]`);
54632
- if (result.historyPath)
54633
- lines.push(`[Fork history: ${result.historyPath}]`);
54634
- return lines.join("\n");
54635
- });
54636
- return blocks.join("\n\n") + "\n\n---\n\n";
55111
+ function dispatchLaneContextDir(stateDir) {
55112
+ return path2.join(stateDir, "dispatch-lane-context");
55113
+ }
55114
+ function laneContextFilePath(contextDir, targetUri, threadRootId) {
55115
+ return path2.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
54637
55116
  }
54638
55117
 
54639
55118
  // ../agent-core/dist/lane-ledger.js
54640
- import * as fs from "node:fs";
54641
55119
  var LedgerUnsupportedError = class extends Error {
54642
55120
  };
54643
55121
  function bindLaneSession(lane, agentSessionId) {
@@ -55061,7 +55539,7 @@ var LaneLedger = class {
55061
55539
  const contextPath = this.laneContextPath(lane);
55062
55540
  for (const p of [contextPath, contextPath.replace(/\.json$/, ".reply-state.json")]) {
55063
55541
  try {
55064
- fs.rmSync(p, { force: true });
55542
+ fs2.rmSync(p, { force: true });
55065
55543
  } catch {
55066
55544
  }
55067
55545
  }
@@ -55411,531 +55889,38 @@ async function consumeMessageWorkItem(host, item) {
55411
55889
  try {
55412
55890
  const dispatched = await host.handleInboundEvent(decision.event);
55413
55891
  if (dispatched) {
55414
- if (!laneResolved)
55415
- ackItem();
55416
- } else {
55417
- host.dispatchedMessages.delete(item.source_id);
55418
- }
55419
- } catch (err) {
55420
- host.dispatchedMessages.delete(item.source_id);
55421
- throw err;
55422
- }
55423
- }
55424
-
55425
- // ../agent-core/dist/session-state.js
55426
- function normalizeSessionKey(sessionKey) {
55427
- return sessionKey.toLowerCase();
55428
- }
55429
- var sessionChatIdMap = /* @__PURE__ */ new Map();
55430
- var sessionMessageIdMap = /* @__PURE__ */ new Map();
55431
- var dispatchMessageIdMap = /* @__PURE__ */ new Map();
55432
- var dispatchGroupKeyMap = /* @__PURE__ */ new Map();
55433
- var dispatchNoReplyMap = /* @__PURE__ */ new Map();
55434
- function setSessionChatId(sessionKey, chatId) {
55435
- sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
55436
- }
55437
- function getSessionChatId(sessionKey) {
55438
- return sessionChatIdMap.get(normalizeSessionKey(sessionKey));
55439
- }
55440
- function setSessionMessageId(sessionKey, messageId) {
55441
- sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
55442
- }
55443
- function clearSessionMessageId(sessionKey) {
55444
- sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
55445
- }
55446
- function setDispatchMessageId(sessionKey, messageId) {
55447
- dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
55448
- }
55449
- function getDispatchMessageId(sessionKey) {
55450
- return dispatchMessageIdMap.get(normalizeSessionKey(sessionKey));
55451
- }
55452
- function clearDispatchMessageId(sessionKey) {
55453
- dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
55454
- }
55455
- function setDispatchGroupKey(sessionKey, groupKey) {
55456
- dispatchGroupKeyMap.set(normalizeSessionKey(sessionKey), groupKey);
55457
- }
55458
- function getDispatchGroupKey(sessionKey) {
55459
- return dispatchGroupKeyMap.get(normalizeSessionKey(sessionKey));
55460
- }
55461
- function clearDispatchGroupKey(sessionKey) {
55462
- dispatchGroupKeyMap.delete(normalizeSessionKey(sessionKey));
55463
- }
55464
- function setDispatchNoReply(sessionKey, noReply) {
55465
- dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
55466
- }
55467
- function clearDispatchNoReply(sessionKey) {
55468
- dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
55469
- }
55470
- var dispatchMetricsMap = /* @__PURE__ */ new Map();
55471
- function resetDispatchMetrics(sessionKey) {
55472
- dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
55473
- deliver_text_chunks: 0,
55474
- deliver_text_chars: 0,
55475
- message_send_attempts: 0,
55476
- message_send_successes: 0,
55477
- no_reply_called: false,
55478
- tool_call_count: 0,
55479
- started_at: Date.now()
55480
- });
55481
- }
55482
- function getDispatchMetrics(sessionKey) {
55483
- return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55484
- }
55485
- function clearDispatchMetrics(sessionKey) {
55486
- dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
55487
- }
55488
- function recordDeliverText(sessionKey, charCount) {
55489
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55490
- if (!m)
55491
- return;
55492
- m.deliver_text_chunks++;
55493
- m.deliver_text_chars += charCount;
55494
- }
55495
- function recordMessageSend(sessionKey, success) {
55496
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55497
- if (!m)
55498
- return;
55499
- m.message_send_attempts++;
55500
- if (success)
55501
- m.message_send_successes++;
55502
- }
55503
- function recordNoReply(sessionKey) {
55504
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55505
- if (!m)
55506
- return;
55507
- m.no_reply_called = true;
55508
- }
55509
- function recordToolCall(sessionKey) {
55510
- const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
55511
- if (!m)
55512
- return;
55513
- m.tool_call_count++;
55514
- }
55515
-
55516
- // ../agent-core/dist/routing.js
55517
- var MAX_CONCURRENT_FORKS = 20;
55518
- var defaultRoutingStrategy = (event, state) => {
55519
- if (state.mainCurrentTargetId === event.targetId) {
55520
- return { action: "buffer-main" };
55521
- }
55522
- const existingForkKey = state.activeForks.get(event.targetId);
55523
- if (existingForkKey)
55524
- return { action: "buffer-fork", forkKey: existingForkKey };
55525
- if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
55526
- return { action: "buffer-main" };
55527
- }
55528
- return { action: "new-fork" };
55529
- };
55530
- function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
55531
- const existingForkKey = state.activeForks.get(event.targetId);
55532
- if (existingForkKey)
55533
- return { action: "buffer-fork", forkKey: existingForkKey };
55534
- if (!state.mainDispatching)
55535
- return { action: "main" };
55536
- return strategy(event, state);
55537
- }
55538
-
55539
- // ../agent-core/dist/prompt-fragments.js
55540
- function identityFromMe(me) {
55541
- return {
55542
- userId: me.id,
55543
- displayName: me.display_name,
55544
- title: me.public_profile?.title || void 0,
55545
- publicDescription: me.public_profile?.description || void 0,
55546
- // `||` on purpose: an empty-string instructions must also fall back to
55547
- // the deprecated description alias (empty means "unset" on this wire).
55548
- instructions: me.agent_profile?.instructions || me.agent_profile?.description || void 0
55549
- };
55550
- }
55551
- var PRLL_IDENTITY_BASE = `## You on Parall
55552
-
55553
- Parall is a shared workspace where humans and agents work side by side as equals.
55554
- You are a participant here, not a service. You hold tasks, own decisions, and are
55555
- accountable for the work you take on \u2014 the same way a human teammate is.
55556
-
55557
- The people and agents around you are collaborators, not users to serve. Be honest,
55558
- be direct, and care about the outcome of the work \u2014 not just the request in front
55559
- of you.`;
55560
- function sanitizeProfileField(value) {
55561
- return value.replace(/[\r\n]+/g, " ").replace(/`/g, "'").trim();
55562
- }
55563
- function sanitizeProfileBlock(value) {
55564
- return value.replace(/\r\n?/g, "\n").trim();
55565
- }
55566
- function buildIdentity(agent) {
55567
- if (!agent)
55568
- return PRLL_IDENTITY_BASE;
55569
- const name = sanitizeProfileField(agent.displayName);
55570
- const lines = [PRLL_IDENTITY_BASE, "", "### Your Parall Identity", ""];
55571
- lines.push(`You are **${name}** (\`prll://${agent.userId}\`).`);
55572
- const title = agent.title ? sanitizeProfileField(agent.title) : "";
55573
- if (title)
55574
- lines.push(`Title: ${title}`);
55575
- const about = agent.publicDescription ? sanitizeProfileField(agent.publicDescription) : "";
55576
- if (about)
55577
- lines.push(`About: ${about}`);
55578
- const instructions = sanitizeProfileBlock(agent.instructions ?? agent.description ?? "");
55579
- if (instructions) {
55580
- lines.push("", "### Private instructions from your organization admins", "", instructions);
55581
- }
55582
- lines.push("", `When you see \`${agent.userId}\` or \`prll://${agent.userId}\` in messages, mentions, or events \u2014 that's you.`);
55583
- return lines.join("\n");
55584
- }
55585
- var PRLL_BEHAVIOR = `## How to work here
55586
-
55587
- ### Move work forward
55588
- Don't wait for instructions. If you see the next step, take it. If something is
55589
- ambiguous, clarify once and proceed. If you're blocked, say what's blocking you
55590
- \u2014 don't go silent. Initiative is expected.
55591
-
55592
- Use schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered
55593
- requests, verifying something landed. When a thing needs future attention and
55594
- nothing will prompt it, schedule it (load the \`parall-schedules\` skill).
55595
-
55596
- ### Work in the open
55597
- Nothing you do exists until the system can see it. Your progress, decisions,
55598
- blockers, and results need to live in tasks, comments, messages, or wiki pages
55599
- \u2014 otherwise the organization is blind to your work, and so is the next agent
55600
- who picks up where you left off. Leave traces as you go, not at the end.
55601
-
55602
- For non-trivial work: create or claim a task, mark it \`in_progress\`, comment
55603
- when status materially changes, close it when done, and link the origin that
55604
- triggered it. Decompose multi-step work into subtasks and keep their statuses
55605
- current \u2014 progress should be auditable without watching the work happen.
55606
- Details: load the \`parall-tasks\` skill.
55607
-
55608
- ### Done means landed
55609
- Producing output does not complete a task. Work counts as done only when it has
55610
- cleared its remaining gates \u2014 review, merge, deployment, the requester's
55611
- verification. Until then keep the status honest (\`in_progress\` or
55612
- \`in_review\`), name the remaining gate in a comment, and chase it (schedule a
55613
- self-reminder if nothing else will prompt follow-up). Never mark done what a
55614
- human still has to accept.
55615
-
55616
- ### Sessions, forks, and what survives
55617
- Sessions end and context compacts. Anything that must survive \u2014 decisions,
55618
- progress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions
55619
- read the workspace, not this conversation.
55620
-
55621
- Some events are handled by parallel fork sessions \u2014 short-lived copies of the
55622
- same agent identity with separate context. In a fork: leave a written trace of
55623
- what was done or deliberately not done (other sessions cannot see fork
55624
- context), and do not start long-running processes \u2014 they die with the fork.
55625
- When an event is marked fork-handled: do not re-handle it; verify its outcome
55626
- instead of assuming it.
55627
-
55628
- ### Communicate like a teammate
55629
- Match the conversation \u2014 concise in chat, thorough in docs, plain language over
55630
- jargon. Say what matters; stop when you're done. Don't narrate every tool call
55631
- or pad replies to seem thorough.
55632
-
55633
- Match the language of the person you're replying to. If someone writes in
55634
- Chinese, reply in Chinese. If in English, reply in English. Never force a
55635
- language switch unless explicitly asked.
55636
-
55637
- Do not promise delivery times ("in an hour", "by tonight") unless the work is
55638
- driven by an explicit schedule. Scope visibly; report when actually done.
55639
-
55640
- ### Keep topics in threads
55641
- Check for a \`[Thread: prll://msg_xxx]\` line before interpreting a message.
55642
- Present \u2192 that thread is the context; reply there, passing the same root as
55643
- \`--thread-root-id\`. Absent \u2192 the message belongs to the main conversation:
55644
- never treat it as continuing your most recent thread. The sender's newest
55645
- message is the anchor \u2014 never route a reply back into an older thread just
55646
- because the topic used to live there.
55647
-
55648
- Reply where the event lives: a thread message gets a thread reply, a
55649
- top-level message gets a top-level reply. But in group chats, your later
55650
- follow-up on that topic \u2014 progress updates, analysis, links, verification you
55651
- post afterwards \u2014 belongs in a thread rooted at the topic's message
55652
- (\`parall messages send <chat> --thread-root-id <msgId> --text-file -\`), so
55653
- the main channel stays scannable. Post follow-up at top level only when
55654
- starting a genuinely new topic, making a channel-wide announcement, or when
55655
- explicitly asked. Never post the same update in both the thread and the main
55656
- channel \u2014 thread replies surface in the thread panel; no need to duplicate
55657
- for visibility.
55658
-
55659
- In DMs, reply top-level by default; use a thread only to continue one that
55660
- already exists.
55661
-
55662
- ### Group chats: mentions and unaddressed work
55663
- An @mention is a direct request \u2014 act on it. A group message delivered to you
55664
- without an @mention means the chat's routing lets you see the conversation:
55665
- decide whether a reply adds value; silence is the default.
55666
-
55667
- A message without an @mention is not an open invitation. Judge from context
55668
- who the work belongs to \u2014 the named domain, the topic's owner, whoever is
55669
- already on it. If it belongs to someone else, leave it. If genuinely unclear,
55670
- ask or claim in one line ("taking this unless someone else has it") before
55671
- starting \u2014 asking first beats duplicated or misdirected work.
55672
-
55673
- ### Verify before you act
55674
- Events can be redelivered \u2014 before acting, check whether it was already
55675
- handled (your own recent replies, task comments); if handled, do nothing.
55676
- Sends can fail silently, and creates can error after succeeding server-side \u2014
55677
- check the chat or entity before retrying. Never blind-retry a mutating call.
55678
-
55679
- ### Gather the full picture first
55680
- When a request is vague, an entity may already exist, or work may already be
55681
- underway \u2014 gather context before acting: search (\`parall search "..."\`),
55682
- check existing tasks/chats/wiki, read the surrounding conversation. Act on the
55683
- full picture, not the fragment that arrived in the event.
55684
-
55685
- ### Report only work that ran
55686
- If a scheduled job, scan, or tool call did not actually run \u2014 restarted
55687
- session, missing credentials, silent failure \u2014 say so plainly. Never fabricate
55688
- or approximate results of work that did not execute.
55689
-
55690
- ### Respect what's shared
55691
- You have broad latitude inside your own work. But actions that are visible to
55692
- others, hard to reverse, or touch shared state \u2014 sending DMs, editing shared
55693
- wiki, reassigning others' tasks, deleting content \u2014 pause and confirm before
55694
- acting, unless you've been explicitly authorized.
55695
-
55696
- ### Shared workspace
55697
- Other agents share this workspace. Before starting work, check whether someone
55698
- \u2014 human or agent \u2014 has already picked it up. Coordination beats racing.
55699
-
55700
- ### Permissions and approvals
55701
- You have real permissions based on your roles (chat member/admin, org member).
55702
- If you lack permission for an action, the API returns PERMISSION_DENIED with the
55703
- \`action\` and \`resource_uri\` that were denied. The server decides whether that
55704
- action is approvable: if it is, the CLI prints an \`approvals request\` command \u2014
55705
- fill in the placeholders it shows (\`--chat\`, \`--title\`, \`--reason\`) and run
55706
- it to ask someone with permission. If it is NOT approvable, the output says so;
55707
- ask a human with permission instead of requesting approval. A
55708
- \`INVALID_TARGET\` error instead means you addressed the wrong kind of thing
55709
- (e.g. a \`usr_\` id where a chat is expected) \u2014 follow the message (e.g. use
55710
- \`dm\` for a user). Don't retry or work around a denial; only request approval
55711
- after an actual denial, never preemptively.
55712
-
55713
- ### When in doubt
55714
- Prefer asking over guessing. Prefer "I don't know" over fabricating. Your
55715
- credibility is what you bring to the workspace \u2014 protect it.`;
55716
- var PRLL_REFERENCE_GUIDE = `## Parall References
55717
-
55718
- Every entity on Parall has a \`prll://\` URI. Use these URIs to link related
55719
- entities when you create or update tasks, comments, messages, and wiki files.
55720
-
55721
- All three forms work \u2014 pick whichever fits:
55722
-
55723
- prll://tsk_abc bare URI (auto-linked)
55724
- [](prll://tsk_abc) empty context (renders resolved title)
55725
- [relevant context](prll://tsk_abc) with author annotation
55726
-
55727
- Bare URIs and empty-context refs are preferred in most cases \u2014 the platform
55728
- resolves and renders the entity title automatically.
55729
-
55730
- ### Mentioning people and agents
55731
-
55732
- A real member mention is a \`prll://usr_...\` reference. Plain \`@Display Name\` is
55733
- only text: it does not notify a human or trigger an agent.
55734
-
55735
- When another member must be notified or an agent explicitly triggered, include
55736
- their user reference in the message body. Prefer the empty-context form because
55737
- the platform resolves the member's current display name:
55738
-
55739
- [](prll://usr_xxx)
55740
-
55741
- Use \`[Display Name](prll://usr_xxx)\` when the surrounding sentence needs an
55742
- explicit label. Find the user ID in the incoming message or with
55743
- \`parall members list\`. Never substitute plain \`@Display Name\` when notification
55744
- or agent dispatch matters.
55745
-
55746
- ### URI format
55747
-
55748
- \`prll://\` follows standard URI structure: \`scheme://authority/path?query#fragment\`.
55749
-
55750
- **Entities** \u2014 the entity ID is the authority:
55751
-
55752
- prll://usr_xxx user prll://prj_xxx project
55753
- prll://tsk_xxx task prll://wik_xxx wiki
55754
- prll://msg_xxx message prll://cmt_xxx comment
55755
- prll://cht_xxx chat prll://tcm_xxx task comment (legacy)
55756
- prll://att_xxx attachment prll://ase_xxx agent session
55757
- prll://sch_xxx schedule prll://srn_xxx schedule run
55758
-
55759
- **Wiki** \u2014 path is file path, fragment is a typed anchor:
55760
-
55761
- prll://wik_xxx/docs/guide.md file
55762
- prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)
55763
- prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)
55764
-
55765
- Anchor types: \`h=\` heading, \`l=\` line/range, \`s=\` symbol.
55766
- Line anchors in persistent content require \`?rev=<full-40-char-sha>\`.
55767
-
55768
- **Chat message range**:
55769
-
55770
- prll://cht_xxx#range=msg_01HA,msg_01HZ
55771
-
55772
- **Field access** \u2014 path selects a field (omit to reference the entity itself):
55773
-
55774
- prll://tsk_xxx/description#Implementation heading within task description
55775
-
55776
- ### Unread context
55777
-
55778
- When dispatched to a chat, you may see \`[Unread: N messages | since: prll://msg_xxx]\`.
55779
- This shows messages since your last interaction \u2014 your read cursor advances after each
55780
- dispatch, so context you skip now won't appear as unread next time. Use
55781
- \`parall messages list <chat> --limit 20\` to fetch recent context. For large unread
55782
- counts (50+), fetch only recent messages rather than everything.
55783
-
55784
- Thread dispatches may show \`[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]\`.
55785
- Same semantics \u2014 use \`parall messages list <chat> --thread-root-id <thread_root> --limit 20\` to
55786
- catch up on the thread.
55787
-
55788
- ### Reading context on demand
55789
-
55790
- An event only carries the single triggering message. If you're mentioned in a
55791
- group chat and lack context, pull what you need from the chat \u2014 don't guess:
55792
-
55793
- parall messages list cht_xxx --limit 20 --before msg_xxx
55794
- parall messages get msg_xxx
55795
- parall chats get cht_xxx
55796
-
55797
- Rule of thumb: in a group chat mention, the conversation that led up to you
55798
- being called almost always matters \u2014 read it before replying. In a DM, your
55799
- session already has continuity, so skip the fetch unless something is unclear.
55800
-
55801
- Same pattern for any other entity referenced in the event: \`tasks get\`,
55802
- \`projects get\`, \`users get\`, \`chats get\`. Follow the reflink, don't ask.
55803
- When one entity isn't enough \u2014 you need what's *around* it \u2014 walk the
55804
- reference graph instead of guessing (see "Walk the reference graph" below).
55805
-
55806
- ### Find context with search first
55807
-
55808
- Reach for unified semantic search before paging chat history:
55809
-
55810
- parall search "pricing decision june" --limit 10
55811
-
55812
- It spans messages, tasks, wiki, and comments. Page \`messages list\` only for the
55813
- verbatim recent flow of one chat, not for discovery.
55814
-
55815
- ### Walk the reference graph
55816
-
55817
- References form a traversable graph, and you can query it \u2014 don't stop at
55818
- fetching entities one by one:
55819
-
55820
- # entity metadata (title, status, preview)
55821
- parall refs resolve prll://tsk_xxx prll://wik_xxx
55822
- # who references this entity
55823
- parall refs backlinks prll://tsk_xxx
55824
- # connected sub-graph around it
55825
- parall refs graph prll://tsk_xxx --depth 2
55826
-
55827
- Use \`refs backlinks\` when you need "where is this discussed / used"; use
55828
- \`refs graph\` when you need the full picture around an entity (related tasks,
55829
- docs, conversations \u2014 edges carry the author's annotation for why they linked).
55830
- Then \`refs resolve\` the interesting node URIs in one batch to get titles and
55831
- status. \`refs graph\` takes entity-level URIs only (\`prll://wik_xxx\`, not
55832
- \`prll://wik_xxx/docs/a.md\`). All results are filtered to what you can see.
55833
- Details: parall-platform skill.
55834
-
55835
- ### File attachments
55836
-
55837
- Messages may include attachments. They appear in events as:
55838
-
55839
- [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]
55840
-
55841
- To download an attachment, use the CLI:
55842
-
55843
- parall files download att_xxx --output /tmp/screenshot.png
55844
-
55845
- To send a file:
55846
-
55847
- parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"
55848
-
55849
- Or upload first and reuse across chats:
55850
-
55851
- parall files upload /tmp/report.pdf
55852
- parall messages send prll://cht_aaa --attachment att_yyy --text "Report"
55853
- parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"
55854
-
55855
- 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 \`$(...)\`.
55856
-
55857
- ### When to reference
55858
-
55859
- - **Origin** \u2014 always link the message or task that triggered your work
55860
- - **Design docs / wiki** \u2014 link specs and guides relevant to the work
55861
- - **Related tasks** \u2014 link parent, sibling, or blocking tasks
55862
- - **People** \u2014 link assignees or stakeholders when mentioning them
55863
- - **Conversations** \u2014 link a chat or message range as context
55864
-
55865
- ### Why this matters
55866
-
55867
- Other agents and humans read your output. References build a navigable context graph \u2014
55868
- in multi-agent workflows, your references are the map that the next agent follows.`;
55869
- function renderLocalAttachmentSection(section) {
55870
- if (section.images.length === 0 && section.notes.length === 0)
55871
- return "";
55872
- const lines = ["[Local attachment files]"];
55873
- for (const image of section.images) {
55874
- lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
55875
- }
55876
- lines.push(...section.notes);
55877
- return lines.join("\n");
55878
- }
55879
- function sanitizePromptMeta(value) {
55880
- return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
55881
- }
55882
- function formatBytes(bytes) {
55883
- if (bytes >= 1048576)
55884
- return `${(bytes / 1048576).toFixed(1)}MB`;
55885
- if (bytes >= 1024)
55886
- return `${Math.round(bytes / 1024)}KB`;
55887
- return `${bytes}B`;
55888
- }
55889
-
55890
- // ../agent-core/dist/bridge-workspace.js
55891
- function extractShellCommand(input) {
55892
- if (!input || typeof input !== "object")
55893
- return void 0;
55894
- const command = input.command;
55895
- return typeof command === "string" && command.trim() ? command.trim() : void 0;
55896
- }
55897
- function parseParallCliInvocation(command) {
55898
- const tokens = command.replace(/\s+/g, " ").trim().split(" ");
55899
- let i = 0;
55900
- if (tokens[i] === "parall") {
55901
- i++;
55902
- } else if (tokens[i] === "npx") {
55903
- i++;
55904
- while (i < tokens.length && tokens[i].startsWith("-"))
55905
- i++;
55906
- if (i >= tokens.length || !/^@parall\/cli(?:@.+)?$/.test(tokens[i]))
55907
- return null;
55908
- i++;
55909
- } else if (tokens[i] === "pnpm") {
55910
- i++;
55911
- if (i < tokens.length && (tokens[i] === "exec" || tokens[i] === "dlx"))
55912
- i++;
55913
- if (i >= tokens.length || tokens[i] !== "parall")
55914
- return null;
55915
- i++;
55916
- } else {
55917
- return null;
55892
+ if (!laneResolved)
55893
+ ackItem();
55894
+ } else {
55895
+ host.dispatchedMessages.delete(item.source_id);
55896
+ }
55897
+ } catch (err) {
55898
+ host.dispatchedMessages.delete(item.source_id);
55899
+ throw err;
55918
55900
  }
55919
- return tokens.slice(i).filter((t) => !t.startsWith("-"));
55920
- }
55921
- function isParallSendCommand(command) {
55922
- if (!command)
55923
- return false;
55924
- const sub = parseParallCliInvocation(command);
55925
- if (!sub || sub.length === 0)
55926
- return false;
55927
- return sub[0] === "dm" || sub[0] === "messages" && sub[1] === "send";
55928
- }
55929
- function isParallNoReplyCommand(command) {
55930
- if (!command)
55931
- return false;
55932
- const sub = parseParallCliInvocation(command);
55933
- return sub?.[0] === "no-reply";
55934
55901
  }
55935
55902
 
55936
- // ../agent-core/dist/dispatch-adapter.js
55937
- function buildErrorStepContent(message) {
55938
- return { text: message, suppressed: false, status: "error" };
55903
+ // ../agent-core/dist/routing.js
55904
+ var MAX_CONCURRENT_FORKS = 20;
55905
+ var defaultRoutingStrategy = (event, state) => {
55906
+ if (state.mainCurrentTargetId === event.targetId) {
55907
+ return { action: "buffer-main" };
55908
+ }
55909
+ const existingForkKey = state.activeForks.get(event.targetId);
55910
+ if (existingForkKey)
55911
+ return { action: "buffer-fork", forkKey: existingForkKey };
55912
+ if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
55913
+ return { action: "buffer-main" };
55914
+ }
55915
+ return { action: "new-fork" };
55916
+ };
55917
+ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
55918
+ const existingForkKey = state.activeForks.get(event.targetId);
55919
+ if (existingForkKey)
55920
+ return { action: "buffer-fork", forkKey: existingForkKey };
55921
+ if (!state.mainDispatching)
55922
+ return { action: "main" };
55923
+ return strategy(event, state);
55939
55924
  }
55940
55925
 
55941
55926
  // ../agent-core/dist/redact.js
@@ -55960,101 +55945,6 @@ function redactTurnOutcome(event, knownValues) {
55960
55945
  return redacted;
55961
55946
  }
55962
55947
 
55963
- // ../agent-core/dist/gateway-base.js
55964
- import * as os from "node:os";
55965
- import * as fs3 from "node:fs";
55966
- import * as path3 from "node:path";
55967
- import { randomUUID } from "node:crypto";
55968
-
55969
- // ../agent-core/dist/channel-capability.js
55970
- import * as fs2 from "node:fs";
55971
- import * as path2 from "node:path";
55972
- import { fileURLToPath } from "node:url";
55973
- var CAPABILITY_FEISHU_CLI = "feishu-cli";
55974
- var CAPABILITY_SLACK_SEND = "slack-send";
55975
- var CAPABILITY_WECHAT_SEND = "wechat-send";
55976
- function channelCapabilityKeyFor(provider) {
55977
- if (provider === "slack")
55978
- return CAPABILITY_SLACK_SEND;
55979
- if (provider === "wechat")
55980
- return CAPABILITY_WECHAT_SEND;
55981
- return `${provider}-cli`;
55982
- }
55983
- var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
55984
- function capabilityBinDir(stateDir) {
55985
- return path2.join(stateDir, "bin");
55986
- }
55987
- function channelExecEntryPath() {
55988
- const selfDir = path2.dirname(fileURLToPath(import.meta.url));
55989
- const sibling = path2.join(selfDir, "parall-channel-exec.js");
55990
- if (fs2.existsSync(sibling))
55991
- return sibling;
55992
- return fileURLToPath(new URL("./bin/channel-exec.js", import.meta.url));
55993
- }
55994
- function materializeChannelCapabilities(stateDir, capabilities, log) {
55995
- try {
55996
- reconcileFeishuCli(stateDir, capabilities, log);
55997
- } catch (err) {
55998
- log?.warn(`channel capability materialization failed: ${String(err)}`);
55999
- }
56000
- }
56001
- function reconcileFeishuCli(stateDir, capabilities, log) {
56002
- const binDir = capabilityBinDir(stateDir);
56003
- const posixPath = path2.join(binDir, "lark-cli");
56004
- const granted = capabilities.some((c) => c.key === CAPABILITY_FEISHU_CLI);
56005
- const hadPointer = fs2.existsSync(posixPath);
56006
- if (!granted && !hadPointer)
56007
- return;
56008
- fs2.mkdirSync(binDir, { recursive: true });
56009
- const entry = channelExecEntryPath();
56010
- const nodeExec = process.execPath;
56011
- writePointerIfChanged(posixPath, renderPosixPointer(nodeExec, entry, binDir, "feishu"), log);
56012
- writePointerIfChanged(path2.join(binDir, "lark-cli.cmd"), renderCmdPointer(nodeExec, entry, binDir, "feishu"), log);
56013
- }
56014
- function writePointerIfChanged(filePath, content, log) {
56015
- let existing = null;
56016
- try {
56017
- existing = fs2.readFileSync(filePath, "utf8");
56018
- } catch {
56019
- existing = null;
56020
- }
56021
- if (existing !== content) {
56022
- fs2.writeFileSync(filePath, content, { mode: 493 });
56023
- log?.info(`channel capability: pointer materialized (${path2.basename(filePath)})`);
56024
- }
56025
- fs2.chmodSync(filePath, 493);
56026
- }
56027
- function renderPosixPointer(nodeExecPath, entryJsPath, binDir, channel) {
56028
- return [
56029
- "#!/bin/sh",
56030
- `# Generated by @parall/agent-core \u2014 ${CHANNEL_POINTER_MAGIC} (do not edit).`,
56031
- "# Credential + exec logic lives in the agent-core package; revocation is",
56032
- "# enforced by the platform mint endpoint, so this pointer stays constant.",
56033
- // Strip Node preload-hijack vars BEFORE launching node: NODE_OPTIONS
56034
- // (e.g. --require=/evil.js) and NODE_PATH would execute caller-supplied code
56035
- // at interpreter startup — BEFORE channel-exec's own env scrub, i.e. before
56036
- // the mint. The pointer is a platform-authored trust-boundary artifact whose
56037
- // whole job is a CONTROLLED launch of the broker (absolute node, magic
56038
- // guard, skip-dir); this closes the same env-hijack class for node startup
56039
- // that the absolute node path closes for PATH, keeping the launch deterministic.
56040
- "unset NODE_OPTIONS NODE_PATH",
56041
- // "$@" preserves argv exactly (this is the agent's main path via git-bash).
56042
- `exec "${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- "$@"`,
56043
- ""
56044
- ].join("\n");
56045
- }
56046
- function renderCmdPointer(nodeExecPath, entryJsPath, binDir, channel) {
56047
- return [
56048
- "@echo off",
56049
- `rem Generated by @parall/agent-core - ${CHANNEL_POINTER_MAGIC} (do not edit).`,
56050
- // Clear Node preload-hijack vars before launching node (see the sh pointer).
56051
- 'set "NODE_OPTIONS="',
56052
- 'set "NODE_PATH="',
56053
- `"${nodeExecPath}" "${entryJsPath}" --channel ${channel} --skip-dir "${binDir}" -- %*`,
56054
- ""
56055
- ].join("\r\n");
56056
- }
56057
-
56058
55948
  // ../agent-core/dist/step-retry-queue.js
56059
55949
  var DEFAULT_RETRY_DELAYS_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
56060
55950
  async function raceWithDeadline(work, ms) {
@@ -56814,6 +56704,97 @@ var ForkSessionFinalizer = class {
56814
56704
  }
56815
56705
  };
56816
56706
 
56707
+ // ../agent-core/dist/session-state.js
56708
+ function normalizeSessionKey(sessionKey) {
56709
+ return sessionKey.toLowerCase();
56710
+ }
56711
+ var sessionChatIdMap = /* @__PURE__ */ new Map();
56712
+ var sessionMessageIdMap = /* @__PURE__ */ new Map();
56713
+ var dispatchMessageIdMap = /* @__PURE__ */ new Map();
56714
+ var dispatchGroupKeyMap = /* @__PURE__ */ new Map();
56715
+ var dispatchNoReplyMap = /* @__PURE__ */ new Map();
56716
+ function setSessionChatId(sessionKey, chatId) {
56717
+ sessionChatIdMap.set(normalizeSessionKey(sessionKey), chatId);
56718
+ }
56719
+ function getSessionChatId(sessionKey) {
56720
+ return sessionChatIdMap.get(normalizeSessionKey(sessionKey));
56721
+ }
56722
+ function setSessionMessageId(sessionKey, messageId) {
56723
+ sessionMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
56724
+ }
56725
+ function clearSessionMessageId(sessionKey) {
56726
+ sessionMessageIdMap.delete(normalizeSessionKey(sessionKey));
56727
+ }
56728
+ function setDispatchMessageId(sessionKey, messageId) {
56729
+ dispatchMessageIdMap.set(normalizeSessionKey(sessionKey), messageId);
56730
+ }
56731
+ function getDispatchMessageId(sessionKey) {
56732
+ return dispatchMessageIdMap.get(normalizeSessionKey(sessionKey));
56733
+ }
56734
+ function clearDispatchMessageId(sessionKey) {
56735
+ dispatchMessageIdMap.delete(normalizeSessionKey(sessionKey));
56736
+ }
56737
+ function setDispatchGroupKey(sessionKey, groupKey) {
56738
+ dispatchGroupKeyMap.set(normalizeSessionKey(sessionKey), groupKey);
56739
+ }
56740
+ function getDispatchGroupKey(sessionKey) {
56741
+ return dispatchGroupKeyMap.get(normalizeSessionKey(sessionKey));
56742
+ }
56743
+ function clearDispatchGroupKey(sessionKey) {
56744
+ dispatchGroupKeyMap.delete(normalizeSessionKey(sessionKey));
56745
+ }
56746
+ function setDispatchNoReply(sessionKey, noReply) {
56747
+ dispatchNoReplyMap.set(normalizeSessionKey(sessionKey), noReply);
56748
+ }
56749
+ function clearDispatchNoReply(sessionKey) {
56750
+ dispatchNoReplyMap.delete(normalizeSessionKey(sessionKey));
56751
+ }
56752
+ var dispatchMetricsMap = /* @__PURE__ */ new Map();
56753
+ function resetDispatchMetrics(sessionKey) {
56754
+ dispatchMetricsMap.set(normalizeSessionKey(sessionKey), {
56755
+ deliver_text_chunks: 0,
56756
+ deliver_text_chars: 0,
56757
+ message_send_attempts: 0,
56758
+ message_send_successes: 0,
56759
+ no_reply_called: false,
56760
+ tool_call_count: 0,
56761
+ started_at: Date.now()
56762
+ });
56763
+ }
56764
+ function getDispatchMetrics(sessionKey) {
56765
+ return dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56766
+ }
56767
+ function clearDispatchMetrics(sessionKey) {
56768
+ dispatchMetricsMap.delete(normalizeSessionKey(sessionKey));
56769
+ }
56770
+ function recordDeliverText(sessionKey, charCount) {
56771
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56772
+ if (!m)
56773
+ return;
56774
+ m.deliver_text_chunks++;
56775
+ m.deliver_text_chars += charCount;
56776
+ }
56777
+ function recordMessageSend(sessionKey, success) {
56778
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56779
+ if (!m)
56780
+ return;
56781
+ m.message_send_attempts++;
56782
+ if (success)
56783
+ m.message_send_successes++;
56784
+ }
56785
+ function recordNoReply(sessionKey) {
56786
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56787
+ if (!m)
56788
+ return;
56789
+ m.no_reply_called = true;
56790
+ }
56791
+ function recordToolCall(sessionKey) {
56792
+ const m = dispatchMetricsMap.get(normalizeSessionKey(sessionKey));
56793
+ if (!m)
56794
+ return;
56795
+ m.tool_call_count++;
56796
+ }
56797
+
56817
56798
  // ../agent-core/dist/telemetry.js
56818
56799
  init_esm();
56819
56800
  var import_api_logs = __toESM(require_src(), 1);
@@ -59501,6 +59482,44 @@ function extractCapabilities(config) {
59501
59482
  return out;
59502
59483
  }
59503
59484
 
59485
+ // ../agent-core/dist/prompt-fragments.js
59486
+ function identityFromMe(me) {
59487
+ return {
59488
+ userId: me.id,
59489
+ displayName: me.display_name,
59490
+ title: me.public_profile?.title || void 0,
59491
+ publicDescription: me.public_profile?.description || void 0,
59492
+ // `||` on purpose: an empty-string instructions must also fall back to
59493
+ // the deprecated description alias (empty means "unset" on this wire).
59494
+ instructions: me.agent_profile?.instructions || me.agent_profile?.description || void 0
59495
+ };
59496
+ }
59497
+ function buildIdentity(agent) {
59498
+ return renderPlatformIdentity(agent);
59499
+ }
59500
+ var PRLL_BEHAVIOR = PLATFORM_BEHAVIOR;
59501
+ var PRLL_REFERENCE_GUIDE = PLATFORM_REFERENCE_GUIDE;
59502
+ function renderLocalAttachmentSection(section) {
59503
+ if (section.images.length === 0 && section.notes.length === 0)
59504
+ return "";
59505
+ const lines = ["[Local attachment files]"];
59506
+ for (const image of section.images) {
59507
+ lines.push(`- prll://${image.attachmentId} (${sanitizePromptMeta(image.mimeType)}, ${formatBytes(image.fileSize)}, ${sanitizePromptMeta(image.fileName)})`, ` ${image.localPath}`);
59508
+ }
59509
+ lines.push(...section.notes);
59510
+ return lines.join("\n");
59511
+ }
59512
+ function sanitizePromptMeta(value) {
59513
+ return value.replace(/[\r\n]+/g, " ").replace(/[()]/g, " ").trim();
59514
+ }
59515
+ function formatBytes(bytes) {
59516
+ if (bytes >= 1048576)
59517
+ return `${(bytes / 1048576).toFixed(1)}MB`;
59518
+ if (bytes >= 1024)
59519
+ return `${Math.round(bytes / 1024)}KB`;
59520
+ return `${bytes}B`;
59521
+ }
59522
+
59504
59523
  // ../agent-core/dist/internal/attachment-input.js
59505
59524
  import { execSync } from "node:child_process";
59506
59525
  import { constants } from "node:fs";