@parall/daemon 1.57.2 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17719,9 +17719,9 @@ var require_getMachineId_linux = __commonJS({
17719
17719
  var api_1 = (init_esm(), __toCommonJS(esm_exports));
17720
17720
  async function getMachineId() {
17721
17721
  const paths = ["/etc/machine-id", "/var/lib/dbus/machine-id"];
17722
- for (const path11 of paths) {
17722
+ for (const path12 of paths) {
17723
17723
  try {
17724
- const result = await fs_1.promises.readFile(path11, { encoding: "utf8" });
17724
+ const result = await fs_1.promises.readFile(path12, { encoding: "utf8" });
17725
17725
  return result.trim();
17726
17726
  } catch (e) {
17727
17727
  api_1.diag.debug(`error reading machine id: ${e}`);
@@ -21124,7 +21124,7 @@ function appendRootPathToUrlIfNeeded(url) {
21124
21124
  return void 0;
21125
21125
  }
21126
21126
  }
21127
- function appendResourcePathToUrl(url, path11) {
21127
+ function appendResourcePathToUrl(url, path12) {
21128
21128
  try {
21129
21129
  new URL(url);
21130
21130
  } catch (_a) {
@@ -21134,11 +21134,11 @@ function appendResourcePathToUrl(url, path11) {
21134
21134
  if (!url.endsWith("/")) {
21135
21135
  url = url + "/";
21136
21136
  }
21137
- url += path11;
21137
+ url += path12;
21138
21138
  try {
21139
21139
  new URL(url);
21140
21140
  } catch (_b) {
21141
- diag2.warn("Configuration: Provided URL appended with '" + path11 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
21141
+ diag2.warn("Configuration: Provided URL appended with '" + path12 + "' is not a valid URL, using 'undefined' instead of '" + url + "'");
21142
21142
  return void 0;
21143
21143
  }
21144
21144
  return url;
@@ -27549,14 +27549,14 @@ var require_util2 = __commonJS({
27549
27549
  }
27550
27550
  const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
27551
27551
  let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`;
27552
- let path11 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
27552
+ let path12 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
27553
27553
  if (origin[origin.length - 1] === "/") {
27554
27554
  origin = origin.slice(0, origin.length - 1);
27555
27555
  }
27556
- if (path11 && path11[0] !== "/") {
27557
- path11 = `/${path11}`;
27556
+ if (path12 && path12[0] !== "/") {
27557
+ path12 = `/${path12}`;
27558
27558
  }
27559
- return new URL(`${origin}${path11}`);
27559
+ return new URL(`${origin}${path12}`);
27560
27560
  }
27561
27561
  if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
27562
27562
  throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -28377,9 +28377,9 @@ var require_diagnostics = __commonJS({
28377
28377
  "undici:client:sendHeaders",
28378
28378
  (evt) => {
28379
28379
  const {
28380
- request: { method, path: path11, origin }
28380
+ request: { method, path: path12, origin }
28381
28381
  } = evt;
28382
- debugLog("sending request to %s %s%s", method, origin, path11);
28382
+ debugLog("sending request to %s %s%s", method, origin, path12);
28383
28383
  }
28384
28384
  );
28385
28385
  }
@@ -28397,14 +28397,14 @@ var require_diagnostics = __commonJS({
28397
28397
  "undici:request:headers",
28398
28398
  (evt) => {
28399
28399
  const {
28400
- request: { method, path: path11, origin },
28400
+ request: { method, path: path12, origin },
28401
28401
  response: { statusCode }
28402
28402
  } = evt;
28403
28403
  debugLog(
28404
28404
  "received response to %s %s%s - HTTP %d",
28405
28405
  method,
28406
28406
  origin,
28407
- path11,
28407
+ path12,
28408
28408
  statusCode
28409
28409
  );
28410
28410
  }
@@ -28413,23 +28413,23 @@ var require_diagnostics = __commonJS({
28413
28413
  "undici:request:trailers",
28414
28414
  (evt) => {
28415
28415
  const {
28416
- request: { method, path: path11, origin }
28416
+ request: { method, path: path12, origin }
28417
28417
  } = evt;
28418
- debugLog("trailers received from %s %s%s", method, origin, path11);
28418
+ debugLog("trailers received from %s %s%s", method, origin, path12);
28419
28419
  }
28420
28420
  );
28421
28421
  diagnosticsChannel.subscribe(
28422
28422
  "undici:request:error",
28423
28423
  (evt) => {
28424
28424
  const {
28425
- request: { method, path: path11, origin },
28425
+ request: { method, path: path12, origin },
28426
28426
  error
28427
28427
  } = evt;
28428
28428
  debugLog(
28429
28429
  "request to %s %s%s errored - %s",
28430
28430
  method,
28431
28431
  origin,
28432
- path11,
28432
+ path12,
28433
28433
  error.message
28434
28434
  );
28435
28435
  }
@@ -28532,7 +28532,7 @@ var require_request = __commonJS({
28532
28532
  var kHandler = Symbol("handler");
28533
28533
  var Request = class {
28534
28534
  constructor(origin, {
28535
- path: path11,
28535
+ path: path12,
28536
28536
  method,
28537
28537
  body,
28538
28538
  headers,
@@ -28549,11 +28549,11 @@ var require_request = __commonJS({
28549
28549
  maxRedirections,
28550
28550
  typeOfService
28551
28551
  }, handler) {
28552
- if (typeof path11 !== "string") {
28552
+ if (typeof path12 !== "string") {
28553
28553
  throw new InvalidArgumentError("path must be a string");
28554
- } else if (path11[0] !== "/" && !(path11.startsWith("http://") || path11.startsWith("https://")) && method !== "CONNECT") {
28554
+ } else if (path12[0] !== "/" && !(path12.startsWith("http://") || path12.startsWith("https://")) && method !== "CONNECT") {
28555
28555
  throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
28556
- } else if (invalidPathRegex.test(path11)) {
28556
+ } else if (invalidPathRegex.test(path12)) {
28557
28557
  throw new InvalidArgumentError("invalid request path");
28558
28558
  }
28559
28559
  if (typeof method !== "string") {
@@ -28628,7 +28628,7 @@ var require_request = __commonJS({
28628
28628
  this.completed = false;
28629
28629
  this.aborted = false;
28630
28630
  this.upgrade = upgrade || null;
28631
- this.path = query ? serializePathWithQuery(path11, query) : path11;
28631
+ this.path = query ? serializePathWithQuery(path12, query) : path12;
28632
28632
  this.origin = origin;
28633
28633
  this.protocol = getProtocolFromUrlString(origin);
28634
28634
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -33667,7 +33667,7 @@ var require_client_h1 = __commonJS({
33667
33667
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
33668
33668
  }
33669
33669
  function writeH1(client, request3) {
33670
- const { method, path: path11, host, upgrade, blocking, reset } = request3;
33670
+ const { method, path: path12, host, upgrade, blocking, reset } = request3;
33671
33671
  let { body, headers, contentLength } = request3;
33672
33672
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
33673
33673
  if (util.isFormDataLike(body)) {
@@ -33736,7 +33736,7 @@ var require_client_h1 = __commonJS({
33736
33736
  if (socket.setTypeOfService) {
33737
33737
  socket.setTypeOfService(request3.typeOfService);
33738
33738
  }
33739
- let header = `${method} ${path11} HTTP/1.1\r
33739
+ let header = `${method} ${path12} HTTP/1.1\r
33740
33740
  `;
33741
33741
  if (typeof host === "string") {
33742
33742
  header += `host: ${host}\r
@@ -34389,7 +34389,7 @@ var require_client_h2 = __commonJS({
34389
34389
  function writeH2(client, request3) {
34390
34390
  const requestTimeout = request3.bodyTimeout ?? client[kBodyTimeout];
34391
34391
  const session = client[kHTTP2Session];
34392
- const { method, path: path11, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request3;
34392
+ const { method, path: path12, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request3;
34393
34393
  let { body } = request3;
34394
34394
  if (upgrade != null && upgrade !== "websocket") {
34395
34395
  util.errorRequest(client, request3, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -34457,7 +34457,7 @@ var require_client_h2 = __commonJS({
34457
34457
  }
34458
34458
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
34459
34459
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
34460
- headers[HTTP2_HEADER_PATH] = path11;
34460
+ headers[HTTP2_HEADER_PATH] = path12;
34461
34461
  if (protocol === "ws:" || protocol === "wss:") {
34462
34462
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
34463
34463
  } else {
@@ -34498,7 +34498,7 @@ var require_client_h2 = __commonJS({
34498
34498
  stream.setTimeout(requestTimeout);
34499
34499
  return true;
34500
34500
  }
34501
- headers[HTTP2_HEADER_PATH] = path11;
34501
+ headers[HTTP2_HEADER_PATH] = path12;
34502
34502
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
34503
34503
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
34504
34504
  if (body && typeof body.read === "function") {
@@ -36800,10 +36800,10 @@ var require_proxy_agent = __commonJS({
36800
36800
  };
36801
36801
  const {
36802
36802
  origin,
36803
- path: path11 = "/",
36803
+ path: path12 = "/",
36804
36804
  headers = {}
36805
36805
  } = opts;
36806
- opts.path = origin + path11;
36806
+ opts.path = origin + path12;
36807
36807
  if (!("host" in headers) && !("Host" in headers)) {
36808
36808
  const { host } = new URL(origin);
36809
36809
  headers.host = host;
@@ -38866,20 +38866,20 @@ var require_mock_utils = __commonJS({
38866
38866
  }
38867
38867
  return normalizedQp;
38868
38868
  }
38869
- function safeUrl(path11) {
38870
- if (typeof path11 !== "string") {
38871
- return path11;
38869
+ function safeUrl(path12) {
38870
+ if (typeof path12 !== "string") {
38871
+ return path12;
38872
38872
  }
38873
- const pathSegments = path11.split("?", 3);
38873
+ const pathSegments = path12.split("?", 3);
38874
38874
  if (pathSegments.length !== 2) {
38875
- return path11;
38875
+ return path12;
38876
38876
  }
38877
38877
  const qp = new URLSearchParams(pathSegments.pop());
38878
38878
  qp.sort();
38879
38879
  return [...pathSegments, qp.toString()].join("?");
38880
38880
  }
38881
- function matchKey(mockDispatch2, { path: path11, method, body, headers }) {
38882
- const pathMatch = matchValue(mockDispatch2.path, path11);
38881
+ function matchKey(mockDispatch2, { path: path12, method, body, headers }) {
38882
+ const pathMatch = matchValue(mockDispatch2.path, path12);
38883
38883
  const methodMatch = matchValue(mockDispatch2.method, method);
38884
38884
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
38885
38885
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -38904,8 +38904,8 @@ var require_mock_utils = __commonJS({
38904
38904
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
38905
38905
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
38906
38906
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
38907
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path11, ignoreTrailingSlash }) => {
38908
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path11)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path11), resolvedPath);
38907
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path12, ignoreTrailingSlash }) => {
38908
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path12)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path12), resolvedPath);
38909
38909
  });
38910
38910
  if (matchedMockDispatches.length === 0) {
38911
38911
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -38944,19 +38944,19 @@ var require_mock_utils = __commonJS({
38944
38944
  mockDispatches.splice(index, 1);
38945
38945
  }
38946
38946
  }
38947
- function removeTrailingSlash(path11) {
38948
- while (path11.endsWith("/")) {
38949
- path11 = path11.slice(0, -1);
38947
+ function removeTrailingSlash(path12) {
38948
+ while (path12.endsWith("/")) {
38949
+ path12 = path12.slice(0, -1);
38950
38950
  }
38951
- if (path11.length === 0) {
38952
- path11 = "/";
38951
+ if (path12.length === 0) {
38952
+ path12 = "/";
38953
38953
  }
38954
- return path11;
38954
+ return path12;
38955
38955
  }
38956
38956
  function buildKey(opts) {
38957
- const { path: path11, method, body, headers, query } = opts;
38957
+ const { path: path12, method, body, headers, query } = opts;
38958
38958
  return {
38959
- path: path11,
38959
+ path: path12,
38960
38960
  method,
38961
38961
  body,
38962
38962
  headers,
@@ -39646,10 +39646,10 @@ var require_pending_interceptors_formatter = __commonJS({
39646
39646
  }
39647
39647
  format(pendingInterceptors) {
39648
39648
  const withPrettyHeaders = pendingInterceptors.map(
39649
- ({ method, path: path11, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
39649
+ ({ method, path: path12, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
39650
39650
  Method: method,
39651
39651
  Origin: origin,
39652
- Path: path11,
39652
+ Path: path12,
39653
39653
  "Status code": statusCode,
39654
39654
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
39655
39655
  Invocations: timesInvoked,
@@ -39731,9 +39731,9 @@ var require_mock_agent = __commonJS({
39731
39731
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
39732
39732
  const dispatchOpts = { ...opts };
39733
39733
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
39734
- const [path11, searchParams] = dispatchOpts.path.split("?");
39734
+ const [path12, searchParams] = dispatchOpts.path.split("?");
39735
39735
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
39736
- dispatchOpts.path = `${path11}?${normalizedSearchParams}`;
39736
+ dispatchOpts.path = `${path12}?${normalizedSearchParams}`;
39737
39737
  }
39738
39738
  return this[kAgent].dispatch(dispatchOpts, handler);
39739
39739
  }
@@ -40134,12 +40134,12 @@ var require_snapshot_recorder = __commonJS({
40134
40134
  * @return {Promise<void>} - Resolves when snapshots are loaded
40135
40135
  */
40136
40136
  async loadSnapshots(filePath) {
40137
- const path11 = filePath || this.#snapshotPath;
40138
- if (!path11) {
40137
+ const path12 = filePath || this.#snapshotPath;
40138
+ if (!path12) {
40139
40139
  throw new InvalidArgumentError("Snapshot path is required");
40140
40140
  }
40141
40141
  try {
40142
- const data = await readFile(resolve3(path11), "utf8");
40142
+ const data = await readFile(resolve3(path12), "utf8");
40143
40143
  const parsed = JSON.parse(data);
40144
40144
  if (Array.isArray(parsed)) {
40145
40145
  this.#snapshots.clear();
@@ -40153,7 +40153,7 @@ var require_snapshot_recorder = __commonJS({
40153
40153
  if (error.code === "ENOENT") {
40154
40154
  this.#snapshots.clear();
40155
40155
  } else {
40156
- throw new UndiciError(`Failed to load snapshots from ${path11}`, { cause: error });
40156
+ throw new UndiciError(`Failed to load snapshots from ${path12}`, { cause: error });
40157
40157
  }
40158
40158
  }
40159
40159
  }
@@ -40164,11 +40164,11 @@ var require_snapshot_recorder = __commonJS({
40164
40164
  * @returns {Promise<void>} - Resolves when snapshots are saved
40165
40165
  */
40166
40166
  async saveSnapshots(filePath) {
40167
- const path11 = filePath || this.#snapshotPath;
40168
- if (!path11) {
40167
+ const path12 = filePath || this.#snapshotPath;
40168
+ if (!path12) {
40169
40169
  throw new InvalidArgumentError("Snapshot path is required");
40170
40170
  }
40171
- const resolvedPath = resolve3(path11);
40171
+ const resolvedPath = resolve3(path12);
40172
40172
  await mkdir2(dirname6(resolvedPath), { recursive: true });
40173
40173
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
40174
40174
  hash,
@@ -40793,15 +40793,15 @@ var require_redirect_handler = __commonJS({
40793
40793
  return;
40794
40794
  }
40795
40795
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
40796
- const path11 = search ? `${pathname}${search}` : pathname;
40797
- const redirectUrlString = `${origin}${path11}`;
40796
+ const path12 = search ? `${pathname}${search}` : pathname;
40797
+ const redirectUrlString = `${origin}${path12}`;
40798
40798
  for (const historyUrl of this.history) {
40799
40799
  if (historyUrl.toString() === redirectUrlString) {
40800
40800
  throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
40801
40801
  }
40802
40802
  }
40803
40803
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
40804
- this.opts.path = path11;
40804
+ this.opts.path = path12;
40805
40805
  this.opts.origin = origin;
40806
40806
  this.opts.query = null;
40807
40807
  }
@@ -47008,11 +47008,11 @@ var require_fetch = __commonJS({
47008
47008
  function dispatch({ body }) {
47009
47009
  const url = requestCurrentURL(request3);
47010
47010
  const agent = fetchParams.controller.dispatcher;
47011
- const path11 = url.pathname + url.search;
47011
+ const path12 = url.pathname + url.search;
47012
47012
  const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
47013
47013
  return new Promise((resolve3, reject) => agent.dispatch(
47014
47014
  {
47015
- path: hasTrailingQuestionMark ? `${path11}?` : path11,
47015
+ path: hasTrailingQuestionMark ? `${path12}?` : path12,
47016
47016
  origin: url.origin,
47017
47017
  method: request3.method,
47018
47018
  body: agent.isMockActive ? request3.body && (request3.body.source || request3.body.stream) : body,
@@ -47959,9 +47959,9 @@ var require_util5 = __commonJS({
47959
47959
  }
47960
47960
  }
47961
47961
  }
47962
- function validateCookiePath(path11) {
47963
- for (let i = 0; i < path11.length; ++i) {
47964
- const code = path11.charCodeAt(i);
47962
+ function validateCookiePath(path12) {
47963
+ for (let i = 0; i < path12.length; ++i) {
47964
+ const code = path12.charCodeAt(i);
47965
47965
  if (code < 32 || // exclude CTLs (0-31)
47966
47966
  code === 127 || // DEL
47967
47967
  code === 59) {
@@ -51131,11 +51131,11 @@ var require_undici = __commonJS({
51131
51131
  if (typeof opts.path !== "string") {
51132
51132
  throw new InvalidArgumentError("invalid opts.path");
51133
51133
  }
51134
- let path11 = opts.path;
51134
+ let path12 = opts.path;
51135
51135
  if (!opts.path.startsWith("/")) {
51136
- path11 = `/${path11}`;
51136
+ path12 = `/${path12}`;
51137
51137
  }
51138
- url = new URL(util.parseOrigin(url).origin + path11);
51138
+ url = new URL(util.parseOrigin(url).origin + path12);
51139
51139
  } else {
51140
51140
  if (!opts) {
51141
51141
  opts = typeof url === "object" ? url : {};
@@ -51250,9 +51250,9 @@ import * as os3 from "node:os";
51250
51250
  // ts/agent-core/dist/generated/platform-instructions.js
51251
51251
  var PLATFORM_IDENTITY_BASE = "## You on Parall\n\nParall is a shared workspace where humans and agents work side by side as equals.\nYou are a participant here, not a service. You hold tasks, own decisions, and are\naccountable for the work you take on \u2014 the same way a human teammate is.\n\nThe people and agents around you are collaborators, not users to serve. Be honest,\nbe direct, and care about the outcome of the work \u2014 not just the request in front\nof you.";
51252
51252
  var IDENTITY_PROFILE_SUFFIX = "### Your Parall Identity\n\nYou are **{{DISPLAY_NAME}}** (`prll://{{USER_ID}}`).{{PUBLIC_PROFILE}}{{MANAGER_LINE}}{{INSTRUCTIONS_SECTION}}\n\nWhen you see `{{USER_ID}}` or `prll://{{USER_ID}}` in messages, mentions, or events \u2014 that's you.";
51253
- var PLATFORM_BRIDGE_WORKSPACE_INSTRUCTIONS = '# Agent workspace\n\nYou are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.\n\n## Message Model\n\nIncoming events are rendered as structured `[Event: ...]` blocks.\nEach event includes `[Chat: ... (prll://cht_xxx)]` \u2014 use that chat ID (or full URI) when replying.\n\n**Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.\nTo say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.\n\n## Parall CLI\n\nAll outbound interactions go through the `parall` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If `parall` is not on PATH, use `npx --yes @parall/cli@latest` instead.\n\n- `parall messages send prll://cht_xxx --text-file -` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)\n- `parall dm prll://usr_xxx --text-file - [--no-reply]` \u2014 direct message another user\n- `parall tasks update prll://tsk_xxx --status in_progress` \u2014 task state\n- `parall no-reply [--reason "..."]` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)\n\n**Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands `$`, backticks, and `$(...)` inside `"..."` before the CLI sees them: `--text "That costs $1,000"` sends `That costs ,000`, and `--text "$(cmd)"` executes `cmd`. Pass message bodies via `--text-file <path>` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:\n\n```bash\nparall messages send prll://cht_xxx --text-file - <<\'EOF\'\nThat costs $1,000, and $(whoami) stays literal. I\'m on it.\nEOF\n```\n\nKeep `--text "..."` for short literals with no `$`, backtick, or apostrophe.\n\nThe bridge injects Parall context via environment variables. The static credentials `PRLL_API_URL`, `PRLL_API_KEY`, and `PRLL_ORG_ID` are always set. `PRLL_CONTEXT_FILE` points to a per-session JSON file that the gateway updates each dispatch with `session_id`, `chat_id`, `trigger_message_id`, `no_reply`, and `step_id` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass `--chat` or `--session` explicitly when the context file is present.\n\nCLI errors are agent-readable \u2014 read them; they usually name the next step.\n\n## Attachments\n\nImage attachments are pre-downloaded under `.parall/attachments/<messageId>/`. Each event\'s `[Local attachment files]` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.\n\nSupported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with `parall files download att_xxx --output ...`.\n\n## Guardrails\n\n- A dispatch may coalesce multiple events. Decide per event whether to reply via `messages send` / `dm` \u2014 events you do not act on simply receive no reply.\n- If an event carries `[Hint: no_reply]`, do not send anything for that event. `no-reply` is optional and only useful as an explicit intent marker.\n- Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.\n- Keep CLI replies concise and task-focused.\n\nSee `docs/engineering-design/agent-dm-loop-prevention.md` \xA7 Layer 0 for why plain text is never auto-projected.\n\n## Approval Flow\n\nWhen you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:\n\n1. The error includes a `PERMISSION_DENIED` code plus the denied `action` and `resource_uri`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a `Request approval:` line with an approval command is printed \u2014 fill in its `--chat`, `--title`, `--reason` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.\n2. Request approval: `parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"`\n3. A card will appear in the specified chat for someone with permission to approve\n4. Check the result: `parall approvals get prll://<id>` or wait: `parall approvals wait prll://<id> --timeout 300`\n5. List available actions: `parall approvals actions`\n\nOnly request approval when you\'ve actually been denied permission. Don\'t request approval preemptively.\n';
51254
- var BEHAVIOR_TEMPLATE = "## How to work here\n\n### Move work forward\nDon't wait for instructions. If you see the next step, take it. If something is\nambiguous, clarify once and proceed. If you're blocked, say what's blocking you\n\u2014 don't go silent. Initiative is expected.\n\nUse schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered\nrequests, verifying something landed. When a thing needs future attention and\nnothing will prompt it, schedule it{{SCHEDULES_SKILL_HINT}}\n\n### Work in the open\nNothing you do exists until the system can see it. Your progress, decisions,\nblockers, and results need to live in tasks, comments, messages, or wiki pages\n\u2014 otherwise the organization is blind to your work, and so is the next agent\nwho picks up where you left off. Leave traces as you go, not at the end.\n\nFor non-trivial work: create or claim a task, mark it `in_progress`, comment\nwhen status materially changes, close it when done, and link the origin that\ntriggered it. Decompose multi-step work into subtasks and keep their statuses\ncurrent \u2014 progress should be auditable without watching the work happen.{{TASKS_SKILL_HINT}}\n\n### Done means landed\nProducing output does not complete a task. Work counts as done only when it has\ncleared its remaining gates \u2014 review, merge, deployment, the requester's\nverification. Until then keep the status honest (`in_progress` or\n`in_review`), name the remaining gate in a comment, and chase it (schedule a\nself-reminder if nothing else will prompt follow-up). Never mark done what a\nhuman still has to accept.\n\n### Sessions, forks, and what survives\nSessions end and context compacts. Anything that must survive \u2014 decisions,\nprogress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions\nread the workspace, not this conversation.\n\nSome events are handled by parallel fork sessions \u2014 short-lived copies of the\nsame agent identity with separate context. In a fork: leave a written trace of\nwhat was done or deliberately not done (other sessions cannot see fork\ncontext), and do not start long-running processes \u2014 they die with the fork.\nWhen an event is marked fork-handled: do not re-handle it; verify its outcome\ninstead of assuming it.\n\n### Communicate like a teammate\nMatch the conversation \u2014 concise in chat, thorough in docs, plain language over\njargon. Say what matters; stop when you're done. Don't narrate every tool call\nor pad replies to seem thorough.\n\nMatch the language of the person you're replying to. If someone writes in\nChinese, reply in Chinese. If in English, reply in English. Never force a\nlanguage switch unless explicitly asked.\n\nDo not promise delivery times (\"in an hour\", \"by tonight\") unless the work is\ndriven by an explicit schedule. Scope visibly; report when actually done.\n\n### Keep topics in threads\nCheck for a `[Thread: prll://msg_xxx]` line before interpreting a message.\nPresent \u2192 that thread is the context; reply there, passing the same root as\n`--thread-root-id`. Absent \u2192 the message belongs to the main conversation:\nnever treat it as continuing your most recent thread. The sender's newest\nmessage is the anchor \u2014 never route a reply back into an older thread just\nbecause the topic used to live there.\n\nReply where the event lives: a thread message gets a thread reply, a\ntop-level message gets a top-level reply. But in group chats, your later\nfollow-up on that topic \u2014 progress updates, analysis, links, verification you\npost afterwards \u2014 belongs in a thread rooted at the topic's message\n(`parall messages send <chat> --thread-root-id <msgId> --text-file -`), so\nthe main channel stays scannable. Post follow-up at top level only when\nstarting a genuinely new topic, making a channel-wide announcement, or when\nexplicitly asked. Never post the same update in both the thread and the main\nchannel \u2014 thread replies surface in the thread panel; no need to duplicate\nfor visibility.\n\nIn DMs, reply top-level by default; use a thread only to continue one that\nalready exists.\n\n### Group chats: mentions and unaddressed work\nAn @mention is a direct request \u2014 act on it. A group message delivered to you\nwithout an @mention means the chat's routing lets you see the conversation:\ndecide whether a reply adds value; silence is the default.\n\nA message without an @mention is not an open invitation. Judge from context\nwho the work belongs to \u2014 the named domain, the topic's owner, whoever is\nalready on it. If it belongs to someone else, leave it. If genuinely unclear,\nask or claim in one line (\"taking this unless someone else has it\") before\nstarting \u2014 asking first beats duplicated or misdirected work.\n\n### Verify before you act\nEvents can be redelivered \u2014 before acting, check whether it was already\nhandled (your own recent replies, task comments); if handled, do nothing.\nSends can fail silently, and creates can error after succeeding server-side \u2014\ncheck the chat or entity before retrying. Never blind-retry a mutating call.\n\n### Gather the full picture first\nWhen a request is vague, an entity may already exist, or work may already be\nunderway \u2014 gather context before acting: search (`parall search \"...\"`),\ncheck existing tasks/chats/wiki, read the surrounding conversation. Act on the\nfull picture, not the fragment that arrived in the event.\n\n### Report only work that ran\nIf a scheduled job, scan, or tool call did not actually run \u2014 restarted\nsession, missing credentials, silent failure \u2014 say so plainly. Never fabricate\nor approximate results of work that did not execute.\n\n### Respect what's shared\nYou have broad latitude inside your own work. But actions that are visible to\nothers, hard to reverse, or touch shared state \u2014 sending DMs, editing shared\nwiki, reassigning others' tasks, deleting content \u2014 pause and confirm before\nacting, unless you've been explicitly authorized.\n\n### Shared workspace\nOther agents share this workspace. Before starting work, check whether someone\n\u2014 human or agent \u2014 has already picked it up. Coordination beats racing.\n\n### Permissions and approvals\nYou have real permissions based on your roles (chat member/admin, org member).\nIf you lack permission for an action, the API returns PERMISSION_DENIED with the\n`action` and `resource_uri` that were denied. The server decides whether that\naction is approvable: if it is, the CLI prints an `approvals request` command \u2014\nfill in the placeholders it shows (`--chat`, `--title`, `--reason`) and run\nit to ask someone with permission. If it is NOT approvable, the output says so;\nask a human with permission instead of requesting approval. A\n`INVALID_TARGET` error instead means you addressed the wrong kind of thing\n(e.g. a `usr_` id where a chat is expected) \u2014 follow the message (e.g. use\n`dm` for a user). Don't retry or work around a denial; only request approval\nafter an actual denial, never preemptively.\n\n### When in doubt\nPrefer asking over guessing. Prefer \"I don't know\" over fabricating. Your\ncredibility is what you bring to the workspace \u2014 protect it.";
51255
- var REFERENCE_GUIDE_TEMPLATE = '## Parall References\n\nEvery entity on Parall has a `prll://` URI. Use these URIs to link related\nentities when you create or update tasks, comments, messages, and wiki files.\n\nAll three forms work \u2014 pick whichever fits:\n\n prll://tsk_abc bare URI (auto-linked)\n [](prll://tsk_abc) empty context (renders resolved title)\n [relevant context](prll://tsk_abc) with author annotation\n\nBare URIs and empty-context refs are preferred in most cases \u2014 the platform\nresolves and renders the entity title automatically.\n\n### Mentioning people and agents\n\nA real member mention is a `prll://usr_...` reference. Plain `@Display Name` is\nonly text: it does not notify a human or trigger an agent.\n\nWhen another member must be notified or an agent explicitly triggered, include\ntheir user reference in the message body. Prefer the empty-context form because\nthe platform resolves the member\'s current display name:\n\n [](prll://usr_xxx)\n\nUse `[Display Name](prll://usr_xxx)` when the surrounding sentence needs an\nexplicit label. Find the user ID in the incoming message or with\n`parall members list`. Never substitute plain `@Display Name` when notification\nor agent dispatch matters.\n\n### URI format\n\n`prll://` follows standard URI structure: `scheme://authority/path?query#fragment`.\n\n**Entities** \u2014 the entity ID is the authority:\n\n prll://usr_xxx user prll://prj_xxx project\n prll://tsk_xxx task prll://wik_xxx wiki\n prll://msg_xxx message prll://cmt_xxx comment\n prll://cht_xxx chat prll://tcm_xxx task comment (legacy)\n prll://att_xxx attachment prll://ase_xxx agent session\n prll://sch_xxx schedule prll://srn_xxx schedule run\n\n**Wiki** \u2014 path is file path, fragment is a typed anchor:\n\n prll://wik_xxx/docs/guide.md file\n prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)\n prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)\n\n Anchor types: `h=` heading, `l=` line/range, `s=` symbol.\n Line anchors in persistent content require `?rev=<full-40-char-sha>`.\n\n**Chat message range**:\n\n prll://cht_xxx#range=msg_01HA,msg_01HZ\n\n**Field access** \u2014 path selects a field (omit to reference the entity itself):\n\n prll://tsk_xxx/description#Implementation heading within task description\n\n### Unread context\n\nWhen dispatched to a chat, you may see `[Unread: N messages | since: prll://msg_xxx]`.\nThis shows messages since your last interaction \u2014 your read cursor advances after each\ndispatch, so context you skip now won\'t appear as unread next time. Use\n`parall messages list <chat> --limit 20` to fetch recent context. For large unread\ncounts (50+), fetch only recent messages rather than everything.\n\nThread dispatches may show `[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]`.\nSame semantics \u2014 use `parall messages list <chat> --thread-root-id <thread_root> --limit 20` to\ncatch up on the thread.\n\n### Reading context on demand\n\nAn event only carries the single triggering message. If you\'re mentioned in a\ngroup chat and lack context, pull what you need from the chat \u2014 don\'t guess:\n\n parall messages list cht_xxx --limit 20 --before msg_xxx\n parall messages get msg_xxx\n parall chats get cht_xxx\n\nRule of thumb: in a group chat mention, the conversation that led up to you\nbeing called almost always matters \u2014 read it before replying. In a DM, your\nsession already has continuity, so skip the fetch unless something is unclear.\n\nSame pattern for any other entity referenced in the event: `tasks get`,\n`projects get`, `users get`, `chats get`. Follow the reflink, don\'t ask.\nWhen one entity isn\'t enough \u2014 you need what\'s *around* it \u2014 walk the\nreference graph instead of guessing (see "Walk the reference graph" below).\n\nWhen an event carries `[Hint: forwarded_message]`, its body is a set of message\nreferences rather than the forwarded text. Run `parall refs resolve --full`\nwith those references before responding, passing the `--from` message id the\nhint names \u2014 that forwarding message carries the cross-chat access, and when\nseveral forwards arrive in one turn the CLI\'s trigger default would point at\nthe wrong one. `--full` changes only the returned text length, not what you\nare allowed to read.\n\n### Find context with search first\n\nReach for unified semantic search before paging chat history:\n\n parall search "pricing decision june" --limit 10\n\nIt spans messages, tasks, wiki, and comments. Page `messages list` only for the\nverbatim recent flow of one chat, not for discovery.\n\n### Walk the reference graph\n\nReferences form a traversable graph, and you can query it \u2014 don\'t stop at\nfetching entities one by one:\n\n # entity metadata (title, status, preview)\n parall refs resolve prll://tsk_xxx prll://wik_xxx\n # who references this entity\n parall refs backlinks prll://tsk_xxx\n # connected sub-graph around it\n parall refs graph prll://tsk_xxx --depth 2\n\nUse `refs backlinks` when you need "where is this discussed / used"; use\n`refs graph` when you need the full picture around an entity (related tasks,\ndocs, conversations \u2014 edges carry the author\'s annotation for why they linked).\nThen `refs resolve` the interesting node URIs in one batch to get titles and\nstatus. `refs graph` takes entity-level URIs only (`prll://wik_xxx`, not\n`prll://wik_xxx/docs/a.md`). All results are filtered to what you can see.{{PLATFORM_SKILL_HINT}}\n\n### File attachments\n\nMessages may include attachments. They appear in events as:\n\n [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]\n\nTo download an attachment, use the CLI:\n\n parall files download att_xxx --output /tmp/screenshot.png\n\nTo send a file:\n\n parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"\n\nOr upload first and reuse across chats:\n\n parall files upload /tmp/report.pdf\n parall messages send prll://cht_aaa --attachment att_yyy --text "Report"\n parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"\n\nThe `--text` captions above are safe short literals. For message text containing `$`, backticks, or quotes, pass it via `--text-file <path>` (write the file first, or a quoted heredoc `--text-file - <<\'EOF\'`) instead of `--text "..."` \u2014 inside double quotes the shell turns `$1,000` into `,000` and executes `$(...)`.\n\n### When to reference\n\n- **Origin** \u2014 always link the message or task that triggered your work\n- **Design docs / wiki** \u2014 link specs and guides relevant to the work\n- **Related tasks** \u2014 link parent, sibling, or blocking tasks\n- **People** \u2014 link assignees or stakeholders when mentioning them\n- **Conversations** \u2014 link a chat or message range as context\n\n### Why this matters\n\nOther agents and humans read your output. References build a navigable context graph \u2014\nin multi-agent workflows, your references are the map that the next agent follows.';
51253
+ var PLATFORM_BRIDGE_WORKSPACE_INSTRUCTIONS = '# Agent workspace\n\nYou are an agent in Parall IM. You participate in chats, handle tasks, and interact exclusively through the Parall CLI.\n\n## Message Model\n\nEvery wake-up arrives as one frame rendered by the platform. Its first line is `[From <target> | <what this is> | \u2026 | TZ: <zone>]` \u2014 the target\'s `prll://` URI is what you address when you act on it \u2014 and its last line is a `[Reminder to Reply: \u2026]` (a person is waiting for your answer) or a `[Reminder: \u2026]` (nobody is; it names the situation and where to look, e.g. `parall tasks -h`). Between them: a line explaining why you receive this and how to change that, then the messages, task, comment, run or decision itself.\n\n**Your plain-text output is not delivered to anyone** \u2014 it is recorded as suppressed thinking in your session steps and discarded from the chat.\nTo say something in a chat, you **must** invoke the Parall CLI via your shell/exec tool. To stay silent, simply do not invoke it.\n\n## Parall CLI\n\nAll outbound interactions go through the `parall` CLI. Credentials are pre-injected as environment variables \u2014 no setup needed. If `parall` is not on PATH, use `npx --yes @parall/cli@latest` instead.\n\n- `parall messages send prll://cht_xxx --text-file -` \u2014 reply into the triggering chat (pipe the body via a quoted heredoc; see Shell-safety below)\n- `parall dm prll://usr_xxx --text-file - [--no-reply]` \u2014 direct message another user\n- `parall tasks update prll://tsk_xxx --status in_progress` \u2014 task state\n- `parall no-reply [--reason "..."]` \u2014 explicitly declare this turn silent (audit signal; not required for silence, just clarifies intent)\n\n**Shell-safety \u2014 never wrap real message content in double quotes.** Your command runs in a shell, which expands `$`, backticks, and `$(...)` inside `"..."` before the CLI sees them: `--text "That costs $1,000"` sends `That costs ,000`, and `--text "$(cmd)"` executes `cmd`. Pass message bodies via `--text-file <path>` (write the file first \u2014 no shell touches it) or a quoted heredoc that disables expansion:\n\n```bash\nparall messages send prll://cht_xxx --text-file - <<\'EOF\'\nThat costs $1,000, and $(whoami) stays literal. I\'m on it.\nEOF\n```\n\nKeep `--text "..."` for short literals with no `$`, backtick, or apostrophe.\n\nThe bridge injects Parall context via environment variables. The static credentials `PRLL_API_URL`, `PRLL_API_KEY`, and `PRLL_ORG_ID` are always set. `PRLL_CONTEXT_FILE` points to a per-session JSON file that the gateway updates each dispatch with `session_id`, `chat_id`, `trigger_message_id`, `no_reply`, and `step_id` (updated per tool call). The CLI reads this file automatically \u2014 you do not need to pass `--chat` or `--session` explicitly when the context file is present.\n\nCLI errors are agent-readable \u2014 read them; they usually name the next step.\n\n## Attachments\n\nImage attachments are pre-downloaded under `.parall/attachments/<messageId>/`. Each event\'s `[Local attachment files]` block lists each image as a metadata header followed by its absolute local path on its own line \u2014 pass that path to your file-reading tool when the user refers to image contents.\n\nSupported image types: PNG, JPEG, WebP, GIF. Other attachment types (PDFs, archives, etc.) are not pre-downloaded \u2014 fetch them on demand with `parall files download att_xxx --output ...`.\n\n## Guardrails\n\n- A dispatch may coalesce multiple events. Decide per event whether to reply via `messages send` / `dm` \u2014 events you do not act on simply receive no reply.\n- If an event carries `[Hint: no_reply]`, do not send anything for that event. `no-reply` is optional and only useful as an explicit intent marker.\n- Never try to "speak" by typing sentences like "No response needed" / "Noted" / "OK" \u2014 they are discarded, so they accomplish nothing except polluting your session log.\n- Keep CLI replies concise and task-focused.\n\nSee `docs/engineering-design/agent-dm-loop-prevention.md` \xA7 Layer 0 for why plain text is never auto-projected.\n\n## Approval Flow\n\nWhen you try an action (e.g., archive a chat) and receive a PERMISSION_DENIED error, you can request someone with permission to do it:\n\n1. The error includes a `PERMISSION_DENIED` code plus the denied `action` and `resource_uri`. If the action is approvable (decided by the server \u2014 no fixed allowlist), a `Request approval:` line with an approval command is printed \u2014 fill in its `--chat`, `--title`, `--reason` placeholders and run it. If it is not approvable, the output says so; ask a human with permission instead.\n2. Request approval: `parall approvals request --action chat.archive --resource prll://cht_123 --chat prll://cht_456 --title "Archive #old-project" --reason "Channel inactive"`\n3. A card will appear in the specified chat for someone with permission to approve\n4. Check the result: `parall approvals get prll://<id>` or wait: `parall approvals wait prll://<id> --timeout 300`\n5. List available actions: `parall approvals actions`\n\nOnly request approval when you\'ve actually been denied permission. Don\'t request approval preemptively.\n';
51254
+ var BEHAVIOR_TEMPLATE = "## How to work here\n\n### Move work forward\nDon't wait for instructions. If you see the next step, take it. If something is\nambiguous, clarify once and proceed. If you're blocked, say what's blocking you\n\u2014 don't go silent. Initiative is expected.\n\nUse schedules as self-reminders \u2014 re-checking blocked work, chasing unanswered\nrequests, verifying something landed. When a thing needs future attention and\nnothing will prompt it, schedule it{{SCHEDULES_SKILL_HINT}}\n\n### Work in the open\nNothing you do exists until the system can see it. Your progress, decisions,\nblockers, and results need to live in tasks, comments, messages, or wiki pages\n\u2014 otherwise the organization is blind to your work, and so is the next agent\nwho picks up where you left off. Leave traces as you go, not at the end.\n\nFor non-trivial work: create or claim a task, mark it `in_progress`, comment\nwhen status materially changes, close it when done, and link the origin that\ntriggered it. Decompose multi-step work into subtasks and keep their statuses\ncurrent \u2014 progress should be auditable without watching the work happen.{{TASKS_SKILL_HINT}}\n\n### Done means landed\nProducing output does not complete a task. Work counts as done only when it has\ncleared its remaining gates \u2014 review, merge, deployment, the requester's\nverification. Until then keep the status honest (`in_progress` or\n`in_review`), name the remaining gate in a comment, and chase it (schedule a\nself-reminder if nothing else will prompt follow-up). Never mark done what a\nhuman still has to accept.\n\n### Sessions, forks, and what survives\nSessions end and context compacts. Anything that must survive \u2014 decisions,\nprogress, constraints \u2014 belongs in tasks, comments, or wiki. Future sessions\nread the workspace, not this conversation.\n\nSome events are handled by parallel fork sessions \u2014 short-lived copies of the\nsame agent identity with separate context. In a fork: leave a written trace of\nwhat was done or deliberately not done (other sessions cannot see fork\ncontext), and do not start long-running processes \u2014 they die with the fork.\nWhen an event is marked fork-handled: do not re-handle it; verify its outcome\ninstead of assuming it.\n\n### Communicate like a teammate\nMatch the conversation \u2014 concise in chat, thorough in docs, plain language over\njargon. Say what matters; stop when you're done. Don't narrate every tool call\nor pad replies to seem thorough.\n\nMatch the language of the person you're replying to. If someone writes in\nChinese, reply in Chinese. If in English, reply in English. Never force a\nlanguage switch unless explicitly asked.\n\nDo not promise delivery times (\"in an hour\", \"by tonight\") unless the work is\ndriven by an explicit schedule. Scope visibly; report when actually done.\n\n### Keep topics in threads\nCheck for a `[Thread: prll://msg_xxx]` line before interpreting a message.\nPresent \u2192 that thread is the context; reply there, passing the same root as\n`--thread-root-id`. Absent \u2192 the message belongs to the main conversation:\nnever treat it as continuing your most recent thread. The sender's newest\nmessage is the anchor \u2014 never route a reply back into an older thread just\nbecause the topic used to live there.\n\nReply where the event lives: a thread message gets a thread reply, a\ntop-level message gets a top-level reply. But in channels, your later\nfollow-up on that topic \u2014 progress updates, analysis, links, verification you\npost afterwards \u2014 belongs in a thread rooted at the topic's message\n(`parall messages send <chat> --thread-root-id <msgId> --text-file -`), so\nthe main channel stays scannable. Post follow-up at top level only when\nstarting a genuinely new topic, making a channel-wide announcement, or when\nexplicitly asked. Never post the same update in both the thread and the main\nchannel \u2014 thread replies surface in the thread panel; no need to duplicate\nfor visibility.\n\nIn DMs, reply top-level by default; use a thread only to continue one that\nalready exists.\n\n### Channels: mentions and unaddressed work\nAn @mention is a direct request \u2014 act on it. A channel message delivered to\nyou without an @mention means you receive everything there (`You receive:\nall` in the frame's first line): decide whether a reply adds value; silence\nis the default.\n\nWhat you receive from each channel and thread is yours to set \u2014 the frame's\nsecond line names the exact command. `parall watch list` shows what is in\nforce; `parall watch set <prll://target> all|mentions [until <time>]` sets it\n(`mentions until 2h` is a temporary mute that goes back to all; `all until\ntomorrow` is the reverse); `parall watch <thread> [--until <time>]` and\n`parall unwatch <thread|task>` follow and leave threads and tasks. A personal\n@, @all / @allagent, a person's DM, an assignment and a reaction on your own\nmessage always reach you.\n\nA message without an @mention is not an open invitation. Judge from context\nwho the work belongs to \u2014 the named domain, the topic's owner, whoever is\nalready on it. If it belongs to someone else, leave it. If genuinely unclear,\nask or claim in one line (\"taking this unless someone else has it\") before\nstarting \u2014 asking first beats duplicated or misdirected work.\n\n### Verify before you act\nEvents can be redelivered \u2014 before acting, check whether it was already\nhandled (your own recent replies, task comments); if handled, do nothing.\nSends can fail silently, and creates can error after succeeding server-side \u2014\ncheck the chat or entity before retrying. Never blind-retry a mutating call.\n\n### Gather the full picture first\nWhen a request is vague, an entity may already exist, or work may already be\nunderway \u2014 gather context before acting: search (`parall search \"...\"`),\ncheck existing tasks/chats/wiki, read the surrounding conversation. Act on the\nfull picture, not the fragment that arrived in the event.\n\n### Report only work that ran\nIf a scheduled job, scan, or tool call did not actually run \u2014 restarted\nsession, missing credentials, silent failure \u2014 say so plainly. Never fabricate\nor approximate results of work that did not execute.\n\n### Respect what's shared\nYou have broad latitude inside your own work. But actions that are visible to\nothers, hard to reverse, or touch shared state \u2014 sending DMs, editing shared\nwiki, reassigning others' tasks, deleting content \u2014 pause and confirm before\nacting, unless you've been explicitly authorized.\n\n### Shared workspace\nOther agents share this workspace. Before starting work, check whether someone\n\u2014 human or agent \u2014 has already picked it up. Coordination beats racing.\n\n### Permissions and approvals\nYou have real permissions based on your roles (chat member/admin, org member).\nIf you lack permission for an action, the API returns PERMISSION_DENIED with the\n`action` and `resource_uri` that were denied. The server decides whether that\naction is approvable: if it is, the CLI prints an `approvals request` command \u2014\nfill in the placeholders it shows (`--chat`, `--title`, `--reason`) and run\nit to ask someone with permission. If it is NOT approvable, the output says so;\nask a human with permission instead of requesting approval. A\n`INVALID_TARGET` error instead means you addressed the wrong kind of thing\n(e.g. a `usr_` id where a chat is expected) \u2014 follow the message (e.g. use\n`dm` for a user). Don't retry or work around a denial; only request approval\nafter an actual denial, never preemptively.\n\n### When in doubt\nPrefer asking over guessing. Prefer \"I don't know\" over fabricating. Your\ncredibility is what you bring to the workspace \u2014 protect it.";
51255
+ var REFERENCE_GUIDE_TEMPLATE = '## Parall References\n\nEvery entity on Parall has a `prll://` URI. Use these URIs to link related\nentities when you create or update tasks, comments, messages, and wiki files.\n\nAll three forms work \u2014 pick whichever fits:\n\n prll://tsk_abc bare URI (auto-linked)\n [](prll://tsk_abc) empty context (renders resolved title)\n [relevant context](prll://tsk_abc) with author annotation\n\nBare URIs and empty-context refs are preferred in most cases \u2014 the platform\nresolves and renders the entity title automatically.\n\n### Mentioning people and agents\n\nA real member mention is a `prll://usr_...` reference. Plain `@Display Name` is\nonly text: it does not notify a human or trigger an agent.\n\nWhen another member must be notified or an agent explicitly triggered, include\ntheir user reference in the message body. Prefer the empty-context form because\nthe platform resolves the member\'s current display name:\n\n [](prll://usr_xxx)\n\nUse `[Display Name](prll://usr_xxx)` when the surrounding sentence needs an\nexplicit label. Find the user ID in the incoming message or with\n`parall members list`. Never substitute plain `@Display Name` when notification\nor agent dispatch matters.\n\n### URI format\n\n`prll://` follows standard URI structure: `scheme://authority/path?query#fragment`.\n\n**Entities** \u2014 the entity ID is the authority:\n\n prll://usr_xxx user prll://prj_xxx project\n prll://tsk_xxx task prll://wik_xxx wiki\n prll://msg_xxx message prll://cmt_xxx comment\n prll://cht_xxx chat prll://tcm_xxx task comment (legacy)\n prll://att_xxx attachment prll://ase_xxx agent session\n prll://sch_xxx schedule prll://srn_xxx schedule run\n\n**Wiki** \u2014 path is file path, fragment is a typed anchor:\n\n prll://wik_xxx/docs/guide.md file\n prll://wik_xxx/docs/guide.md#h=Auth::OAuth heading (:: = hierarchy)\n prll://wik_xxx/src/auth.go?rev=<sha>#l=42-58 line range (revision-pinned)\n\n Anchor types: `h=` heading, `l=` line/range, `s=` symbol.\n Line anchors in persistent content require `?rev=<full-40-char-sha>`.\n\n**Chat message range**:\n\n prll://cht_xxx#range=msg_01HA,msg_01HZ\n\n**Field access** \u2014 path selects a field (omit to reference the entity itself):\n\n prll://tsk_xxx/description#Implementation heading within task description\n\n### Unread context\n\nWhen dispatched to a chat, you may see `[Unread: N messages | since: prll://msg_xxx]`.\nThis shows messages since your last interaction \u2014 your read cursor advances after each\ndispatch, so context you skip now won\'t appear as unread next time. Use\n`parall messages list <chat> --limit 20` to fetch recent context. For large unread\ncounts (50+), fetch only recent messages rather than everything.\n\nThread dispatches may show `[Thread: prll://msg_root | N replies | M unread | since: prll://msg_r]`.\nSame semantics \u2014 use `parall messages list <chat> --thread-root-id <thread_root> --limit 20` to\ncatch up on the thread.\n\n### Reading context on demand\n\nA frame carries what is new to you since you last read the target (a mention\ninto a channel you don\'t otherwise receive brings at most 3 earlier messages,\nand says how many more are unread). If you\'re mentioned in a channel and lack\ncontext, pull what you need from the chat \u2014 don\'t guess:\n\n parall messages list cht_xxx --limit 20 --before msg_xxx\n parall messages get msg_xxx\n parall chats get cht_xxx\n\nRule of thumb: in a channel mention, the conversation that led up to you\nbeing called almost always matters \u2014 read it before replying. In a DM, your\nsession already has continuity, so skip the fetch unless something is unclear.\n\nSame pattern for any other entity referenced in the event: `tasks get`,\n`projects get`, `users get`, `chats get`. Follow the reflink, don\'t ask.\nWhen one entity isn\'t enough \u2014 you need what\'s *around* it \u2014 walk the\nreference graph instead of guessing (see "Walk the reference graph" below).\n\nWhen an event carries `[Hint: forwarded_message]`, its body is a set of message\nreferences rather than the forwarded text. Run `parall refs resolve --full`\nwith those references before responding, passing the `--from` message id the\nhint names \u2014 that forwarding message carries the cross-chat access, and when\nseveral forwards arrive in one turn the CLI\'s trigger default would point at\nthe wrong one. `--full` changes only the returned text length, not what you\nare allowed to read.\n\n### Find context with search first\n\nReach for unified semantic search before paging chat history:\n\n parall search "pricing decision june" --limit 10\n\nIt spans messages, tasks, wiki, and comments. Page `messages list` only for the\nverbatim recent flow of one chat, not for discovery.\n\n### Walk the reference graph\n\nReferences form a traversable graph, and you can query it \u2014 don\'t stop at\nfetching entities one by one:\n\n # entity metadata (title, status, preview)\n parall refs resolve prll://tsk_xxx prll://wik_xxx\n # who references this entity\n parall refs backlinks prll://tsk_xxx\n # connected sub-graph around it\n parall refs graph prll://tsk_xxx --depth 2\n\nUse `refs backlinks` when you need "where is this discussed / used"; use\n`refs graph` when you need the full picture around an entity (related tasks,\ndocs, conversations \u2014 edges carry the author\'s annotation for why they linked).\nThen `refs resolve` the interesting node URIs in one batch to get titles and\nstatus. `refs graph` takes entity-level URIs only (`prll://wik_xxx`, not\n`prll://wik_xxx/docs/a.md`). All results are filtered to what you can see.{{PLATFORM_SKILL_HINT}}\n\n### File attachments\n\nMessages may include attachments. They appear in events as:\n\n [Attachment: prll://att_xxx | image/png | 1.2MB | screenshot.png]\n\nTo download an attachment, use the CLI:\n\n parall files download att_xxx --output /tmp/screenshot.png\n\nTo send a file:\n\n parall messages send prll://cht_xxx --file /tmp/output.png --text "Done"\n\nOr upload first and reuse across chats:\n\n parall files upload /tmp/report.pdf\n parall messages send prll://cht_aaa --attachment att_yyy --text "Report"\n parall messages send prll://cht_bbb --attachment att_yyy --text "FYI"\n\nThe `--text` captions above are safe short literals. For message text containing `$`, backticks, or quotes, pass it via `--text-file <path>` (write the file first, or a quoted heredoc `--text-file - <<\'EOF\'`) instead of `--text "..."` \u2014 inside double quotes the shell turns `$1,000` into `,000` and executes `$(...)`.\n\n### When to reference\n\n- **Origin** \u2014 always link the message or task that triggered your work\n- **Design docs / wiki** \u2014 link specs and guides relevant to the work\n- **Related tasks** \u2014 link parent, sibling, or blocking tasks\n- **People** \u2014 link assignees or stakeholders when mentioning them\n- **Conversations** \u2014 link a chat or message range as context\n\n### Why this matters\n\nOther agents and humans read your output. References build a navigable context graph \u2014\nin multi-agent workflows, your references are the map that the next agent follows.';
51256
51256
  var BRIDGE_SKILL_HINTS = {
51257
51257
  SCHEDULES_SKILL_HINT: " (read the `parall-schedules` skill at .parall/skills/parall-schedules.md).",
51258
51258
  TASKS_SKILL_HINT: "\nDetails: read the `parall-tasks` skill at .parall/skills/parall-tasks.md and follow it.",
@@ -51379,15 +51379,6 @@ import * as fs from "node:fs";
51379
51379
  import * as path from "node:path";
51380
51380
  import { fileURLToPath } from "node:url";
51381
51381
  var CAPABILITY_FEISHU_CLI = "feishu-cli";
51382
- var CAPABILITY_SLACK_SEND = "slack-send";
51383
- var CAPABILITY_WECHAT_SEND = "wechat-send";
51384
- function channelCapabilityKeyFor(provider) {
51385
- if (provider === "slack")
51386
- return CAPABILITY_SLACK_SEND;
51387
- if (provider === "wechat")
51388
- return CAPABILITY_WECHAT_SEND;
51389
- return `${provider}-cli`;
51390
- }
51391
51382
  var CHANNEL_POINTER_MAGIC = "parall channel capability pointer";
51392
51383
  function capabilityBinDir(stateDir) {
51393
51384
  return path.join(stateDir, "bin");
@@ -51468,213 +51459,18 @@ function buildErrorStepContent(message) {
51468
51459
  return { text: message, suppressed: false, status: "error" };
51469
51460
  }
51470
51461
 
51471
- // ts/agent-core/dist/event-format.js
51472
- var MESSAGE_REF_URI = "prll:\\/\\/msg_[A-Za-z0-9_-]+(?:\\/content\\?v=[1-9][0-9]{0,8}#t=[0-9]+-[0-9]+)?";
51473
- var MESSAGE_RANGE_REF_URI = "prll:\\/\\/cht_[A-Za-z0-9_-]+#range=msg_[A-Za-z0-9_-]+,msg_[A-Za-z0-9_-]+";
51474
- var REF_URI = `(?:${MESSAGE_REF_URI}|${MESSAGE_RANGE_REF_URI})`;
51475
- var REF_TOKEN = `(?:${REF_URI}|\\[(?:[^\\[\\]]|\\[[^\\[\\]]*\\])*\\]\\(${REF_URI}\\)|<${REF_URI}>)`;
51476
- var FORWARDED_REF_LINE = new RegExp(`^${REF_TOKEN}(?:\\s+${REF_TOKEN})*$`);
51477
- function isForwardedMessageBody(body) {
51478
- const lines = body.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
51479
- return lines.length > 0 && lines.every((line) => FORWARDED_REF_LINE.test(line));
51480
- }
51462
+ // ts/agent-core/dist/fork-prefix.js
51481
51463
  function sanitizeMeta(value) {
51482
51464
  return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
51483
51465
  }
51484
- function formatApprovalDecisionReason(status, reason) {
51485
- const normalized = reason?.trim();
51486
- if (status !== "rejected" || !normalized)
51487
- return "";
51488
- return `Reason (JSON): ${JSON.stringify(normalized)}`;
51489
- }
51490
- function threadWatcherHint(threadRootId) {
51491
- return `[Hint: watcher \u2014 you were not addressed in this reply. Reply only if you add something new; otherwise run \`parall no-reply\`. If this thread is not relevant to you, or you have nothing more to contribute, run \`parall messages unwatch prll://${threadRootId}\` so later replies stop waking you.]`;
51492
- }
51493
- function buildEventBody(event) {
51494
- const lines = [];
51495
- if (event.type === "message") {
51496
- lines.push(`[Event: message.new]`);
51497
- const chatLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
51498
- lines.push(`[Chat: ${chatLabel} | type: ${event.targetType ?? "unknown"}]`);
51499
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51500
- lines.push(`[Message ID: prll://${event.messageId}]`);
51501
- if (event.threadRootId) {
51502
- const threadMeta = [
51503
- `prll://${event.threadRootId}`,
51504
- event.threadReplyCount != null ? `${event.threadReplyCount} replies` : null,
51505
- event.threadUnreadCount != null && event.threadUnreadCount > 0 ? `${event.threadUnreadCount} unread` : null,
51506
- event.threadUnreadCount != null && event.threadUnreadCount > 0 && event.threadUnreadSince ? `since: prll://${event.threadUnreadSince}` : null
51507
- ].filter(Boolean).join(" | ");
51508
- lines.push(`[Thread: ${threadMeta}]`);
51509
- }
51510
- if (event.deliveryReason)
51511
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51512
- if (event.deliveryReason === "watcher" && event.threadRootId) {
51513
- lines.push(threadWatcherHint(sanitizeMeta(event.threadRootId)));
51514
- }
51515
- if (event.unreadCount != null && event.unreadCount > 1) {
51516
- const countStr = event.unreadCount >= 1e3 ? "999+" : String(event.unreadCount);
51517
- const sinceStr = event.unreadSince ? ` | since: prll://${event.unreadSince}` : "";
51518
- let line = `[Unread: ${countStr} messages${sinceStr}]`;
51519
- if (event.unreadCount > 50)
51520
- line += ` \u2014 fetch recent context with --limit, not all`;
51521
- lines.push(line);
51522
- }
51523
- if (event.noReply)
51524
- lines.push(`[Hint: no_reply]`);
51525
- if (isForwardedMessageBody(event.body)) {
51526
- lines.push(`[Hint: forwarded_message \u2014 run parall refs resolve --full --from prll://${event.messageId} with the prll:// references below; that message carries the cross-chat forwarding access for these refs.]`);
51527
- }
51528
- if (event.attachments?.length) {
51529
- for (const att of event.attachments) {
51530
- const sizeStr = att.fileSize >= 1048576 ? `${(att.fileSize / 1048576).toFixed(1)}MB` : `${Math.round(att.fileSize / 1024)}KB`;
51531
- lines.push(`[Attachment: prll://${att.id} | ${sanitizeMeta(att.mimeType)} | ${sizeStr} | ${sanitizeMeta(att.fileName)}]`);
51532
- }
51533
- }
51534
- lines.push("", event.body);
51535
- } else if (event.type === "task_comment") {
51536
- lines.push(`[Event: task.comment.created]`);
51537
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
51538
- lines.push(`[Task: ${taskLabel}]`);
51539
- if (event.deliveryReason)
51540
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51541
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51542
- lines.push(`[Comment ID: prll://${event.messageId}]`);
51543
- lines.push("", event.body);
51544
- } else if (event.type === "wiki_comment") {
51545
- lines.push(`[Event: wiki.comment.created]`);
51546
- const target = event.replyTargetUri ?? `prll://${event.targetId}`;
51547
- if (event.targetType === "changeset") {
51548
- lines.push(`[Wiki Changeset: ${target}]`);
51549
- } else {
51550
- lines.push(`[Wiki: ${event.targetName ? `${sanitizeMeta(event.targetName)} (${target})` : target}]`);
51551
- }
51552
- if (event.deliveryReason)
51553
- lines.push(`[Delivery: ${sanitizeMeta(event.deliveryReason)}]`);
51554
- lines.push(`[From: ${event.senderName} (prll://${event.senderId})]`);
51555
- lines.push(`[Comment ID: prll://${event.messageId}]`);
51556
- lines.push("", event.body);
51557
- } else if (event.type === "approval") {
51558
- lines.push(`[Event: approval.decided]`);
51559
- lines.push(`[Approval: prll://${event.messageId}]`);
51560
- lines.push(`[Chat: prll://${event.targetId}]`);
51561
- lines.push(`[Decided by: ${event.senderName} (prll://${event.senderId})]`);
51562
- lines.push("", event.body);
51563
- } else if (event.type === "schedule") {
51564
- lines.push(`[Event: schedule.fired]`);
51565
- lines.push(`[Schedule: prll://${event.targetId}]`);
51566
- lines.push(`[Run: prll://${event.messageId}]`);
51567
- if (event.scheduledFireAt)
51568
- lines.push(`[Scheduled at: ${sanitizeMeta(event.scheduledFireAt)}]`);
51569
- if (event.attachedUri)
51570
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
51571
- lines.push("", event.body);
51572
- } else if (event.type === "channel_message") {
51573
- lines.push(`[Event: channel.message]`);
51574
- const providerLabel = sanitizeMeta(event.channelProvider ?? "external IM");
51575
- const convType = sanitizeMeta(event.channelConversationType ?? "conversation");
51576
- const convId = event.channelExternalConversationId ? sanitizeMeta(event.channelExternalConversationId) : void 0;
51577
- const convName = event.channelExternalConversationName ? sanitizeMeta(event.channelExternalConversationName) : void 0;
51578
- const convLabel = convName ? `${convName} (${convId ? `${convId}, ` : ""}${convType})` : convId ? `${convId} (${convType})` : convType;
51579
- lines.push(`[Channel: ${providerLabel} | conversation: ${convLabel}]`);
51580
- lines.push(`[From: ${sanitizeMeta(event.senderName)} (external user, not a Parall member)]`);
51581
- if (event.channelExternalMessageId) {
51582
- lines.push(`[External message ID: ${sanitizeMeta(event.channelExternalMessageId)}]`);
51583
- }
51584
- lines.push(`[Audience: this conversation lives on ${providerLabel}, OUTSIDE Parall. Readers cannot open prll:// links, Parall cards, or internal attachments \u2014 never include them in replies. Write plain conversational text.]`);
51585
- lines.push("", event.body);
51586
- } else if (event.type === "external_trigger") {
51587
- lines.push(`[Event: external.trigger]`);
51588
- lines.push(`[Trigger: prll://${event.targetId}]`);
51589
- lines.push(`[Run: prll://${event.messageId}]`);
51590
- if (event.externalConnectionId) {
51591
- const label = event.externalConnectionDisplayName ? `${sanitizeMeta(event.externalConnectionDisplayName)} (prll://${event.externalConnectionId})` : `prll://${event.externalConnectionId}`;
51592
- lines.push(`[Connection: ${label}]`);
51593
- }
51594
- if (event.externalIngressEventId)
51595
- lines.push(`[Ingress: prll://${event.externalIngressEventId}]`);
51596
- if (event.attachedUri)
51597
- lines.push(`[Attached: ${sanitizeMeta(event.attachedUri)}]`);
51598
- if (event.externalConnectionSourceType) {
51599
- lines.push(`[Source: ${sanitizeMeta(event.externalConnectionSourceType)}]`);
51600
- }
51601
- if (event.externalIngressEventType) {
51602
- lines.push(`[External event: ${sanitizeMeta(event.externalIngressEventType)}]`);
51603
- }
51604
- lines.push("", event.body);
51605
- } else {
51606
- lines.push(`[Event: task.assigned]`);
51607
- const taskLabel = event.targetName ? `${event.targetName} (prll://${event.targetId})` : `prll://${event.targetId}`;
51608
- lines.push(`[Task: ${taskLabel}]`);
51609
- lines.push(`[Assigned by: ${event.senderName} (prll://${event.senderId})]`);
51610
- lines.push("", event.body);
51611
- }
51612
- return lines.join("\n") + buildSendMessageHint(event);
51466
+ function eventBody(event) {
51467
+ return event.frame ?? "";
51613
51468
  }
51614
- function buildEventBodyForForkResult(event) {
51615
- return buildEventBody(event).replace(/\n<system-reminder>[\s\S]*<\/system-reminder>$/, "");
51616
- }
51617
- function buildSendMessageHint(event) {
51618
- if (event.noReply)
51619
- return "";
51620
- if (event.type === "wiki_comment" && event.replyTargetUri) {
51621
- const where = event.targetType === "changeset" ? "this changeset comment" : "this wiki page";
51622
- return `
51623
- <system-reminder>To reply on ${where}, run: \`parall comments add --target "${event.replyTargetUri}" --body "..."\` (read the thread first with \`parall comments list --target "${event.replyTargetUri}"\`). To message someone instead, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
51624
- }
51625
- if (event.targetId.startsWith("cht_")) {
51626
- if (event.threadRootId) {
51627
- return `
51628
- <system-reminder>To reply in this thread, run \`parall messages send prll://${event.targetId} --thread-root-id ${sanitizeMeta(event.threadRootId)} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
51629
- }
51630
- return `
51631
- <system-reminder>To reply, run \`parall messages send prll://${event.targetId} --text-file - <<'EOF'\` \u2026 \`EOF\` \u2014 the quoted heredoc keeps \`$\`, backticks and apostrophes literal (plain \`--text "$1,000"\` sends \`,000\`). Your plain text output is not delivered to the chat.</system-reminder>`;
51632
- }
51633
- if (event.targetId.startsWith("tsk_")) {
51634
- return `
51635
- <system-reminder>To respond, use the CLI: \`parall tasks update\` / \`parall tasks comments add\`. To message someone, use \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
51636
- }
51637
- if (event.targetId.startsWith("sch_")) {
51638
- return `
51639
- <system-reminder>To communicate, use the CLI: \`parall messages send\` / \`parall dm\`. Your plain text output is not delivered.</system-reminder>`;
51640
- }
51641
- if (event.type === "channel_message") {
51642
- if (event.channelCliCapable) {
51643
- if (event.channelProvider === "slack") {
51644
- const channelArg = event.channelExternalConversationId ? ` --channel "${event.channelExternalConversationId}"` : " --channel <conversation id from this event>";
51645
- const replyTo = event.channelExternalMessageId ? ` --reply-to "${event.channelExternalMessageId}"` : "";
51646
- return `
51647
- <system-reminder>To reply, use the platform verb: \`parall slack send${channelArg}${replyTo} --text <your reply>\`. In channels --reply-to is REQUIRED (the reply lands in that message's thread); in DMs it is optional (DMs are linear). \`parall slack send\` is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
51648
- }
51649
- if (event.channelProvider === "wechat") {
51650
- const toArg = event.channelExternalConversationId ? ` --to "${event.channelExternalConversationId}"` : " --to <wxid from this event>";
51651
- const atArg = event.channelConversationType === "group" ? event.senderId && event.senderId !== "external" ? ` --at "${event.senderId}"` : " --at <wxid of the person you are answering>" : "";
51652
- const historyArg = event.channelExternalConversationId ? ` --conversation "${event.channelExternalConversationId}"` : " --conversation <wxid from this event>";
51653
- return `
51654
- <system-reminder>Need earlier context? Run \`parall wechat history${historyArg}\`; history is not inserted automatically. To reply, use the platform verb: \`parall wechat send${toArg}${atArg} --text-file - <<'EOF'\` \u2026 \`EOF\` (or --text "<short text>" for simple literals \u2014 the quoted heredoc keeps $, backticks and apostrophes literal). In group chats, --at @-mentions the person you are answering. \`parall wechat send\` is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
51655
- }
51656
- if (!event.channelProvider) {
51657
- return `
51658
- <system-reminder>To reply, use the channel capability granted in your system prompt \u2014 for Feishu conversations that is \`lark-cli im\`, for Slack it is \`parall slack send\` (pass the message id from this event as --reply-to), for WeChat it is \`parall wechat send\`. That capability is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
51659
- }
51660
- const convRef = event.channelExternalConversationId ? `chat_id "${event.channelExternalConversationId}"` : "the conversation id named in this event";
51661
- const threadAlt = event.channelExternalMessageId ? ` To reply threaded to this specific message, reference message_id "${event.channelExternalMessageId}".` : "";
51662
- return `
51663
- <system-reminder>To reply, use the official Feishu CLI on your PATH: send a message to ${convRef} with \`lark-cli im\` (see \`lark-cli im --help\` for send syntax; auth is provisioned automatically).${threadAlt} lark-cli is the ONLY outbound path \u2014 your plain text output is NOT delivered to the external conversation.</system-reminder>`;
51664
- }
51665
- const platform = event.channelProvider ?? "the external platform";
51666
- return `
51667
- <system-reminder>This message arrived from ${platform}, but outbound replies are currently disabled for this org (no channel capability granted). Do NOT attempt to reply on the external platform. If action is needed, surface it inside Parall (\`parall messages send\` / \`parall dm\`). Your plain text output is not delivered anywhere.</system-reminder>`;
51668
- }
51669
- if (event.type === "external_trigger" || event.targetId.startsWith("xtr_")) {
51670
- return `
51671
- <system-reminder>This external trigger is incoming-only. Your plain text output is not sent back to the external provider. To communicate in Parall, use \`parall messages send\` / \`parall dm\`; provider-specific outbound actions require a separate capability.</system-reminder>`;
51672
- }
51673
- return "";
51469
+ function forkResultBody(event) {
51470
+ return eventBody(event).replace(/\n\[Reminder[^\n]*\]$/, "");
51674
51471
  }
51675
51472
  function buildForkScopePrefix(event) {
51676
- const targetLabel = event.targetName ? `"${event.targetName}" (prll://${event.targetId})` : `prll://${event.targetId}`;
51677
- return `[Fork scope: You are a parallel worker forked from the main session to handle ${targetLabel}. The conversation history above belongs to the main session's in-progress dispatch \u2014 do NOT continue it or complete it, or produce external output (comments, messages) for work visible there. The main session owns its own output.
51473
+ return `[Fork scope: You are a parallel worker forked from the main session to handle prll://${event.targetId}. The conversation history above belongs to the main session's in-progress dispatch \u2014 do NOT continue it or complete it, or produce external output (comments, messages) for work visible there. The main session owns its own output.
51678
51474
 
51679
51475
  Only act on the event below within your target scope. If your event reveals findings about the main session's work, report them in your summary \u2014 do not post them externally.
51680
51476
 
@@ -51703,6 +51499,26 @@ function buildForkResultPrefix(results) {
51703
51499
 
51704
51500
  // ts/agent-core/dist/gateway-base.js
51705
51501
  import * as os from "node:os";
51502
+
51503
+ // ts/agent-core/dist/change-source.js
51504
+ var CHANGE_REASONS = /* @__PURE__ */ new Set([
51505
+ "edited",
51506
+ "deleted",
51507
+ "unmentioned",
51508
+ "mention",
51509
+ "reaction"
51510
+ ]);
51511
+ function splitChangeSource(sourceId) {
51512
+ const i = sourceId.indexOf("~");
51513
+ if (i <= 0)
51514
+ return { messageId: sourceId };
51515
+ const [reason] = sourceId.slice(i + 1).split("~");
51516
+ if (!reason || !CHANGE_REASONS.has(reason))
51517
+ return { messageId: sourceId };
51518
+ return { messageId: sourceId.slice(0, i), reason };
51519
+ }
51520
+
51521
+ // ts/agent-core/dist/gateway-base.js
51706
51522
  import * as fs3 from "node:fs";
51707
51523
  import * as path3 from "node:path";
51708
51524
  import { randomUUID } from "node:crypto";
@@ -51817,6 +51633,8 @@ var ENDPOINTS = {
51817
51633
  MESSAGE_WATCH: (id) => `${API_BASE}/messages/${id}/watch`,
51818
51634
  MESSAGE_WATCHERS: (id) => `${API_BASE}/messages/${id}/watchers`,
51819
51635
  MESSAGE_WATCHING: (id) => `${API_BASE}/messages/${id}/watching`,
51636
+ /** Caller's attention levels across chats / threads / tasks. */
51637
+ WATCHES: (orgId) => `${API_BASE}/orgs/${orgId}/watches`,
51820
51638
  MESSAGE_REACTIONS: (id) => `${API_BASE}/messages/${id}/reactions`,
51821
51639
  MESSAGE_REACTION: (id, emoji) => `${API_BASE}/messages/${id}/reactions/${encodeURIComponent(emoji)}`,
51822
51640
  // Upload (org-scoped)
@@ -51839,6 +51657,7 @@ var ENDPOINTS = {
51839
51657
  AGENT_ACTIVITY: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/activity`,
51840
51658
  AGENT_MONITOR: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/monitor`,
51841
51659
  AGENT_ME: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me`,
51660
+ AGENT_REPLY_POLICY_CAPABILITY: (orgId) => `${API_BASE}/orgs/${orgId}/agents/me/reply-policy-capability`,
51842
51661
  AGENT_NEW_SESSION: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/new-session`,
51843
51662
  AGENT_DEEP_RESET: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/deep-reset`,
51844
51663
  AGENT_SESSIONS: (orgId, agentId) => `${API_BASE}/orgs/${orgId}/agents/${agentId}/sessions`,
@@ -51875,6 +51694,7 @@ var ENDPOINTS = {
51875
51694
  MACHINE_AGENT_WORKSPACE_SETUP: (orgId, machineId, agentId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/agents/${agentId}/workspace/setup`,
51876
51695
  MACHINE_LLM_SOURCE: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/llm-source`,
51877
51696
  MACHINE_PROVIDER_ENABLED: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/provider-enabled`,
51697
+ MACHINE_MANAGED_BY: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/managed-by`,
51878
51698
  MACHINE_CAPABILITIES: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/capabilities`,
51879
51699
  MACHINE_RUNTIME_AUTH: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/runtime-auth`,
51880
51700
  MACHINE_KEYS: (orgId, machineId) => `${API_BASE}/orgs/${orgId}/machines/${machineId}/keys`,
@@ -52355,8 +52175,22 @@ var ProjectTaskClient = class {
52355
52175
  async unsubscribeTaskMember(orgId, taskId, userId) {
52356
52176
  return this.request("DELETE", ENDPOINTS.TASK_SUBSCRIBER(orgId, taskId, userId));
52357
52177
  }
52358
- async watchThread(threadRootId) {
52359
- return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId));
52178
+ async watchThread(threadRootId, body) {
52179
+ return this.request("POST", ENDPOINTS.MESSAGE_WATCH(threadRootId), body);
52180
+ }
52181
+ // ---- Attention settings (agent-attention-design.md §4) ----
52182
+ /** The caller's watch rows: the setting per chat / thread. */
52183
+ async listWatches(orgId) {
52184
+ const res = await this.request("GET", ENDPOINTS.WATCHES(orgId));
52185
+ return res.data;
52186
+ }
52187
+ /**
52188
+ * Set the caller's setting on one target (prll://cht_ / msg_ root).
52189
+ * Threads are watched first when not yet; chats require membership (404
52190
+ * NOT_A_MEMBER otherwise). Tasks carry no setting (watch / unwatch only).
52191
+ */
52192
+ async setWatchLevel(orgId, body) {
52193
+ return this.request("PUT", ENDPOINTS.WATCHES(orgId), body);
52360
52194
  }
52361
52195
  async unwatchThread(threadRootId) {
52362
52196
  return this.request("DELETE", ENDPOINTS.MESSAGE_WATCH(threadRootId));
@@ -52756,7 +52590,7 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52756
52590
  return apiError;
52757
52591
  }
52758
52592
  /** Build headers common to all requests (auth, swimlane). */
52759
- buildHeaders(path11, extra) {
52593
+ buildHeaders(path12, extra) {
52760
52594
  const headers = {
52761
52595
  "Content-Type": "application/json",
52762
52596
  ...extra
@@ -52767,7 +52601,7 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52767
52601
  if (this.swimlaneName) {
52768
52602
  headers["X-Prll-Swimlane"] = this.swimlaneName;
52769
52603
  }
52770
- if (path11.startsWith(API_BASE)) {
52604
+ if (path12.startsWith(API_BASE)) {
52771
52605
  const overrides = this.getFeatureFlagOverrides?.();
52772
52606
  if (overrides)
52773
52607
  headers["X-Prll-FF-Override"] = overrides;
@@ -52791,8 +52625,8 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52791
52625
  * is authoritative, so wiki vs api routing can't drift from how a caller
52792
52626
  * happens to invoke the client.
52793
52627
  */
52794
- baseUrlFor(path11) {
52795
- return path11.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
52628
+ baseUrlFor(path12) {
52629
+ return path12.startsWith(WIKI_BASE) ? this.wikiBaseUrl : this.baseUrl;
52796
52630
  }
52797
52631
  setToken(token) {
52798
52632
  this.token = token;
@@ -52819,10 +52653,10 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52819
52653
  * REFRESH_THRESHOLD_S, refresh it **before** sending the request.
52820
52654
  * No-op when the token is still fresh, missing, or un-parseable.
52821
52655
  */
52822
- async ensureFreshToken(path11) {
52656
+ async ensureFreshToken(path12) {
52823
52657
  if (!this.token || !this.getRefreshToken)
52824
52658
  return;
52825
- const pathSuffix = path11.replace(/^\/api\/v1/, "");
52659
+ const pathSuffix = path12.replace(/^\/api\/v1/, "");
52826
52660
  if (_ParallClient.AUTH_PATHS.has(pathSuffix))
52827
52661
  return;
52828
52662
  const exp = _ParallClient.decodeJwtExp(this.token);
@@ -52854,11 +52688,11 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52854
52688
  this.refreshPromise = null;
52855
52689
  }
52856
52690
  }
52857
- async request(method, path11, body, query, retried = false, opts) {
52691
+ async request(method, path12, body, query, retried = false, opts) {
52858
52692
  if (!retried) {
52859
- await this.ensureFreshToken(path11);
52693
+ await this.ensureFreshToken(path12);
52860
52694
  }
52861
- let url = `${this.baseUrlFor(path11)}${path11}`;
52695
+ let url = `${this.baseUrlFor(path12)}${path12}`;
52862
52696
  if (query) {
52863
52697
  const params = new URLSearchParams();
52864
52698
  for (const [key, value] of Object.entries(query)) {
@@ -52870,7 +52704,7 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52870
52704
  if (qs)
52871
52705
  url += `?${qs}`;
52872
52706
  }
52873
- const headers = this.buildHeaders(path11, opts?.headers);
52707
+ const headers = this.buildHeaders(path12, opts?.headers);
52874
52708
  const timeoutSignal = AbortSignal.timeout(opts?.timeoutMs ?? 15e3);
52875
52709
  const signal = opts?.signal ? AbortSignal.any([opts.signal, timeoutSignal]) : timeoutSignal;
52876
52710
  let res;
@@ -52888,12 +52722,12 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52888
52722
  throw _ParallClient.normalizeFetchError(err);
52889
52723
  }
52890
52724
  if (res.status === 401) {
52891
- const pathSuffix = path11.replace(/^\/api\/v1/, "");
52725
+ const pathSuffix = path12.replace(/^\/api\/v1/, "");
52892
52726
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
52893
52727
  if (!retried && !isAuthPath && this.getRefreshToken) {
52894
52728
  const refreshed = await this.tryRefresh();
52895
52729
  if (refreshed) {
52896
- return this.request(method, path11, body, query, true, opts);
52730
+ return this.request(method, path12, body, query, true, opts);
52897
52731
  }
52898
52732
  }
52899
52733
  if (this.onTokenExpired && !isAuthPath) {
@@ -52923,18 +52757,18 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52923
52757
  * hit the 100 MiB cap, so a longer 5-minute timeout is used so a
52924
52758
  * 50 MiB blob on a slow connection doesn't get chopped at 15 s.
52925
52759
  */
52926
- async multipartRequest(method, path11, body, retried = false, opts) {
52760
+ async multipartRequest(method, path12, body, retried = false, opts) {
52927
52761
  if (!retried) {
52928
- await this.ensureFreshToken(path11);
52762
+ await this.ensureFreshToken(path12);
52929
52763
  }
52930
- const { "Content-Type": _drop, ...headers } = this.buildHeaders(path11);
52764
+ const { "Content-Type": _drop, ...headers } = this.buildHeaders(path12);
52931
52765
  void _drop;
52932
52766
  const timeoutMs = opts?.timeoutMs ?? 5 * 60 * 1e3;
52933
52767
  let res;
52934
52768
  try {
52935
52769
  res = await sendMultipartRequest({
52936
52770
  method,
52937
- url: `${this.baseUrlFor(path11)}${path11}`,
52771
+ url: `${this.baseUrlFor(path12)}${path12}`,
52938
52772
  headers,
52939
52773
  body,
52940
52774
  timeoutMs,
@@ -52945,12 +52779,12 @@ var ParallClient = class _ParallClient extends AttachmentClient {
52945
52779
  throw _ParallClient.normalizeFetchError(err);
52946
52780
  }
52947
52781
  if (res.status === 401) {
52948
- const pathSuffix = path11.replace(/^\/api\/v1/, "");
52782
+ const pathSuffix = path12.replace(/^\/api\/v1/, "");
52949
52783
  const isAuthPath = _ParallClient.AUTH_PATHS.has(pathSuffix);
52950
52784
  if (!retried && !isAuthPath && this.getRefreshToken) {
52951
52785
  const refreshed = await this.tryRefresh();
52952
52786
  if (refreshed) {
52953
- return this.multipartRequest(method, path11, body, true, opts);
52787
+ return this.multipartRequest(method, path12, body, true, opts);
52954
52788
  }
52955
52789
  }
52956
52790
  if (this.onTokenExpired && !isAuthPath) {
@@ -53405,6 +53239,15 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53405
53239
  const res = await this.request("GET", ENDPOINTS.APPROVALS_ACTIONS);
53406
53240
  return res.data;
53407
53241
  }
53242
+ /**
53243
+ * Action names plus the payload contract each documented action publishes
53244
+ * (field names, types, and where a CAS base like expected_version is read
53245
+ * from). Additive over getApprovableActions(): older servers omit
53246
+ * `contracts`.
53247
+ */
53248
+ async getApprovableActionCatalog() {
53249
+ return this.request("GET", ENDPOINTS.APPROVALS_ACTIONS);
53250
+ }
53408
53251
  // ---- Agents (org-scoped) ----
53409
53252
  async createAgent(orgId, req, opts) {
53410
53253
  return this.request("POST", ENDPOINTS.AGENTS(orgId), req, void 0, false, opts);
@@ -53629,6 +53472,19 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53629
53472
  provider_enabled: providerEnabled
53630
53473
  });
53631
53474
  }
53475
+ /**
53476
+ * Convert a member's personal device into an organization machine
53477
+ * (PATCH /machines/{id}/managed-by). One-way and idempotent; org admins only
53478
+ * (an admin-role agent qualifies). After conversion every org admin manages
53479
+ * the machine and the registrant is just a member. 'member' is rejected —
53480
+ * an org machine cannot become a personal device again. See
53481
+ * docs/engineering-design/org-machine-assets-design.md §4.
53482
+ */
53483
+ async convertMachineToOrgManaged(orgId, machineId) {
53484
+ return this.request("PATCH", ENDPOINTS.MACHINE_MANAGED_BY(orgId, machineId), {
53485
+ managed_by: "org"
53486
+ });
53487
+ }
53632
53488
  /**
53633
53489
  * Replace the machine's capability set (admin). Primary use: healing a
53634
53490
  * machine that registered without `browser_provider` during the capability
@@ -53772,8 +53628,8 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53772
53628
  * remote filesystem browse of a member's machine was remote device access.
53773
53629
  * The endpoint now answers 409 LOCAL_BROWSE_NOT_SUPPORTED unconditionally;
53774
53630
  * workspace paths are typed in (or picked on the machine's own Desktop). */
53775
- async browseMachineFilesystem(orgId, machineId, path11) {
53776
- return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path11 }, void 0, false, { timeoutMs: 15e3 });
53631
+ async browseMachineFilesystem(orgId, machineId, path12) {
53632
+ return this.request("POST", ENDPOINTS.MACHINE_BROWSE(orgId, machineId), { path: path12 }, void 0, false, { timeoutMs: 15e3 });
53777
53633
  }
53778
53634
  /** Create a new machine key. Returns the raw key string (shown once) + metadata. */
53779
53635
  async createMachineKey(orgId, machineId, name) {
@@ -53878,6 +53734,18 @@ var ParallClient = class _ParallClient extends AttachmentClient {
53878
53734
  async steerDispatch(orgId, req) {
53879
53735
  return this.request("POST", ENDPOINTS.DISPATCH_STEER(orgId), req);
53880
53736
  }
53737
+ /**
53738
+ * Declare the runtime contract for this WS connection: the runtime runs
53739
+ * what the server decides and takes the server-rendered wake frame from
53740
+ * claim / steer responses instead of filtering and rendering locally.
53741
+ * Bound to the connection's session id; re-declare on every hello.
53742
+ * 409 STALE_WS_SESSION when the id is not the agent's current connection.
53743
+ */
53744
+ async declareReplyPolicyCapability(orgId, wsSessionId) {
53745
+ await this.request("PUT", ENDPOINTS.AGENT_REPLY_POLICY_CAPABILITY(orgId), {
53746
+ ws_session_id: wsSessionId
53747
+ });
53748
+ }
53881
53749
  /** Advance exact runtime-input lifecycle for members of an explicit lane. */
53882
53750
  async updateDispatchInputState(orgId, req) {
53883
53751
  return this.request("POST", ENDPOINTS.DISPATCH_INPUT_STATE(orgId), req);
@@ -54335,12 +54203,12 @@ var ParallClient = class _ParallClient extends AttachmentClient {
54335
54203
  async deleteWikiRestriction(orgId, wikiId, restrictionId) {
54336
54204
  await this.request("DELETE", ENDPOINTS.WIKI_RESTRICTION(orgId, wikiId, restrictionId));
54337
54205
  }
54338
- async getWikiAccessStatus(orgId, wikiId, path11) {
54339
- return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path11 ? { path: path11 } : void 0);
54206
+ async getWikiAccessStatus(orgId, wikiId, path12) {
54207
+ return this.request("GET", ENDPOINTS.WIKI_ACCESS_STATUS(orgId, wikiId), void 0, path12 ? { path: path12 } : void 0);
54340
54208
  }
54341
54209
  // ---- Wiki membership projection (who-can-access, invites, join/leave) ----
54342
- async getWikiAccessPolicy(orgId, wikiId, path11 = "") {
54343
- return this.request("GET", ENDPOINTS.WIKI_ACCESS_POLICY(orgId, wikiId), void 0, path11 ? { path: path11 } : void 0);
54210
+ async getWikiAccessPolicy(orgId, wikiId, path12 = "") {
54211
+ return this.request("GET", ENDPOINTS.WIKI_ACCESS_POLICY(orgId, wikiId), void 0, path12 ? { path: path12 } : void 0);
54344
54212
  }
54345
54213
  async putWikiAccessPolicy(orgId, wikiId, policy) {
54346
54214
  return this.request("PUT", ENDPOINTS.WIKI_ACCESS_POLICY(orgId, wikiId), policy);
@@ -54385,14 +54253,14 @@ var ParallClient = class _ParallClient extends AttachmentClient {
54385
54253
  async getWikiCommits(orgId, wikiId, params) {
54386
54254
  return this.request("GET", ENDPOINTS.WIKI_COMMITS(orgId, wikiId), void 0, params);
54387
54255
  }
54388
- async getWikiFileCommits(orgId, wikiId, path11, params) {
54256
+ async getWikiFileCommits(orgId, wikiId, path12, params) {
54389
54257
  return this.request("GET", ENDPOINTS.WIKI_FILE_COMMITS(orgId, wikiId), void 0, {
54390
- path: path11,
54258
+ path: path12,
54391
54259
  ...params
54392
54260
  });
54393
54261
  }
54394
- async getWikiBlame(orgId, wikiId, path11, ref) {
54395
- return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path11, ref });
54262
+ async getWikiBlame(orgId, wikiId, path12, ref) {
54263
+ return this.request("GET", ENDPOINTS.WIKI_BLAME(orgId, wikiId), void 0, { path: path12, ref });
54396
54264
  }
54397
54265
  // ---- Wiki Operations (audit log) ----
54398
54266
  async getWikiOperations(orgId, wikiId, params) {
@@ -55209,20 +55077,6 @@ function buildApiError(res, rawErrorBody) {
55209
55077
  return apiError;
55210
55078
  }
55211
55079
 
55212
- // ts/sdk/dist/types.js
55213
- var MENTION_ALL_USER_ID = "all";
55214
- var MENTION_ALL_HUMANS_USER_ID = "allhuman";
55215
- var MENTION_ALL_AGENTS_USER_ID = "allagent";
55216
- function mentionTargetsUser(mentionUserId, userId, userType) {
55217
- if (mentionUserId === userId || mentionUserId === MENTION_ALL_USER_ID)
55218
- return true;
55219
- if (mentionUserId === MENTION_ALL_HUMANS_USER_ID)
55220
- return userType === "human";
55221
- if (mentionUserId === MENTION_ALL_AGENTS_USER_ID)
55222
- return userType === "agent";
55223
- return false;
55224
- }
55225
-
55226
55080
  // ts/sdk/dist/ws.js
55227
55081
  function isRetryableNetworkError(err) {
55228
55082
  return err instanceof Error && err.name === "ApiError" && "status" in err && err.status === 0;
@@ -55654,7 +55508,7 @@ var LaneLedger = class {
55654
55508
  get contextDir() {
55655
55509
  return this.opts.contextDir;
55656
55510
  }
55657
- /** Only chat message events ride the lane ledger; typed events stay on the legacy ack path. */
55511
+ /** Chat message events ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
55658
55512
  handles(event) {
55659
55513
  return event.type === "message" && event.targetId.startsWith("cht_");
55660
55514
  }
@@ -55670,6 +55524,75 @@ var LaneLedger = class {
55670
55524
  laneContextPath(lane) {
55671
55525
  return laneContextFilePath(this.opts.contextDir, lane.targetUri, lane.threadRootId);
55672
55526
  }
55527
+ /**
55528
+ * Whether the server already rendered this message into a frame the model
55529
+ * saw on its live lane. The row is folded there and resolves with that
55530
+ * lane's turn — a local copy has nothing left to deliver.
55531
+ */
55532
+ seenInFrame(targetId, threadRootId, messageId) {
55533
+ const lane = this.lanes.get(laneKeyForTarget(`prll://${targetId}`, threadRootId));
55534
+ return lane?.seen.has(messageId) ?? false;
55535
+ }
55536
+ /**
55537
+ * Hand the pending frame to the caller (once) with the members it covers
55538
+ * and what the claim said about the wake, and record those members as
55539
+ * seen. Absent frame ⇒ nothing new to render (every member already seen).
55540
+ */
55541
+ takeFrame(lane) {
55542
+ const frame = lane.frame;
55543
+ const ids = lane.framed;
55544
+ for (const id of ids)
55545
+ lane.seen.add(id);
55546
+ lane.frame = void 0;
55547
+ lane.framed = [];
55548
+ const { input, noReply, attachments } = lane;
55549
+ lane.input = void 0;
55550
+ lane.noReply = void 0;
55551
+ lane.attachments = void 0;
55552
+ return { frame, ids, input, noReply, attachments };
55553
+ }
55554
+ /** Record what the claim response said about the wake alongside its frame. */
55555
+ recordWake(lane, res) {
55556
+ if (res.input)
55557
+ lane.input = res.input;
55558
+ if (res.no_reply != null)
55559
+ lane.noReply = res.no_reply;
55560
+ if (res.attachments?.length) {
55561
+ lane.attachments = res.attachments.map((a) => ({
55562
+ id: a.id,
55563
+ fileName: a.file_name ?? "",
55564
+ fileSize: a.file_size ?? 0,
55565
+ mimeType: a.mime_type ?? ""
55566
+ }));
55567
+ }
55568
+ }
55569
+ /** The injection landed: the model has seen these members. */
55570
+ markSeen(event, ids) {
55571
+ const lane = this.lanes.get(this.laneKeyFor(event));
55572
+ if (!lane)
55573
+ return;
55574
+ for (const id of ids)
55575
+ lane.seen.add(id);
55576
+ }
55577
+ /**
55578
+ * The injection did not land (turn already over, process gone): keep the
55579
+ * server's increment as the lane's pending frame so the buffered copy's
55580
+ * drain renders it as its own turn instead of skipping it as seen.
55581
+ */
55582
+ deferFrame(event, frame, ids) {
55583
+ const lane = this.lanes.get(this.laneKeyFor(event));
55584
+ if (!lane)
55585
+ return;
55586
+ this.recordFrame(lane, frame, ids);
55587
+ }
55588
+ recordFrame(lane, frame, ids) {
55589
+ if (!frame)
55590
+ return;
55591
+ lane.frame = lane.frame ? `${lane.frame}
55592
+
55593
+ ${frame}` : frame;
55594
+ lane.framed.push(...ids);
55595
+ }
55673
55596
  /**
55674
55597
  * Claim (or reuse) the lane for a group of same-lane message events and
55675
55598
  * fold every group member into it. Returns 'foreign' when a healthy
@@ -55719,11 +55642,15 @@ var LaneLedger = class {
55719
55642
  threadRootId: trigger.threadRootId,
55720
55643
  coverageMode: actualCoverage,
55721
55644
  folded: /* @__PURE__ */ new Map(),
55645
+ framed: [],
55646
+ seen: /* @__PURE__ */ new Set(),
55722
55647
  ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
55723
55648
  };
55724
55649
  for (const ev of res.events ?? []) {
55725
55650
  lane.folded.set(ev.source_id, ev.id);
55726
55651
  }
55652
+ this.recordFrame(lane, res.frame, (res.events ?? []).map((ev) => ev.source_id));
55653
+ this.recordWake(lane, res);
55727
55654
  this.lanes.set(laneKey, lane);
55728
55655
  }
55729
55656
  for (const ev of events) {
@@ -55737,6 +55664,7 @@ var LaneLedger = class {
55737
55664
  ...ev.dispatchEventId ? { dispatch_event_id: ev.dispatchEventId } : { source_type: "message", source_id: ev.messageId }
55738
55665
  });
55739
55666
  lane.folded.set(ev.messageId, res.dispatch_event_id);
55667
+ this.recordFrame(lane, res.frame, [ev.messageId]);
55740
55668
  } catch (err) {
55741
55669
  if (isStaleLane(err)) {
55742
55670
  this.lanes.delete(laneKey);
@@ -55760,8 +55688,13 @@ var LaneLedger = class {
55760
55688
  const lane = this.lanes.get(laneKey);
55761
55689
  if (!lane)
55762
55690
  return null;
55691
+ if (lane.seen.has(event.messageId))
55692
+ return null;
55763
55693
  if (lane.folded.has(event.messageId)) {
55764
- return { inputLifecycle: this.inputLifecycle(lane, [event]) };
55694
+ return {
55695
+ inputLifecycle: this.inputLifecycleFor(lane, [event.messageId]),
55696
+ covered: [event.messageId]
55697
+ };
55765
55698
  }
55766
55699
  try {
55767
55700
  const res = await this.opts.client.steerDispatch(this.opts.orgId, {
@@ -55771,7 +55704,12 @@ var LaneLedger = class {
55771
55704
  ...event.dispatchEventId ? { dispatch_event_id: event.dispatchEventId } : { source_type: "message", source_id: event.messageId }
55772
55705
  });
55773
55706
  lane.folded.set(event.messageId, res.dispatch_event_id);
55774
- return { inputLifecycle: this.inputLifecycle(lane, [event]) };
55707
+ const covered = [event.messageId];
55708
+ return {
55709
+ inputLifecycle: this.inputLifecycleFor(lane, covered),
55710
+ frame: res.frame,
55711
+ covered
55712
+ };
55775
55713
  } catch (err) {
55776
55714
  if (isStaleLane(err)) {
55777
55715
  this.lanes.delete(laneKey);
@@ -55786,10 +55724,18 @@ var LaneLedger = class {
55786
55724
  * batched prompt covers every WorkItem represented in that single frame.
55787
55725
  */
55788
55726
  inputLifecycle(lane, events) {
55727
+ return this.inputLifecycleFor(lane, events.map((event) => event.messageId));
55728
+ }
55729
+ /**
55730
+ * Exact lifecycle over a set of folded members by message id — the set a
55731
+ * prompt or injection actually delivers (frame coverage ∪ buffered group).
55732
+ */
55733
+ inputLifecycleFor(lane, messageIds) {
55789
55734
  if (lane.coverageMode !== "explicit")
55790
55735
  return void 0;
55791
- const dispatchEventIds = events.map((event) => lane.folded.get(event.messageId)).filter((id) => Boolean(id));
55792
- if (dispatchEventIds.length !== events.length) {
55736
+ const unique = [...new Set(messageIds)];
55737
+ const dispatchEventIds = unique.map((messageId) => lane.folded.get(messageId)).filter((id) => Boolean(id));
55738
+ if (dispatchEventIds.length !== unique.length) {
55793
55739
  throw new Error(`explicit lane ${lane.lane} is missing a folded WorkItem mapping`);
55794
55740
  }
55795
55741
  return {
@@ -55987,10 +55933,12 @@ var LaneLedger = class {
55987
55933
  return this.lanes.size;
55988
55934
  }
55989
55935
  /**
55990
- * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>),
55991
- * by WorkItem id or by source identity (the live task.assigned event has no
55992
- * WorkItem id). Returns null when a healthy incumbent (another pod) holds
55993
- * it or the WorkItem is already resolved the caller must skip processing.
55936
+ * Claim the single-member lane of one typed WorkItem (resource = dsp:<id>)
55937
+ * by WorkItem id. The server renders the wake frame on claim (or resolves
55938
+ * the item as stale and answers `claimed: false, reason: "stale"`).
55939
+ * Returns null when a healthy incumbent (another pod) holds it, the
55940
+ * WorkItem is already resolved, or the server found nothing to wake for
55941
+ * — the caller must skip processing.
55994
55942
  */
55995
55943
  async claimTyped(ref) {
55996
55944
  let res;
@@ -56005,8 +55953,15 @@ var LaneLedger = class {
56005
55953
  throw new LedgerUnsupportedError("claim endpoint unavailable");
56006
55954
  throw err;
56007
55955
  }
56008
- if (!res.claimed || !res.lane || !res.events?.length)
55956
+ if (!res.claimed || !res.lane || !res.events?.length) {
55957
+ if (res.reason === "stale") {
55958
+ this.opts.log?.info(`typed dispatch ${ref.dispatchEventId ?? `${ref.sourceType}:${ref.sourceId}`} resolved by the server as stale (${res.stale_reason ?? "unspecified"})`);
55959
+ } else if (res.claimed && res.lane) {
55960
+ await this.opts.client.releaseDispatchLane(this.opts.orgId, res.lane).catch(() => {
55961
+ });
55962
+ }
56009
55963
  return null;
55964
+ }
56010
55965
  const workItem = res.events[0];
56011
55966
  const targetUri = `dsp:${workItem.id}`;
56012
55967
  const leaseUntilMs = Date.parse(res.lease_until ?? "");
@@ -56016,9 +55971,13 @@ var LaneLedger = class {
56016
55971
  targetUri,
56017
55972
  coverageMode: "implicit",
56018
55973
  folded: /* @__PURE__ */ new Map([[workItem.source_id, workItem.id]]),
55974
+ framed: [],
55975
+ seen: /* @__PURE__ */ new Set(),
56019
55976
  typedDispatchEventId: workItem.id,
56020
55977
  ...Number.isNaN(leaseUntilMs) ? {} : { leaseUntilMs, leaseTtlMs: Math.max(leaseUntilMs - Date.now(), 6e4) }
56021
55978
  };
55979
+ this.recordFrame(lane, res.frame, [workItem.source_id]);
55980
+ this.recordWake(lane, res);
56022
55981
  this.lanes.set(lane.laneKey, lane);
56023
55982
  return lane;
56024
55983
  }
@@ -56061,6 +56020,19 @@ function shiftMainBufferGroup(host, groupKey, preserveInjectedFrameBoundary) {
56061
56020
  }
56062
56021
  return events;
56063
56022
  }
56023
+ function applyWake(event, wake) {
56024
+ if (wake.frame)
56025
+ event.frame = wake.frame;
56026
+ if (wake.input) {
56027
+ event.input = wake.input;
56028
+ if (wake.input.sender_id)
56029
+ event.senderId = wake.input.sender_id;
56030
+ }
56031
+ if (wake.noReply != null)
56032
+ event.noReply = wake.noReply;
56033
+ if (wake.attachments?.length)
56034
+ event.attachments = wake.attachments;
56035
+ }
56064
56036
  function hasUninjectedSameLaneEventAhead(host, event) {
56065
56037
  const eventIndex = host.dispatchState.mainBuffer.lastIndexOf(event);
56066
56038
  if (eventIndex <= 0)
@@ -56078,10 +56050,17 @@ async function steerLaneMessage(host, event) {
56078
56050
  const folded = await ledger.steerLive(event);
56079
56051
  if (!folded)
56080
56052
  return;
56081
- const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, buildEventBody(event), folded.inputLifecycle);
56053
+ if (!folded.frame)
56054
+ return;
56055
+ event.frame = folded.frame;
56056
+ const injected = await adapter.enqueueDuringDispatch(opts.runtimeKey, eventBody(event), folded.inputLifecycle);
56082
56057
  if (injected) {
56083
56058
  host.injectedMainBufferEvents.add(event);
56059
+ ledger.markSeen(event, folded.covered);
56084
56060
  opts.log?.info(`steer folded+injected for ${event.messageId} (will drain for bookkeeping)`);
56061
+ } else if (folded.frame) {
56062
+ ledger.deferFrame(event, folded.frame, folded.covered);
56063
+ opts.log?.info(`steer folded but not injected for ${event.messageId} \u2014 frame deferred to the drain`);
56085
56064
  }
56086
56065
  }
56087
56066
  async function dispatchLaneGroup(host, opts) {
@@ -56094,18 +56073,9 @@ async function dispatchLaneGroup(host, opts) {
56094
56073
  if (!(err instanceof LedgerUnsupportedError))
56095
56074
  throw err;
56096
56075
  host.disableLedger("claim endpoint missing");
56097
- await host.emitDispatchReceived(event);
56098
- const dispatched2 = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText);
56099
- if (!dispatched2)
56100
- return "shutdown";
56101
- for (const ev of opts.events) {
56102
- host.opts.client.ackDispatch(host.opts.config.org_id, {
56103
- source_type: ev.ackSourceType ?? "message",
56104
- source_id: ev.ackSourceId ?? ev.messageId
56105
- }).catch(() => {
56106
- });
56107
- }
56108
- return "dispatched";
56076
+ for (const ev of opts.events)
56077
+ host.dispatchedMessages.delete(ev.messageId);
56078
+ return "foreign";
56109
56079
  }
56110
56080
  if (!lane) {
56111
56081
  for (const ev of opts.events) {
@@ -56113,11 +56083,32 @@ async function dispatchLaneGroup(host, opts) {
56113
56083
  }
56114
56084
  return "foreign";
56115
56085
  }
56086
+ const pending = ledger.takeFrame(lane);
56087
+ const frame = pending.frame;
56088
+ if (!frame && opts.events.every((ev) => lane.seen.has(ev.messageId))) {
56089
+ host.opts.log?.info(`lane group for ${event.messageId} already rendered by the server frame \u2014 no turn`);
56090
+ const pendingInjections2 = host.opts.dispatchAdapter.hasPendingInjections?.(opts.sessionKey) ?? false;
56091
+ await ledger.completeIfIdle(lane.laneKey, pendingInjections2 || opts.hasMoreLocal());
56092
+ return "dispatched";
56093
+ }
56094
+ if (!frame) {
56095
+ host.opts.log?.warn(`lane group for ${event.messageId} claimed without a frame \u2014 releasing the members instead of running`);
56096
+ for (const ev of opts.events)
56097
+ host.dispatchedMessages.delete(ev.messageId);
56098
+ await ledger.release(lane.laneKey).catch(() => {
56099
+ });
56100
+ return "foreign";
56101
+ }
56102
+ applyWake(event, pending);
56116
56103
  host.noteSessionLane(opts.sessionKey, lane.laneKey);
56117
56104
  let dispatched = false;
56118
56105
  try {
56119
- const inputLifecycle = ledger.inputLifecycle(lane, [...opts.earlier, event]);
56120
- dispatched = await host.runDispatch(event, opts.sessionKey, opts.body, opts.earlier, opts.captureText, inputLifecycle);
56106
+ const inputLifecycle = ledger.inputLifecycleFor(lane, [
56107
+ ...opts.earlier.map((ev) => ev.messageId),
56108
+ event.messageId,
56109
+ ...frame ? pending.ids : []
56110
+ ]);
56111
+ dispatched = await host.runDispatch(event, opts.sessionKey, opts.bodyPrefix + eventBody(event), opts.earlier, opts.captureText, inputLifecycle);
56121
56112
  } catch (err) {
56122
56113
  host.noteSessionLane(opts.sessionKey, null);
56123
56114
  await ledger.release(lane.laneKey).catch(() => {
@@ -56185,50 +56176,16 @@ async function resolveDispatchByID(host, dispatchEventId, lane) {
56185
56176
  return "failed";
56186
56177
  }
56187
56178
  }
56188
- function clearTypedDedupeForEvent(host, event) {
56189
- const sourceId = event.ackSourceId;
56190
- if (!sourceId)
56191
- return;
56192
- switch (event.ackSourceType) {
56193
- case "task_activity": {
56194
- const prefix = `${event.targetId}:`;
56195
- for (const key of host.dispatchedTasks) {
56196
- if (key.startsWith(prefix))
56197
- host.dispatchedTasks.delete(key);
56198
- }
56199
- break;
56200
- }
56201
- case "comment":
56202
- host.dispatchedTasks.delete(`comment:${sourceId}`);
56203
- break;
56204
- case "schedule_run":
56205
- host.dispatchedTasks.delete(`schedule_run:${sourceId}`);
56206
- break;
56207
- case "external_trigger_run":
56208
- host.dispatchedTasks.delete(`external_trigger_run:${sourceId}`);
56209
- break;
56210
- case "channel_message":
56211
- host.dispatchedMessages.delete(`channel_message:${sourceId}`);
56212
- break;
56213
- case "approval":
56214
- host.dispatchedTasks.delete(`approval:${sourceId}`);
56215
- break;
56216
- }
56217
- }
56218
56179
  async function settleDrainedTypedGroup(host, events, ids, turnErrored) {
56219
56180
  if (turnErrored) {
56220
56181
  host.opts.log?.info(`buffered typed turn for ${events[events.length - 1]?.messageId} surfaced a runtime error \u2014 leaving for re-drive`);
56221
- for (const event of events)
56222
- clearTypedDedupeForEvent(host, event);
56223
56182
  return;
56224
56183
  }
56225
56184
  const legacyAckFrom = async (start) => {
56226
- for (const [j, id] of ids.slice(start).entries()) {
56185
+ for (const id of ids.slice(start)) {
56227
56186
  try {
56228
56187
  await host.opts.client.ackDispatchByID(host.opts.config.org_id, id);
56229
56188
  } catch {
56230
- } finally {
56231
- clearTypedDedupeForEvent(host, events[start + j]);
56232
56189
  }
56233
56190
  }
56234
56191
  };
@@ -56244,7 +56201,6 @@ async function settleDrainedTypedGroup(host, events, ids, turnErrored) {
56244
56201
  await legacyAckFrom(i);
56245
56202
  return;
56246
56203
  }
56247
- clearTypedDedupeForEvent(host, events[i]);
56248
56204
  }
56249
56205
  }
56250
56206
  var TYPED_BACKOFF_BASE_MS = 2e3;
@@ -56280,18 +56236,8 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56280
56236
  }
56281
56237
  host.typedRedriveBackoff.set(backoffKey, { failures, until: Date.now() + backoffMs });
56282
56238
  };
56283
- const runLegacy = async () => {
56284
- let acked = false;
56285
- try {
56286
- if (await run(ref.dispatchEventId)) {
56287
- acked = settleAck(await hooks.legacyAck(ref.dispatchEventId));
56288
- }
56289
- } finally {
56290
- settle(acked);
56291
- }
56292
- };
56293
56239
  if (!host.laneLedger || host.ledgerDisabled) {
56294
- await runLegacy();
56240
+ host.opts.log?.info(`typed dispatch ${backoffKey} skipped \u2014 the server renders no wake frame`);
56295
56241
  return;
56296
56242
  }
56297
56243
  let lane;
@@ -56300,7 +56246,6 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56300
56246
  } catch (err) {
56301
56247
  if (err instanceof LedgerUnsupportedError) {
56302
56248
  host.disableLedger("claim endpoint missing");
56303
- await runLegacy();
56304
56249
  return;
56305
56250
  }
56306
56251
  throw err;
@@ -56312,7 +56257,7 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56312
56257
  let resolved = false;
56313
56258
  let viaLegacyAck = false;
56314
56259
  try {
56315
- if (await run(lane.typedDispatchEventId)) {
56260
+ if (await run(lane)) {
56316
56261
  if (host.typedByIdCompleteUnsupported || !lane.typedDispatchEventId) {
56317
56262
  viaLegacyAck = true;
56318
56263
  resolved = settleAck(await hooks.legacyAck(lane.typedDispatchEventId));
@@ -56324,13 +56269,9 @@ async function consumeTypedDispatch(host, ref, run, hooks) {
56324
56269
  viaLegacyAck = true;
56325
56270
  resolved = settleAck(await hooks.legacyAck(lane.typedDispatchEventId));
56326
56271
  } else if (outcome === "stale") {
56327
- hooks.clearDedupe?.();
56328
56272
  resolved = true;
56329
56273
  } else {
56330
56274
  resolved = outcome === "ok";
56331
- if (!resolved) {
56332
- hooks.clearDedupe?.();
56333
- }
56334
56275
  }
56335
56276
  }
56336
56277
  }
@@ -56349,56 +56290,27 @@ async function consumeMessageWorkItem(host, item) {
56349
56290
  return;
56350
56291
  if (!host.tryClaimMessage(item.source_id))
56351
56292
  return;
56352
- if (host.dispatchState.mainBuffer.some((event) => event.messageId === item.source_id))
56353
- return;
56354
- const ackItem = () => {
56355
- if (host.laneLedger && !host.ledgerDisabled && !host.typedByIdCompleteUnsupported) {
56356
- void resolveDispatchByID(host, item.id).then((outcome) => {
56357
- if (outcome === "unsupported") {
56358
- host.typedByIdCompleteUnsupported = true;
56359
- host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
56360
- });
56361
- }
56362
- });
56363
- return;
56364
- }
56365
- host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id).catch(() => {
56366
- });
56367
- };
56368
- let msg = null;
56369
- try {
56370
- msg = await host.opts.client.getMessage(item.source_id);
56371
- } catch (err) {
56372
- const status = err?.status;
56373
- if (status !== 404) {
56374
- host.opts.log?.warn(`message fetch failed for ${item.source_id}, leaving pending: ${String(err)}`);
56375
- host.dispatchedMessages.delete(item.source_id);
56376
- return;
56377
- }
56378
- }
56379
- if (!msg || msg.sender_id === host.opts.agentUserId) {
56380
- host.dispatchedMessages.delete(item.source_id);
56381
- ackItem();
56382
- return;
56383
- }
56384
- const decision = await host.buildMessageDispatchDecision(item.chat_id, msg);
56385
- if (decision.action === "retry") {
56386
- host.dispatchedMessages.delete(item.source_id);
56293
+ if (host.dispatchState.mainBuffer.some((event2) => event2.messageId === item.source_id))
56387
56294
  return;
56388
- }
56389
- if (decision.action === "skip") {
56390
- host.dispatchedMessages.delete(item.source_id);
56391
- ackItem();
56295
+ if (host.laneLedger && !host.ledgerDisabled && host.laneLedger.seenInFrame(item.chat_id, item.thread_root_id ?? void 0, item.source_id)) {
56392
56296
  return;
56393
56297
  }
56394
- decision.event.dispatchEventId = item.id;
56395
- const laneResolved = host.usesLaneLedger(decision.event);
56298
+ const change = splitChangeSource(item.source_id);
56299
+ const event = {
56300
+ type: "message",
56301
+ targetId: item.chat_id,
56302
+ targetType: "chat",
56303
+ senderId: item.actor_id ?? "",
56304
+ messageId: item.source_id,
56305
+ threadRootId: item.thread_root_id ?? void 0,
56306
+ deliveryReason: item.delivery_reason ?? change.reason ?? void 0,
56307
+ ackSourceType: "message",
56308
+ ackSourceId: item.source_id,
56309
+ dispatchEventId: item.id
56310
+ };
56396
56311
  try {
56397
- const dispatched = await host.handleInboundEvent(decision.event);
56398
- if (dispatched) {
56399
- if (!laneResolved)
56400
- ackItem();
56401
- } else {
56312
+ const dispatched = await host.handleInboundEvent(event);
56313
+ if (!dispatched) {
56402
56314
  host.dispatchedMessages.delete(item.source_id);
56403
56315
  }
56404
56316
  } catch (err) {
@@ -57587,6 +57499,16 @@ function createOtelLogger(layer, prefix) {
57587
57499
 
57588
57500
  // ts/agent-core/dist/gateway-base.js
57589
57501
  var LIVE_SESSION_STATUSES = /* @__PURE__ */ new Set(["open", "active", "idle"]);
57502
+ var TYPED_EVENT_KINDS = {
57503
+ task_assign: { type: "task", ackSourceType: "task_activity" },
57504
+ task_update: { type: "task", ackSourceType: "task_activity" },
57505
+ task_comment: { type: "task_comment", ackSourceType: "comment" },
57506
+ wiki_comment: { type: "wiki_comment", ackSourceType: "comment" },
57507
+ "schedule.fire": { type: "schedule", ackSourceType: "schedule_run" },
57508
+ external_trigger: { type: "external_trigger", ackSourceType: "external_trigger_run" },
57509
+ channel_message: { type: "channel_message", ackSourceType: "channel_message" },
57510
+ approval_decided: { type: "approval", ackSourceType: "approval" }
57511
+ };
57590
57512
  function parseShutdownDeadlineMs(raw) {
57591
57513
  if (!raw)
57592
57514
  return void 0;
@@ -57620,6 +57542,9 @@ function inputStepIdempotencyKey(event) {
57620
57542
  return randomUUID();
57621
57543
  }
57622
57544
  function resolveStepTarget(event) {
57545
+ if (event.input?.step_target) {
57546
+ return { target_type: event.input.step_target.type, target_id: event.input.step_target.id };
57547
+ }
57623
57548
  if (event.type === "task" || event.targetId.startsWith("tsk_")) {
57624
57549
  return { target_type: "task", target_id: event.targetId };
57625
57550
  }
@@ -57640,48 +57565,63 @@ function resolveStepTarget(event) {
57640
57565
  }
57641
57566
  return { target_type: "", target_id: event.targetId || void 0 };
57642
57567
  }
57643
- function parseWikiCommentTarget(targetUri) {
57644
- const routingKey = targetUri.replace(/^prll:\/\//, "");
57645
- const entityId = routingKey.match(/^([^/?#]+)/)?.[1] ?? routingKey;
57646
- const targetType = entityId.startsWith("wcs_") ? "changeset" : "wiki";
57647
- let label = entityId;
57648
- if (targetType === "wiki") {
57649
- const pathMatch = routingKey.slice(entityId.length).match(/^\/([^?#]+)/);
57650
- if (pathMatch) {
57651
- try {
57652
- label = decodeURIComponent(pathMatch[1]);
57653
- } catch {
57654
- label = pathMatch[1];
57655
- }
57656
- }
57568
+ function inputTriggerTypeFor(type) {
57569
+ switch (type) {
57570
+ case "task":
57571
+ return "task_assign";
57572
+ case "task_comment":
57573
+ return "task_comment";
57574
+ case "wiki_comment":
57575
+ return "wiki_comment";
57576
+ case "schedule":
57577
+ return "schedule_fire";
57578
+ case "external_trigger":
57579
+ return "external_trigger";
57580
+ case "channel_message":
57581
+ return "channel_message";
57582
+ case "approval":
57583
+ return "approval_decided";
57584
+ default:
57585
+ return "mention";
57586
+ }
57587
+ }
57588
+ function inputTriggerRef(event) {
57589
+ const sourceId = event.ackSourceId ?? event.messageId;
57590
+ switch (event.type) {
57591
+ case "task":
57592
+ return { task_id: event.targetId };
57593
+ case "task_comment":
57594
+ return { comment_id: sourceId, task_id: event.targetId };
57595
+ case "wiki_comment":
57596
+ return { comment_id: sourceId, target_uri: `prll://${event.targetId}` };
57597
+ case "schedule":
57598
+ return { schedule_id: event.targetId, run_id: sourceId };
57599
+ case "external_trigger":
57600
+ return { trigger_id: event.targetId, run_id: sourceId };
57601
+ case "channel_message":
57602
+ return { conversation_id: event.targetId, channel_message_id: sourceId };
57603
+ case "approval":
57604
+ return { approval_id: sourceId };
57605
+ default:
57606
+ return {
57607
+ message_id: splitChangeSource(event.messageId).messageId,
57608
+ // Thread context for the session→chat backlink: a thread reply can
57609
+ // only be navigated to with its thread root.
57610
+ ...event.threadRootId ? { thread_root_id: event.threadRootId } : {}
57611
+ };
57657
57612
  }
57658
- return { routingKey, label, targetType };
57659
- }
57660
- async function fetchAllChats(client, orgId, chatInfoMap) {
57661
- let cursor;
57662
- let total = 0;
57663
- do {
57664
- const res = await client.getChats(orgId, { limit: 100, cursor });
57665
- for (const chat of res.data) {
57666
- chatInfoMap.set(chat.id, {
57667
- type: chat.type,
57668
- name: chat.name ?? null,
57669
- agentRoutingMode: chat.agent_routing_mode
57670
- });
57671
- }
57672
- total += res.data.length;
57673
- cursor = res.has_more ? res.next_cursor : void 0;
57674
- } while (cursor);
57675
- return total;
57676
57613
  }
57677
57614
  var ParallAgentGateway = class {
57678
57615
  opts;
57679
- chatInfoMap = /* @__PURE__ */ new Map();
57680
- dispatchedTasks = /* @__PURE__ */ new Set();
57681
- // connection id → provider alias, for channel_message prompt labeling
57682
- // (stable mapping; avoids one connection fetch per inbound message).
57683
- channelConnectionProviders = /* @__PURE__ */ new Map();
57616
+ // In-process in-flight guard for message WorkItems (see LaneFlowHost).
57684
57617
  dispatchedMessages = /* @__PURE__ */ new Set();
57618
+ /**
57619
+ * Consumption fence: no WorkItem is claimed before this connection's
57620
+ * runtime contract is declared (handleHello). A claim made before the
57621
+ * declaration would get no frame — and a frameless claim has nothing to
57622
+ * run. Open until the first hello starts a declaration.
57623
+ */
57624
+ contractReady = Promise.resolve();
57685
57625
  injectedMainBufferEvents = /* @__PURE__ */ new WeakSet();
57686
57626
  // Per-WorkItem failure backoff for typed dispatch consumption — see
57687
57627
  // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
@@ -57793,29 +57733,6 @@ var ParallAgentGateway = class {
57793
57733
  ws.on("hello", async (data) => {
57794
57734
  await this.handleHello(data);
57795
57735
  });
57796
- ws.on("chat.update", (data) => {
57797
- const changes = data.changes;
57798
- if (!changes)
57799
- return;
57800
- const existing = this.chatInfoMap.get(data.chat_id);
57801
- if (existing) {
57802
- this.chatInfoMap.set(data.chat_id, {
57803
- ...existing,
57804
- ...typeof changes.type === "string" ? { type: changes.type } : {},
57805
- ...typeof changes.name === "string" ? { name: changes.name } : {},
57806
- ...typeof changes.agent_routing_mode === "string" ? { agentRoutingMode: changes.agent_routing_mode } : {}
57807
- });
57808
- } else if (typeof changes.type === "string") {
57809
- this.chatInfoMap.set(data.chat_id, {
57810
- type: changes.type,
57811
- name: typeof changes.name === "string" ? changes.name : null,
57812
- agentRoutingMode: typeof changes.agent_routing_mode === "string" ? changes.agent_routing_mode : "passive"
57813
- });
57814
- }
57815
- });
57816
- ws.on("message.new", async (data) => {
57817
- await this.handleMessage(data);
57818
- });
57819
57736
  ws.on("agent_config.update", async (data) => {
57820
57737
  this.opts.log?.info(`config update notification (version=${data.version})`);
57821
57738
  try {
@@ -57843,135 +57760,11 @@ var ParallAgentGateway = class {
57843
57760
  this.opts.log?.warn(`recovery.overflow \u2014 triggering full catch-up`);
57844
57761
  this.catchUpFromDispatch().catch((err) => this.opts.log?.warn(`overflow catch-up failed: ${String(err)}`));
57845
57762
  });
57846
- ws.on("task.assigned", async (data) => {
57847
- if (data.assignee_id !== this.opts.agentUserId)
57848
- return;
57849
- if (data.status !== "todo" && data.status !== "in_progress")
57850
- return;
57763
+ ws.on("dispatch.new", async (data) => {
57851
57764
  try {
57852
- await this.consumeTypedDispatch(data.dispatch_event_id ? { dispatchEventId: data.dispatch_event_id } : { sourceType: "task_activity", sourceId: data.id }, (dispatchEventId) => this.handleTaskAssignment(data, data.id, dispatchEventId), {
57853
- legacyAck: (dispatchEventId) => {
57854
- if (dispatchEventId) {
57855
- return this.ackDispatchEvent(dispatchEventId, () => {
57856
- this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
57857
- });
57858
- }
57859
- return this.opts.client.ackDispatch(this.opts.config.org_id, {
57860
- source_type: "task_activity",
57861
- source_id: data.id
57862
- }).then(() => true, (err) => {
57863
- this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`);
57864
- this.opts.log?.warn(`dispatch ack failed for task ${data.id}, releasing for re-drive: ${String(err)}`);
57865
- return false;
57866
- });
57867
- },
57868
- clearDedupe: () => this.dispatchedTasks.delete(`${data.id}:${data.updated_at}`)
57869
- });
57765
+ await this.consumeWorkItem(data);
57870
57766
  } catch (err) {
57871
- this.opts.log?.error(`task dispatch failed for ${data.id}: ${String(err)}`);
57872
- }
57873
- });
57874
- ws.on("dispatch.new", async (data) => {
57875
- if (data.event_type !== "message" && this.isBufferedTypedWorkItem(data.id)) {
57876
- this.opts.log?.info(`typed dispatch ${data.id} already buffered for the drain \u2014 skipping re-claim`);
57877
- return;
57878
- }
57879
- if (data.event_type === "task_assign") {
57880
- if (!data.task_id)
57881
- return;
57882
- try {
57883
- await this.handleTaskAssignmentRedrive(data);
57884
- } catch (err) {
57885
- this.opts.log?.error(`task assignment re-drive failed for ${data.task_id}: ${String(err)}`);
57886
- }
57887
- } else if (data.event_type === "task_comment") {
57888
- if (!data.source_id || !data.task_id)
57889
- return;
57890
- try {
57891
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleTaskComment(data.source_id, data.task_id ?? "", data.actor_id, data.delivery_reason, dispatchEventId), {
57892
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57893
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57894
- });
57895
- } catch (err) {
57896
- this.opts.log?.error(`task comment dispatch failed for ${data.source_id}: ${String(err)}`);
57897
- }
57898
- } else if (data.event_type === "wiki_comment") {
57899
- if (!data.source_id)
57900
- return;
57901
- try {
57902
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleWikiComment(data.source_id, data.actor_id, data.delivery_reason, dispatchEventId), {
57903
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57904
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57905
- });
57906
- } catch (err) {
57907
- this.opts.log?.error(`wiki comment dispatch failed for ${data.source_id}: ${String(err)}`);
57908
- }
57909
- } else if (data.event_type === "task_update") {
57910
- if (!data.task_id)
57911
- return;
57912
- try {
57913
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.handleTaskDispatch(data.task_id ?? "", data.source_id ?? data.task_id ?? "", {
57914
- allowCreator: true,
57915
- dispatchEventId
57916
- }), {
57917
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57918
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57919
- });
57920
- } catch (err) {
57921
- this.opts.log?.error(`task update dispatch failed for ${data.task_id}: ${String(err)}`);
57922
- }
57923
- } else if (data.event_type === "schedule.fire") {
57924
- if (!data.source_id)
57925
- return;
57926
- try {
57927
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleScheduleFire(data.source_id, data.actor_id, dispatchEventId), {
57928
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57929
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57930
- });
57931
- } catch (err) {
57932
- this.opts.log?.error(`schedule fire dispatch failed for ${data.source_id}: ${String(err)}`);
57933
- }
57934
- } else if (data.event_type === "external_trigger") {
57935
- if (!data.source_id)
57936
- return;
57937
- try {
57938
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleExternalTriggerRun(data.source_id, dispatchEventId), {
57939
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57940
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57941
- });
57942
- } catch (err) {
57943
- this.opts.log?.error(`external trigger dispatch failed for ${data.source_id}: ${String(err)}`);
57944
- }
57945
- } else if (data.event_type === "channel_message") {
57946
- if (!data.source_id)
57947
- return;
57948
- try {
57949
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleChannelMessage(data.source_id, dispatchEventId), {
57950
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57951
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57952
- });
57953
- } catch (err) {
57954
- this.opts.log?.error(`channel message dispatch failed for ${data.source_id}: ${String(err)}`);
57955
- }
57956
- } else if (data.event_type === "approval_decided") {
57957
- if (!data.source_id)
57958
- return;
57959
- try {
57960
- await this.consumeTypedDispatch({ dispatchEventId: data.id }, (dispatchEventId) => this.fetchAndHandleApprovalDecided(data.source_id, data.actor_id, data.chat_id ?? null, dispatchEventId), {
57961
- legacyAck: () => this.ackDispatchEvent(data.id, () => this.clearTypedDispatchDedupe(data)),
57962
- clearDedupe: () => this.clearTypedDispatchDedupe(data)
57963
- });
57964
- } catch (err) {
57965
- this.opts.log?.error(`approval decided dispatch failed for ${data.source_id}: ${String(err)}`);
57966
- }
57967
- } else if (data.event_type === "message" && this.laneLedger && data.source_id && data.chat_id) {
57968
- try {
57969
- await this.handleMessageRedrive(data);
57970
- } catch (err) {
57971
- this.opts.log?.error(`message re-drive failed for ${data.source_id}: ${String(err)}`);
57972
- }
57973
- } else if (data.event_type !== "message") {
57974
- this.opts.log?.info(`dispatch.new with unhandled event_type=${String(data.event_type)} (id=${data.id}) \u2014 no-op`);
57767
+ this.opts.log?.error(`dispatch ${data.id} (${String(data.event_type)}) failed: ${String(err)}`);
57975
57768
  }
57976
57769
  });
57977
57770
  this.opts.log?.info(`connecting to ${this.opts.connectionLabel ?? "Parall WS"}...`);
@@ -58156,44 +57949,6 @@ var ParallAgentGateway = class {
58156
57949
  isTypedEventBuffered(event) {
58157
57950
  return this.isBufferedTypedWorkItem(event.dispatchEventId);
58158
57951
  }
58159
- // PARITY: this switch and gateway-lane-flow's clearTypedDedupeForEvent must
58160
- // handle the same typed source families — extend BOTH when adding a typed
58161
- // event type (same dedupe entries, keyed from different event shapes).
58162
- clearTypedDispatchDedupe(item) {
58163
- switch (item.event_type) {
58164
- case "task_assign":
58165
- case "task_update":
58166
- if (item.task_id) {
58167
- const prefix = `${item.task_id}:`;
58168
- for (const key of this.dispatchedTasks) {
58169
- if (key.startsWith(prefix))
58170
- this.dispatchedTasks.delete(key);
58171
- }
58172
- }
58173
- break;
58174
- case "task_comment":
58175
- case "wiki_comment":
58176
- if (item.source_id)
58177
- this.dispatchedTasks.delete(`comment:${item.source_id}`);
58178
- break;
58179
- case "schedule.fire":
58180
- if (item.source_id)
58181
- this.dispatchedTasks.delete(`schedule_run:${item.source_id}`);
58182
- break;
58183
- case "external_trigger":
58184
- if (item.source_id)
58185
- this.dispatchedTasks.delete(`external_trigger_run:${item.source_id}`);
58186
- break;
58187
- case "channel_message":
58188
- if (item.source_id)
58189
- this.dispatchedMessages.delete(`channel_message:${item.source_id}`);
58190
- break;
58191
- case "approval_decided":
58192
- if (item.source_id)
58193
- this.dispatchedTasks.delete(`approval:${item.source_id}`);
58194
- break;
58195
- }
58196
- }
58197
57952
  buildDispatchContext(event, sessionKey) {
58198
57953
  const binding = this.sessionBindings.get(sessionKey);
58199
57954
  return {
@@ -58206,7 +57961,7 @@ var ParallAgentGateway = class {
58206
57961
  runtimeKey: this.opts.runtimeKey,
58207
57962
  sessionId: binding?.agentSessionId,
58208
57963
  chatId: event.type === "message" || event.type === "approval" ? event.targetId : void 0,
58209
- triggerMessageId: event.messageId,
57964
+ triggerMessageId: splitChangeSource(event.messageId).messageId,
58210
57965
  noReply: event.noReply ?? false,
58211
57966
  contextFilePath: this.opts.contextFilePathForSession?.(sessionKey),
58212
57967
  stepIdFilePath: this.opts.stepIdFilePathForSession?.(sessionKey),
@@ -58220,35 +57975,24 @@ var ParallAgentGateway = class {
58220
57975
  }
58221
57976
  async createInputStep(sessionId, event) {
58222
57977
  const target = resolveStepTarget(event);
57978
+ const input = event.input;
58223
57979
  await this.stepPersister.persist(sessionId, "input", {
58224
57980
  step_type: "input",
58225
57981
  target_type: target.target_type,
58226
57982
  target_id: target.target_id,
58227
57983
  idempotency_key: inputStepIdempotencyKey(event),
58228
57984
  content: {
58229
- trigger_type: event.type === "task" ? "task_assign" : event.type === "task_comment" ? "task_comment" : event.type === "wiki_comment" ? "wiki_comment" : event.type === "schedule" ? "schedule_fire" : event.type === "external_trigger" ? "external_trigger" : event.type === "channel_message" ? "channel_message" : event.type === "approval" ? "approval_decided" : "mention",
58230
- trigger_ref: event.type === "task" ? { task_id: event.targetId } : event.type === "task_comment" ? { comment_id: event.messageId, task_id: event.targetId } : event.type === "wiki_comment" ? { comment_id: event.messageId, target_uri: event.replyTargetUri } : event.type === "schedule" ? { schedule_id: event.targetId, run_id: event.messageId } : event.type === "external_trigger" ? {
58231
- trigger_id: event.targetId,
58232
- run_id: event.messageId,
58233
- connection_id: event.externalConnectionId,
58234
- ingress_event_id: event.externalIngressEventId
58235
- } : event.type === "channel_message" ? {
58236
- conversation_id: event.targetId,
58237
- channel_message_id: event.messageId,
58238
- provider: event.channelProvider,
58239
- external_conversation_id: event.channelExternalConversationId
58240
- } : event.type === "approval" ? { approval_id: event.messageId } : {
58241
- message_id: event.messageId,
58242
- // Thread context for the session→chat backlink:
58243
- // a thread reply can only be navigated to with
58244
- // its thread root (the chat surface rejects
58245
- // bare thread-message targets).
58246
- ...event.threadRootId ? { thread_root_id: event.threadRootId } : {}
58247
- },
57985
+ // What the server said about the wake (claim `input`), plus the
57986
+ // source pointer and the anchor the web needs to link a chat
57987
+ // message or a task to this session.
57988
+ trigger_type: input?.trigger_type ?? inputTriggerTypeFor(event.type),
57989
+ trigger_ref: inputTriggerRef(event),
57990
+ source_type: event.ackSourceType,
57991
+ source_id: event.ackSourceId ?? event.messageId,
58248
57992
  sender_id: event.senderId,
58249
- sender_name: event.senderName,
58250
- summary: event.body.substring(0, 200),
58251
- ...event.sentAt ? { sent_at: event.sentAt } : {}
57993
+ ...input?.sender_name ? { sender_name: input.sender_name } : {},
57994
+ summary: (input?.summary ?? eventBody(event)).substring(0, 200),
57995
+ ...input?.sent_at ? { sent_at: input.sent_at } : {}
58252
57996
  }
58253
57997
  });
58254
57998
  }
@@ -58760,13 +58504,14 @@ var ParallAgentGateway = class {
58760
58504
  retainForkContinuationRetries(this.forkContinuationRetries, events, fork.continuationPrefix);
58761
58505
  try {
58762
58506
  const batchText = [];
58763
- const body = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last) + buildEventBody(last);
58507
+ const bodyPrefix = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last);
58508
+ const body = bodyPrefix + eventBody(last);
58764
58509
  let dispatched;
58765
58510
  if (this.usesLaneLedger(last)) {
58766
58511
  const outcome = await this.dispatchLaneGroup({
58767
58512
  events,
58768
58513
  sessionKey: fork.fork.sessionKey,
58769
- body,
58514
+ bodyPrefix,
58770
58515
  earlier,
58771
58516
  captureText: batchText,
58772
58517
  // Per-LANE residue check (parity with the main-buffer path):
@@ -58841,9 +58586,9 @@ var ParallAgentGateway = class {
58841
58586
  sourceEvent: {
58842
58587
  type: first.type,
58843
58588
  targetId: fork.targetId,
58844
- summary: fork.processedEvents.length === 1 ? `${first.type} from ${first.senderName} in ${first.targetName ?? fork.targetId}` : `${fork.processedEvents.length} events in ${first.targetName ?? fork.targetId}`
58589
+ summary: fork.processedEvents.length === 1 ? `${first.type} in ${fork.targetId}` : `${fork.processedEvents.length} events in ${fork.targetId}`
58845
58590
  },
58846
- eventBodies: fork.processedEvents.map((e) => buildEventBodyForForkResult(e)),
58591
+ eventBodies: fork.processedEvents.map((e) => forkResultBody(e)),
58847
58592
  actions: [],
58848
58593
  agentSummary,
58849
58594
  historyPath
@@ -58914,7 +58659,7 @@ var ParallAgentGateway = class {
58914
58659
  outcome = await this.dispatchLaneGroup({
58915
58660
  events,
58916
58661
  sessionKey: this.opts.runtimeKey,
58917
- body: forkPrefix + buildEventBody(event),
58662
+ bodyPrefix: forkPrefix,
58918
58663
  earlier,
58919
58664
  hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === groupKey)
58920
58665
  });
@@ -58956,16 +58701,14 @@ var ParallAgentGateway = class {
58956
58701
  }
58957
58702
  }
58958
58703
  const isTypedGroup = events.every((ev) => ev.type !== "message");
58959
- const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => buildEventBody(ev)).join("\n\n") : buildEventBody(event);
58704
+ const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => eventBody(ev)).join("\n\n") : eventBody(event);
58960
58705
  let dispatched;
58961
58706
  try {
58962
58707
  dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + body, earlier);
58963
58708
  } catch (err) {
58964
58709
  if (!isTypedGroup)
58965
58710
  throw err;
58966
- this.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}, claims freed for re-drive): ${String(err)}`);
58967
- for (const ev of events)
58968
- clearTypedDedupeForEvent(this.laneFlowHost(), ev);
58711
+ this.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}): ${String(err)}`);
58969
58712
  this.dispatchState.pendingForkResults.unshift(...pendingFork);
58970
58713
  continue;
58971
58714
  }
@@ -58986,7 +58729,6 @@ var ParallAgentGateway = class {
58986
58729
  source_id: sourceId
58987
58730
  }).catch(() => {
58988
58731
  });
58989
- clearTypedDedupeForEvent(this.laneFlowHost(), bufferedEvent);
58990
58732
  }
58991
58733
  } finally {
58992
58734
  for (const id of drainingIds)
@@ -59029,7 +58771,7 @@ var ParallAgentGateway = class {
59029
58771
  outcome = await this.dispatchLaneGroup({
59030
58772
  events: [event],
59031
58773
  sessionKey: this.opts.runtimeKey,
59032
- body: forkPrefix + buildEventBody(event),
58774
+ bodyPrefix: forkPrefix,
59033
58775
  earlier: [],
59034
58776
  hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === this.dispatchGroupKey(event))
59035
58777
  });
@@ -59061,7 +58803,7 @@ var ParallAgentGateway = class {
59061
58803
  }
59062
58804
  let dispatched = false;
59063
58805
  try {
59064
- dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + buildEventBody(event));
58806
+ dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + eventBody(event));
59065
58807
  if (dispatched && typedRefs && this.consumeTurnError(this.opts.runtimeKey)) {
59066
58808
  this.opts.log?.info(`typed dispatch turn for ${event.messageId} surfaced a runtime error \u2014 releasing for retry`);
59067
58809
  dispatched = false;
@@ -59095,7 +58837,7 @@ var ParallAgentGateway = class {
59095
58837
  // the WorkItem stays live, and every re-drive injects it AGAIN (the
59096
58838
  // 7/16 watcher duplicate-delivery loop, #1149). Typed events stay
59097
58839
  // buffered; the drain claims them as their own turn.
59098
- event.type === "message" && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, buildEventBody(event))
58840
+ event.type === "message" && event.frame != null && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, eventBody(event))
59099
58841
  ) {
59100
58842
  this.opts.log?.info(`steer injected for ${event.messageId} (will drain for bookkeeping)`);
59101
58843
  }
@@ -59156,605 +58898,75 @@ var ParallAgentGateway = class {
59156
58898
  }
59157
58899
  }
59158
58900
  }
59159
- async getOrFetchChatInfo(chatId) {
59160
- const cached = this.chatInfoMap.get(chatId);
59161
- if (cached)
59162
- return cached;
59163
- try {
59164
- const chat = await this.opts.client.getChat(this.opts.config.org_id, chatId);
59165
- const chatInfo = {
59166
- type: chat.type,
59167
- name: chat.name ?? null,
59168
- agentRoutingMode: chat.agent_routing_mode
59169
- };
59170
- this.chatInfoMap.set(chatId, chatInfo);
59171
- return chatInfo;
59172
- } catch (err) {
59173
- this.opts.log?.warn(`failed to resolve chat ${chatId}: ${String(err)}`);
59174
- return null;
59175
- }
59176
- }
59177
- async buildMessageDispatchDecision(chatId, message) {
59178
- if (message.message_type !== "text") {
59179
- return { action: "skip" };
59180
- }
59181
- const chatInfo = await this.getOrFetchChatInfo(chatId);
59182
- if (!chatInfo)
59183
- return { action: "retry" };
59184
- const content = message.content;
59185
- const body = content.text?.trim() ?? "";
59186
- const hasAttachments = message.attachments?.length;
59187
- if (!body && !hasAttachments)
59188
- return { action: "skip" };
59189
- const mentions = content.mentions ?? [];
59190
- const isMentioned = mentions.some((mention) => mentionTargetsUser(mention.user_id, this.opts.agentUserId, "agent"));
59191
- let deliveryReason;
59192
- if (message.thread_root_id) {
59193
- if (isMentioned) {
59194
- deliveryReason = "mention";
59195
- } else {
59196
- let watching;
59197
- try {
59198
- watching = await this.opts.client.isWatchingThread(message.thread_root_id);
59199
- } catch {
59200
- return { action: "retry" };
59201
- }
59202
- if (!watching)
59203
- return { action: "skip" };
59204
- deliveryReason = "watcher";
59205
- }
59206
- } else if (chatInfo.type === "group") {
59207
- if (chatInfo.agentRoutingMode !== "active" && !isMentioned)
59208
- return { action: "skip" };
59209
- if (isMentioned)
59210
- deliveryReason = "mention";
59211
- }
59212
- const attachments = (message.attachments ?? []).map((a) => ({
59213
- id: a.id,
59214
- fileName: a.file_name,
59215
- fileSize: a.file_size,
59216
- mimeType: a.mime_type
59217
- }));
59218
- let unreadCount;
59219
- let unreadSince;
59220
- let threadReplyCount;
59221
- let threadUnreadCount;
59222
- let threadUnreadSince;
59223
- const isPassiveOrSmart = chatInfo.type === "group" && chatInfo.agentRoutingMode !== "active";
59224
- const unreadPromise = isPassiveOrSmart ? this.opts.client.getUnreadCounts(this.opts.config.org_id).catch(() => void 0) : Promise.resolve(void 0);
59225
- const threadPromise = message.thread_root_id ? this.opts.client.getThreadUnread(this.opts.config.org_id, chatId, message.thread_root_id).catch(() => void 0) : Promise.resolve(void 0);
59226
- const [counts, threadUnread] = await Promise.all([unreadPromise, threadPromise]);
59227
- if (counts) {
59228
- const entry = counts[chatId];
59229
- if (entry && entry.count > 1) {
59230
- unreadCount = entry.count;
59231
- unreadSince = entry.since;
59232
- }
59233
- }
59234
- if (threadUnread) {
59235
- threadReplyCount = threadUnread.total;
59236
- threadUnreadCount = threadUnread.unread > 0 ? threadUnread.unread : void 0;
59237
- threadUnreadSince = threadUnread.since ?? void 0;
59238
- }
59239
- return {
59240
- action: "dispatch",
59241
- event: {
59242
- type: "message",
59243
- targetId: chatId,
59244
- targetName: chatInfo.name ?? void 0,
59245
- targetType: chatInfo.type,
59246
- senderId: message.sender_id,
59247
- senderName: message.sender?.display_name ?? message.sender_id,
59248
- messageId: message.id,
59249
- body: body || "[attachment]",
59250
- threadRootId: message.thread_root_id ?? void 0,
59251
- deliveryReason,
59252
- noReply: message.hints?.no_reply ?? false,
59253
- attachments: attachments.length > 0 ? attachments : void 0,
59254
- sentAt: message.created_at,
59255
- ackSourceType: "message",
59256
- ackSourceId: message.id,
59257
- unreadCount,
59258
- unreadSince,
59259
- threadReplyCount,
59260
- threadUnreadCount,
59261
- threadUnreadSince
59262
- }
59263
- };
59264
- }
59265
- async handleMessage(data) {
58901
+ /**
58902
+ * One WorkItem the server pushed (dispatch.new) or a catch-up page
58903
+ * listed: messages ride their (chat, thread) lane; every other family
58904
+ * rides its own dsp lane, claimed, run on the server frame, resolved by
58905
+ * id. A typed WorkItem whose event copy is already buffered for the
58906
+ * drain is left to the drain (re-claiming it would race the drain's
58907
+ * fence-less settlement).
58908
+ */
58909
+ async consumeWorkItem(item) {
58910
+ await this.contractReady;
59266
58911
  if (this.shuttingDown)
59267
58912
  return;
59268
- const chatId = data.chat_id;
59269
- if (data.sender_id === this.opts.agentUserId)
59270
- return;
59271
- if (data.message_type !== "text")
59272
- return;
59273
- if (!this.tryClaimMessage(data.id))
59274
- return;
59275
- const decision = await this.buildMessageDispatchDecision(chatId, data);
59276
- if (decision.action !== "dispatch") {
59277
- this.dispatchedMessages.delete(data.id);
58913
+ if (item.event_type === "message") {
58914
+ if (!item.chat_id || !item.source_id)
58915
+ return;
58916
+ await this.consumeMessageWorkItem({
58917
+ id: item.id,
58918
+ source_id: item.source_id,
58919
+ chat_id: item.chat_id,
58920
+ actor_id: item.actor_id,
58921
+ thread_root_id: item.thread_root_id,
58922
+ delivery_reason: item.delivery_reason
58923
+ });
59278
58924
  return;
59279
58925
  }
59280
- const event = decision.event;
59281
- try {
59282
- const dispatched = await this.handleInboundEvent(event);
59283
- if (dispatched) {
59284
- if (!this.usesLaneLedger(event)) {
59285
- this.opts.client.ackDispatch(this.opts.config.org_id, { source_type: "message", source_id: data.id }).catch(() => {
59286
- });
59287
- }
59288
- } else {
59289
- this.dispatchedMessages.delete(data.id);
59290
- }
59291
- } catch (err) {
59292
- this.opts.log?.error(`event dispatch failed for ${data.id}: ${String(err)}`);
59293
- this.dispatchedMessages.delete(data.id);
59294
- }
59295
- }
59296
- // Ledger re-drive consumption: dispatch.new message hints re-enter the
59297
- // shared WorkItem consumption path (same protocol as catch-up).
59298
- async handleMessageRedrive(item) {
59299
- if (!item.chat_id || !item.source_id)
58926
+ if (!TYPED_EVENT_KINDS[item.event_type]) {
58927
+ this.opts.log?.info(`dispatch with unhandled event_type=${String(item.event_type)} (id=${item.id}) \u2014 no-op`);
59300
58928
  return;
59301
- await this.consumeMessageWorkItem({
59302
- id: item.id,
59303
- source_id: item.source_id,
59304
- chat_id: item.chat_id
59305
- });
59306
- }
59307
- // A task assignment's first delivery rides task.assigned, but a typed lane
59308
- // released without an effect is re-driven as dispatch.new. Reuse the exact
59309
- // typed claim path used by catch-up so that recovery does not require a
59310
- // runtime reconnect.
59311
- async handleTaskAssignmentRedrive(item) {
59312
- if (!item.task_id)
58929
+ }
58930
+ if (this.isBufferedTypedWorkItem(item.id)) {
58931
+ this.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping re-claim`);
59313
58932
  return;
59314
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
59315
- dispatchEventId
59316
- }), {
59317
- legacyAck: (dispatchEventId) => this.ackDispatchEvent(dispatchEventId ?? item.id, () => this.clearTypedDispatchDedupe(item)),
59318
- clearDedupe: () => this.clearTypedDispatchDedupe(item)
59319
- });
58933
+ }
58934
+ await this.consumeTypedDispatch({ dispatchEventId: item.id }, (lane) => this.runTypedFrame(item, lane), { legacyAck: () => this.ackDispatchEvent(item.id) });
59320
58935
  }
59321
58936
  consumeMessageWorkItem(item) {
59322
58937
  return consumeMessageWorkItem(this.laneFlowHost(), item);
59323
58938
  }
59324
- async handleTaskAssignment(task, ackSourceId, dispatchEventId) {
59325
- if (this.shuttingDown)
59326
- return false;
59327
- const dedupeKey = `${task.id}:${task.updated_at}`;
59328
- if (this.dispatchedTasks.has(dedupeKey)) {
59329
- this.opts.log?.info(`skipping already-dispatched task ${task.identifier ?? task.id}`);
59330
- return false;
59331
- }
59332
- this.dispatchedTasks.add(dedupeKey);
59333
- this.opts.log?.info(`task assigned: ${task.identifier ?? task.id} "${task.title}"`);
59334
- const parts = [`Title: ${task.title}`];
59335
- parts.push(`Status: ${task.status}`, `Priority: ${task.priority}`);
59336
- if (task.project_id)
59337
- parts.push(`Project: prll://${task.project_id}`);
59338
- if (task.parent_id)
59339
- parts.push(`Parent: prll://${task.parent_id}`);
59340
- if (task.description)
59341
- parts.push("", task.description);
59342
- const event = {
59343
- type: "task",
59344
- targetId: task.id,
59345
- targetName: task.identifier ?? void 0,
59346
- targetType: "task",
59347
- senderId: task.creator_id,
59348
- senderName: "system",
59349
- messageId: task.id,
59350
- body: parts.join("\n"),
59351
- sentAt: task.updated_at ?? task.created_at,
59352
- ackSourceType: "task_activity",
59353
- ackSourceId,
59354
- dispatchEventId
59355
- };
59356
- const dispatched = await this.handleInboundEvent(event);
59357
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59358
- this.dispatchedTasks.delete(dedupeKey);
59359
- }
59360
- return dispatched;
59361
- }
59362
- async handleTaskDispatch(taskId, ackSourceId, opts = {}) {
59363
- let task = null;
59364
- try {
59365
- task = await this.opts.client.getTask(this.opts.config.org_id, taskId);
59366
- } catch (err) {
59367
- const status = err?.status;
59368
- if (status === 404)
59369
- return true;
59370
- throw err;
59371
- }
59372
- const isAssignee = task.assignee_id === this.opts.agentUserId;
59373
- const isCreatorUpdate = opts.allowCreator === true && task.creator_id === this.opts.agentUserId;
59374
- if (!isAssignee && !isCreatorUpdate) {
59375
- this.opts.log?.info(`skipping stale task dispatch ${ackSourceId ?? taskId} \u2014 assigned to ${task.assignee_id}, creator ${task.creator_id}`);
59376
- return true;
59377
- }
59378
- return this.handleTaskAssignment(task, ackSourceId, opts.dispatchEventId);
59379
- }
59380
- async handleTaskComment(commentId, taskId, actorId, deliveryReason, dispatchEventId) {
59381
- if (this.shuttingDown)
59382
- return false;
59383
- const dedupeKey = `comment:${commentId}`;
59384
- if (this.dispatchedTasks.has(dedupeKey))
59385
- return false;
59386
- this.dispatchedTasks.add(dedupeKey);
59387
- let comment = null;
59388
- try {
59389
- comment = await this.opts.client.getComment(this.opts.config.org_id, commentId);
59390
- } catch (err) {
59391
- const status = err?.status;
59392
- if (status === 404) {
59393
- this.opts.log?.info(`skipping deleted comment ${commentId}, acking stale dispatch`);
59394
- this.dispatchedTasks.delete(dedupeKey);
59395
- return true;
59396
- }
59397
- this.dispatchedTasks.delete(dedupeKey);
59398
- return false;
59399
- }
59400
- if (!comment) {
59401
- this.dispatchedTasks.delete(dedupeKey);
59402
- return true;
59403
- }
59404
- if (comment.hints?.no_reply) {
59405
- this.opts.log?.info(`skipping no_reply task comment ${commentId}, acking stale dispatch`);
59406
- this.dispatchedTasks.delete(dedupeKey);
59407
- return true;
59408
- }
59409
- let task = null;
59410
- try {
59411
- task = await this.opts.client.getTask(this.opts.config.org_id, taskId);
59412
- } catch {
59413
- }
59414
- const taskLabel = task ? `${task.identifier ?? task.id} "${task.title}"` : taskId;
59415
- this.opts.log?.info(`task comment on ${taskLabel} by ${actorId ?? "unknown"}`);
59416
- const parts = [];
59417
- if (task) {
59418
- parts.push(`Task: ${task.title} (prll://${task.id})`);
59419
- parts.push(`Status: ${task.status}`, `Priority: ${task.priority}`);
59420
- } else {
59421
- parts.push(`Task: prll://${taskId}`);
59422
- }
59423
- parts.push(`Comment by: ${comment.author?.display_name ?? actorId ?? "unknown"} (prll://${comment.author_id})`);
59424
- parts.push("", comment.body);
59425
- const event = {
59426
- type: "task_comment",
59427
- targetId: taskId,
59428
- targetName: task?.identifier ?? void 0,
59429
- targetType: "task",
59430
- senderId: comment.author_id,
59431
- senderName: comment.author?.display_name ?? actorId ?? "unknown",
59432
- messageId: commentId,
59433
- body: parts.join("\n"),
59434
- deliveryReason: deliveryReason ?? void 0,
59435
- ackSourceType: "comment",
59436
- ackSourceId: commentId,
59437
- dispatchEventId
59438
- };
59439
- let dispatched;
59440
- try {
59441
- dispatched = await this.handleInboundEvent(event);
59442
- } catch (err) {
59443
- this.dispatchedTasks.delete(dedupeKey);
59444
- throw err;
59445
- }
59446
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59447
- this.dispatchedTasks.delete(dedupeKey);
59448
- }
59449
- return dispatched;
59450
- }
59451
- async handleWikiComment(commentId, actorId, deliveryReason, dispatchEventId) {
59452
- if (this.shuttingDown)
59453
- return false;
59454
- const dedupeKey = `comment:${commentId}`;
59455
- if (this.dispatchedTasks.has(dedupeKey))
59456
- return false;
59457
- this.dispatchedTasks.add(dedupeKey);
59458
- let comment = null;
59459
- try {
59460
- comment = await this.opts.client.getComment(this.opts.config.org_id, commentId);
59461
- } catch (err) {
59462
- const status = err?.status;
59463
- if (status === 404 || status === 403) {
59464
- this.opts.log?.info(`skipping inaccessible wiki comment ${commentId} (status ${status}), acking stale dispatch`);
59465
- this.dispatchedTasks.delete(dedupeKey);
59466
- return true;
59467
- }
59468
- this.dispatchedTasks.delete(dedupeKey);
59469
- return false;
59470
- }
59471
- if (!comment) {
59472
- this.dispatchedTasks.delete(dedupeKey);
59473
- return true;
59474
- }
59475
- if (comment.hints?.no_reply) {
59476
- this.opts.log?.info(`skipping no_reply wiki comment ${commentId}, acking stale dispatch`);
59477
- this.dispatchedTasks.delete(dedupeKey);
59478
- return true;
59479
- }
59480
- const target = parseWikiCommentTarget(comment.target_uri);
59481
- this.opts.log?.info(`wiki comment on ${target.label} by ${actorId ?? "unknown"}`);
59482
- const event = {
59483
- type: "wiki_comment",
59484
- // Full target_uri (scheme-stripped) is the routing key so different
59485
- // pages / inline anchors / changesets in the same wiki don't collide on
59486
- // one gateway lane. replyTargetUri keeps the canonical prll:// form.
59487
- targetId: target.routingKey,
59488
- targetName: target.label,
59489
- targetType: target.targetType,
59490
- senderId: comment.author_id,
59491
- senderName: comment.author?.display_name ?? actorId ?? "unknown",
59492
- messageId: commentId,
59493
- body: comment.body,
59494
- deliveryReason: deliveryReason ?? void 0,
59495
- replyTargetUri: comment.target_uri,
59496
- ackSourceType: "comment",
59497
- ackSourceId: commentId,
59498
- dispatchEventId
59499
- };
59500
- let dispatched;
59501
- try {
59502
- dispatched = await this.handleInboundEvent(event);
59503
- } catch (err) {
59504
- this.dispatchedTasks.delete(dedupeKey);
59505
- throw err;
59506
- }
59507
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59508
- this.dispatchedTasks.delete(dedupeKey);
59509
- }
59510
- return dispatched;
59511
- }
59512
58939
  /**
59513
- * Fetch the schedule_run snapshot, then feed it as an inbound event. 404 is
59514
- * tolerated and treated as "dispatched" so the caller can ack the stale
59515
- * deliverysee `docs/primitives/schedule.md` § "Snapshot 不变性: 内容 vs
59516
- * 可见性". A later PATCH on target_id / attached_to_uri legitimately revokes
59517
- * access to already-delivered run snapshots, and the runtime must not crash
59518
- * or retry forever in that case.
58940
+ * Run one claimed typed WorkItem on the frame the claim returned. The
58941
+ * event is addressing only: the routing target the server named
58942
+ * (`input.subject`the task, the wiki target, the schedule, the
58943
+ * conversation, the chat an approval belongs to), the ids the ledger
58944
+ * keys on, and the input-step metadata. No frame means nothing to run.
59519
58945
  */
59520
- async fetchAndHandleScheduleFire(runId, actorId, dispatchEventId) {
59521
- let run = null;
59522
- try {
59523
- run = await this.opts.client.getScheduleRun(this.opts.config.org_id, runId);
59524
- } catch (err) {
59525
- const status = err?.status;
59526
- if (status === 404) {
59527
- this.opts.log?.warn(`schedule run ${runId} not accessible (404), acking stale dispatch`);
59528
- return true;
59529
- }
59530
- this.opts.log?.warn(`schedule run fetch failed for ${runId}, leaving pending: ${String(err)}`);
59531
- return false;
59532
- }
59533
- if (!run)
59534
- return true;
59535
- return this.handleScheduleFire(run, actorId, dispatchEventId);
59536
- }
59537
- async handleScheduleFire(run, actorId, dispatchEventId) {
59538
- if (this.shuttingDown)
59539
- return false;
59540
- const dedupeKey = `schedule_run:${run.id}`;
59541
- if (this.dispatchedTasks.has(dedupeKey))
59542
- return false;
59543
- this.dispatchedTasks.add(dedupeKey);
59544
- this.opts.log?.info(`schedule fired: ${run.id} (schedule ${run.schedule_id})`);
59545
- const event = {
59546
- type: "schedule",
59547
- // Route by schedule_id (not attached chat_id) so concurrent fires of
59548
- // different schedules can fork independently — matches the PR1 primitive
59549
- // design where "schedule triggers; target decides response" and fire
59550
- // semantics are independent of any attached conversation.
59551
- targetId: run.schedule_id,
59552
- targetType: "schedule",
59553
- senderId: actorId ?? "system",
59554
- senderName: "schedule",
59555
- messageId: run.id,
59556
- body: run.fired_description ?? "",
59557
- scheduledFireAt: run.scheduled_fire_at,
59558
- attachedUri: run.fired_attached_uri ?? void 0,
59559
- ackSourceType: "schedule_run",
59560
- ackSourceId: run.id,
59561
- dispatchEventId
59562
- };
59563
- let dispatched;
59564
- try {
59565
- dispatched = await this.handleInboundEvent(event);
59566
- } catch (err) {
59567
- this.dispatchedTasks.delete(dedupeKey);
59568
- throw err;
59569
- }
59570
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59571
- this.dispatchedTasks.delete(dedupeKey);
59572
- }
59573
- return dispatched;
59574
- }
59575
- async fetchAndHandleExternalTriggerRun(runId, dispatchEventId) {
59576
- let run = null;
59577
- try {
59578
- run = await this.opts.client.getExternalTriggerRun(this.opts.config.org_id, runId);
59579
- } catch (err) {
59580
- const status = err?.status;
59581
- if (status === 404) {
59582
- this.opts.log?.warn(`external trigger run ${runId} not accessible (404), acking stale dispatch`);
59583
- return true;
59584
- }
59585
- this.opts.log?.warn(`external trigger run fetch failed for ${runId}, leaving pending: ${String(err)}`);
59586
- return false;
59587
- }
59588
- if (!run)
59589
- return true;
59590
- return this.handleExternalTriggerRun(run, dispatchEventId);
59591
- }
59592
- // fetchAndHandleChannelMessage resolves a channel_message dispatch to its
59593
- // durable ChannelMessage + conversation and hands it to the inbound
59594
- // pipeline. targetId = the ChannelConversation id, so per-conversation
59595
- // multi-turn continuity rides the same per-target session mechanics as
59596
- // chats. Design: docs/engineering-design/external-im-channel-design.md.
59597
- async fetchAndHandleChannelMessage(messageId, dispatchEventId) {
59598
- if (this.shuttingDown)
59599
- return false;
59600
- const claimKey = `channel_message:${messageId}`;
59601
- if (!this.tryClaimMessage(claimKey))
59602
- return false;
59603
- let msg = null;
59604
- let conv = null;
59605
- try {
59606
- msg = await this.opts.client.getChannelMessage(this.opts.config.org_id, messageId);
59607
- conv = await this.opts.client.getChannelConversation(this.opts.config.org_id, msg.conversation_id);
59608
- } catch (err) {
59609
- const status = err?.status;
59610
- if (status === 404) {
59611
- this.opts.log?.warn(`channel message ${messageId} not accessible (404), acking stale dispatch`);
59612
- return true;
59613
- }
59614
- this.dispatchedMessages.delete(claimKey);
59615
- this.opts.log?.warn(`channel message fetch failed for ${messageId}, leaving pending: ${String(err)}`);
59616
- return false;
59617
- }
59618
- if (!msg || !conv) {
59619
- return true;
59620
- }
59621
- this.opts.log?.info(`channel message: ${msg.id} (conversation ${conv.id})`);
59622
- let provider = this.channelConnectionProviders.get(conv.connection_id);
59623
- if (!provider) {
59624
- try {
59625
- const connection = await this.opts.client.getChannelConnection(this.opts.config.org_id, conv.connection_id);
59626
- provider = connection.provider;
59627
- this.channelConnectionProviders.set(conv.connection_id, provider);
59628
- } catch {
59629
- provider = void 0;
59630
- }
59631
- }
59632
- const keys = this.opts.getCapabilityKeys?.() ?? [];
59633
- const cliCapable = provider ? keys.includes(channelCapabilityKeyFor(provider)) : keys.some((k) => k.endsWith("-cli") || k === CAPABILITY_SLACK_SEND || k === CAPABILITY_WECHAT_SEND);
59634
- const event = {
59635
- type: "channel_message",
59636
- targetId: conv.id,
59637
- targetName: conv.external_conversation_name || conv.external_user_name || conv.external_conversation_id,
59638
- targetType: "channel_conversation",
59639
- senderId: msg.external_user_id || "external",
59640
- senderName: msg.external_user_name || msg.external_user_id || "external user",
59641
- messageId: msg.id,
59642
- body: msg.text,
59643
- sentAt: msg.received_at,
59644
- channelProvider: provider,
59645
- channelConversationType: conv.conversation_type || void 0,
59646
- channelExternalConversationId: conv.external_conversation_id,
59647
- channelExternalConversationName: conv.external_conversation_name || void 0,
59648
- channelExternalMessageId: msg.external_message_id,
59649
- channelCliCapable: cliCapable,
59650
- ackSourceType: "channel_message",
59651
- ackSourceId: msg.id,
59652
- dispatchEventId
59653
- };
59654
- let dispatched;
59655
- try {
59656
- dispatched = await this.handleInboundEvent(event);
59657
- } catch (err) {
59658
- this.dispatchedMessages.delete(claimKey);
59659
- throw err;
59660
- }
59661
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59662
- this.dispatchedMessages.delete(claimKey);
59663
- }
59664
- return dispatched;
59665
- }
59666
- async handleExternalTriggerRun(run, dispatchEventId) {
58946
+ async runTypedFrame(item, lane) {
59667
58947
  if (this.shuttingDown)
59668
58948
  return false;
59669
- const dedupeKey = `external_trigger_run:${run.id}`;
59670
- if (this.dispatchedTasks.has(dedupeKey))
59671
- return false;
59672
- this.dispatchedTasks.add(dedupeKey);
59673
- this.opts.log?.info(`external trigger fired: ${run.id} (trigger ${run.trigger_id})`);
59674
- const attachedUri = typeof run.trigger_snapshot?.attached_to_uri === "string" ? run.trigger_snapshot.attached_to_uri : void 0;
59675
- const event = {
59676
- type: "external_trigger",
59677
- targetId: run.trigger_id,
59678
- targetName: run.trigger_name || void 0,
59679
- targetType: "external_trigger",
59680
- senderId: "system",
59681
- senderName: "external",
59682
- messageId: run.id,
59683
- body: run.agent_input_body ?? "",
59684
- externalConnectionId: run.connection_id,
59685
- externalConnectionSourceType: run.connection_source_type || void 0,
59686
- externalConnectionDisplayName: run.connection_display_name || void 0,
59687
- externalIngressEventId: run.ingress_event_id,
59688
- externalIngressEventType: run.ingress_event_type || void 0,
59689
- attachedUri,
59690
- ackSourceType: "external_trigger_run",
59691
- ackSourceId: run.id,
59692
- dispatchEventId
59693
- };
59694
- let dispatched;
59695
- try {
59696
- dispatched = await this.handleInboundEvent(event);
59697
- } catch (err) {
59698
- this.dispatchedTasks.delete(dedupeKey);
59699
- throw err;
59700
- }
59701
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59702
- this.dispatchedTasks.delete(dedupeKey);
59703
- }
59704
- return dispatched;
59705
- }
59706
- async fetchAndHandleApprovalDecided(approvalId, actorId, chatId, dispatchEventId) {
59707
- let approval = null;
59708
- try {
59709
- approval = await this.opts.client.getApproval(approvalId);
59710
- } catch (err) {
59711
- const status = err?.status;
59712
- if (status === 404 || status === 403) {
59713
- this.opts.log?.warn(`approval ${approvalId} not accessible (${status}), acking stale dispatch`);
59714
- return true;
59715
- }
59716
- this.opts.log?.warn(`approval fetch failed for ${approvalId}, leaving pending: ${String(err)}`);
58949
+ const wake = this.laneLedger?.takeFrame(lane);
58950
+ if (!wake?.frame) {
58951
+ this.opts.log?.warn(`typed dispatch ${item.id} (${String(item.event_type)}) claimed without a frame \u2014 leaving it pending`);
59717
58952
  return false;
59718
58953
  }
59719
- if (!approval)
59720
- return true;
59721
- if (this.shuttingDown)
59722
- return false;
59723
- const dedupeKey = `approval:${approval.id}`;
59724
- if (this.dispatchedTasks.has(dedupeKey))
59725
- return false;
59726
- this.dispatchedTasks.add(dedupeKey);
59727
- this.opts.log?.info(`approval decided: ${approval.id} (${approval.status})`);
59728
- const statusLabel = approval.status === "approved" ? "Approved" : "Rejected";
59729
- const execInfo = approval.execution_status ? ` | execution: ${approval.execution_status}` : "";
59730
- const reasonLine = formatApprovalDecisionReason(approval.status, approval.decision_reason);
59731
- const reasonInfo = reasonLine ? `
59732
- ${reasonLine}` : "";
59733
- const body = `${statusLabel}: ${approval.title}${execInfo}${reasonInfo}`;
58954
+ const kind = TYPED_EVENT_KINDS[item.event_type];
58955
+ const targetId = wake.input?.subject || item.task_id || item.chat_id || item.source_id || item.id;
59734
58956
  const event = {
59735
- type: "approval",
59736
- targetId: chatId ?? approval.chat_id,
59737
- senderId: actorId ?? approval.decided_by ?? "system",
59738
- senderName: "approver",
59739
- messageId: approval.id,
59740
- body,
59741
- // The WorkItem's real source pair. Without it the legacy fallback
59742
- // guessed ('message', approval_id) — a pair no row matches.
59743
- ackSourceType: "approval",
59744
- ackSourceId: approval.id,
59745
- dispatchEventId
59746
- };
59747
- let dispatched;
59748
- try {
59749
- dispatched = await this.handleInboundEvent(event);
59750
- } catch (err) {
59751
- this.dispatchedTasks.delete(dedupeKey);
59752
- throw err;
59753
- }
59754
- if (!dispatched && !this.isTypedEventBuffered(event)) {
59755
- this.dispatchedTasks.delete(dedupeKey);
59756
- }
59757
- return dispatched;
58957
+ type: kind.type,
58958
+ targetId,
58959
+ targetType: wake.input?.step_target?.type,
58960
+ senderId: wake.input?.sender_id ?? item.actor_id ?? "system",
58961
+ messageId: item.source_id,
58962
+ deliveryReason: item.delivery_reason ?? void 0,
58963
+ ackSourceType: kind.ackSourceType,
58964
+ ackSourceId: item.source_id,
58965
+ dispatchEventId: item.id
58966
+ };
58967
+ applyWake(event, wake);
58968
+ this.opts.log?.info(`${String(item.event_type)} ${item.source_id} \u2192 ${targetId}`);
58969
+ return this.handleInboundEvent(event);
59758
58970
  }
59759
58971
  async catchUpFromDispatch() {
59760
58972
  const OVERFLOW_THRESHOLD = 500;
@@ -59808,54 +59020,9 @@ ${reasonLine}` : "";
59808
59020
  }
59809
59021
  continue;
59810
59022
  }
59811
- if (item.event_type !== "message" && this.isBufferedTypedWorkItem(item.id)) {
59812
- this.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping catch-up claim`);
59813
- continue;
59814
- }
59815
59023
  processed++;
59816
59024
  try {
59817
- const typedHooks = {
59818
- legacyAck: () => this.ackDispatchEvent(item.id, () => this.clearTypedDispatchDedupe(item)),
59819
- clearDedupe: () => this.clearTypedDispatchDedupe(item)
59820
- };
59821
- if (item.event_type === "task_assign" && item.task_id) {
59822
- try {
59823
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
59824
- dispatchEventId
59825
- }), typedHooks);
59826
- } catch (err) {
59827
- this.opts.log?.warn(`catch-up task fetch failed for ${item.task_id}, leaving pending: ${String(err)}`);
59828
- continue;
59829
- }
59830
- } else if (item.event_type === "task_update" && item.task_id) {
59831
- try {
59832
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskDispatch(item.task_id ?? "", item.source_id ?? item.task_id ?? "", {
59833
- allowCreator: true,
59834
- dispatchEventId
59835
- }), typedHooks);
59836
- } catch (err) {
59837
- this.opts.log?.warn(`catch-up task fetch failed for ${item.task_id}, leaving pending: ${String(err)}`);
59838
- continue;
59839
- }
59840
- } else if (item.event_type === "task_comment" && item.source_id && item.task_id) {
59841
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleTaskComment(item.source_id, item.task_id ?? "", item.actor_id, item.delivery_reason, dispatchEventId), typedHooks);
59842
- } else if (item.event_type === "wiki_comment" && item.source_id) {
59843
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.handleWikiComment(item.source_id, item.actor_id, item.delivery_reason, dispatchEventId), typedHooks);
59844
- } else if (item.event_type === "schedule.fire" && item.source_id) {
59845
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleScheduleFire(item.source_id, item.actor_id, dispatchEventId), typedHooks);
59846
- } else if (item.event_type === "external_trigger" && item.source_id) {
59847
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleExternalTriggerRun(item.source_id, dispatchEventId), typedHooks);
59848
- } else if (item.event_type === "channel_message" && item.source_id) {
59849
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleChannelMessage(item.source_id, dispatchEventId), typedHooks);
59850
- } else if (item.event_type === "approval_decided" && item.source_id) {
59851
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (dispatchEventId) => this.fetchAndHandleApprovalDecided(item.source_id, item.actor_id, item.chat_id ?? null, dispatchEventId), typedHooks);
59852
- } else if (item.event_type === "message" && item.source_id && item.chat_id) {
59853
- await this.consumeMessageWorkItem({
59854
- id: item.id,
59855
- source_id: item.source_id,
59856
- chat_id: item.chat_id
59857
- });
59858
- }
59025
+ await this.consumeWorkItem(item);
59859
59026
  } catch (err) {
59860
59027
  this.opts.log?.warn(`catch-up dispatch ${item.id} (${item.event_type}) failed: ${String(err)}`);
59861
59028
  }
@@ -59928,9 +59095,18 @@ ${fullSummary}` : fullSummary;
59928
59095
  this.ledgerDisabled = false;
59929
59096
  }
59930
59097
  const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
59098
+ let openFence = () => {
59099
+ };
59100
+ this.contractReady = new Promise((resolve3) => {
59101
+ openFence = resolve3;
59102
+ });
59931
59103
  try {
59932
- const count = await fetchAllChats(client, config.org_id, this.chatInfoMap);
59933
- log2?.info(`WebSocket connected, ${count} chats cached`);
59104
+ log2?.info("WebSocket connected");
59105
+ try {
59106
+ await this.declareRuntimeContract();
59107
+ } finally {
59108
+ openFence();
59109
+ }
59934
59110
  await this.opts.onSessionReady?.({
59935
59111
  activeSessionId: this.activeSessionId,
59936
59112
  ws: this.opts.ws,
@@ -59964,6 +59140,44 @@ ${fullSummary}` : fullSummary;
59964
59140
  log2?.error(`failed to fetch chats: ${String(err)}`);
59965
59141
  }
59966
59142
  }
59143
+ /**
59144
+ * Declare the runtime contract for this connection: the server decides
59145
+ * who runs and renders the wake frame; this runtime only runs. Bound to
59146
+ * the WS session id, so it repeats on every hello. Retried with backoff
59147
+ * until it lands — WorkItems wait behind the fence meanwhile, nothing is
59148
+ * claimed without a frame. A server without the endpoint renders no
59149
+ * frames: the runtime runs nothing and WorkItems stay pending. A
59150
+ * stale-session 409 means a newer connection already declared.
59151
+ */
59152
+ async declareRuntimeContract() {
59153
+ const session = this.sessionId;
59154
+ if (!session)
59155
+ return;
59156
+ for (let attempt = 0; ; attempt++) {
59157
+ try {
59158
+ await this.opts.client.declareReplyPolicyCapability(this.opts.config.org_id, session);
59159
+ this.opts.log?.info("runtime contract declared (server-rendered frames)");
59160
+ return;
59161
+ } catch (err) {
59162
+ if (err instanceof ApiError && err.status === 404) {
59163
+ this.opts.log?.warn("server predates the runtime contract \u2014 it renders no wake frames; WorkItems stay pending");
59164
+ return;
59165
+ }
59166
+ if (err instanceof ApiError && err.status === 409) {
59167
+ this.opts.log?.info("runtime contract already declared by a newer connection");
59168
+ return;
59169
+ }
59170
+ const delayMs = Math.min(3e4, 2e3 * 2 ** Math.min(attempt, 4));
59171
+ this.opts.log?.warn(`runtime contract declaration failed (retry in ${delayMs / 1e3}s): ${String(err)}`);
59172
+ await new Promise((resolve3) => {
59173
+ const timer = setTimeout(resolve3, delayMs);
59174
+ timer.unref?.();
59175
+ });
59176
+ if (this.shuttingDown || this.sessionId !== session)
59177
+ return;
59178
+ }
59179
+ }
59180
+ }
59967
59181
  // Resolves when in-flight dispatches hit 0 or the deadline elapses.
59968
59182
  // Deadline arming the resolver rather than rejecting keeps shutdown() linear
59969
59183
  // — callers don't need to try/catch.
@@ -60082,6 +59296,14 @@ function resolveRuntimeModel(isOperatorOverride, platformModel, configModel) {
60082
59296
  const operatorOverride = isOperatorOverride ? platformModel : null;
60083
59297
  return operatorOverride ?? configModel ?? platformModel ?? void 0;
60084
59298
  }
59299
+ function resolveRuntimeContextWindow(resolvedModel, defaults, llmSource2) {
59300
+ if (llmSource2 !== "parall")
59301
+ return void 0;
59302
+ if (!resolvedModel || resolvedModel !== defaults.model)
59303
+ return void 0;
59304
+ const contextWindow = defaults.contextWindow;
59305
+ return typeof contextWindow === "number" && Number.isSafeInteger(contextWindow) && contextWindow > 0 ? contextWindow : void 0;
59306
+ }
60085
59307
  function deriveModelIsPin(defaults, profile) {
60086
59308
  return defaults.modelIsPin !== void 0 ? defaults.modelIsPin : isPlatformModelOverride(profile);
60087
59309
  }
@@ -60111,36 +59333,46 @@ function saveCache(stateDir, response) {
60111
59333
  fs4.writeFileSync(tmpPath, JSON.stringify(cached, null, 2), "utf-8");
60112
59334
  fs4.renameSync(tmpPath, filePath);
60113
59335
  }
60114
- function runtimeModelName(canonicalModel, runtimeType, config) {
59336
+ function runtimeModelConfig(canonicalModel, runtimeType, config) {
60115
59337
  const runtime = runtimeType?.trim();
60116
- if (!runtime || runtime === "openclaw" || runtime === "hermes")
60117
- return canonicalModel;
60118
59338
  const models = config.models ?? {};
60119
59339
  const providers = models.providers ?? {};
60120
59340
  const parall = providers.parall ?? {};
60121
59341
  const catalog = Array.isArray(parall.models) ? parall.models : [];
60122
59342
  const match = catalog.find((model) => model.id === canonicalModel);
60123
- if (!match)
60124
- return null;
59343
+ if (!match) {
59344
+ return !runtime || runtime === "openclaw" || runtime === "hermes" ? { model: canonicalModel, contextWindow: null } : null;
59345
+ }
59346
+ const contextWindow = typeof match.contextWindow === "number" && Number.isSafeInteger(match.contextWindow) && match.contextWindow > 0 ? match.contextWindow : null;
59347
+ if (!runtime || runtime === "openclaw" || runtime === "hermes") {
59348
+ return { model: canonicalModel, contextWindow };
59349
+ }
60125
59350
  const runtimeNames = match.runtime_names ?? {};
60126
59351
  const runtimeName = runtimeNames[runtime];
60127
- if (typeof runtimeName === "string" && runtimeName)
60128
- return runtimeName;
60129
- return canonicalModel;
59352
+ if (typeof runtimeName === "string" && runtimeName) {
59353
+ return {
59354
+ model: runtimeName,
59355
+ contextWindow: runtimeName === canonicalModel ? contextWindow : null
59356
+ };
59357
+ }
59358
+ return { model: canonicalModel, contextWindow };
60130
59359
  }
60131
59360
  function extractDefaults(config, runtimeType) {
60132
59361
  const agents = config.agents ?? {};
60133
59362
  const defaults = agents.defaults ?? {};
60134
59363
  let model = null;
59364
+ let contextWindow = null;
60135
59365
  if (typeof defaults.model === "string" && defaults.model) {
60136
59366
  const canonicalModel = defaults.model.replace(/^parall-anthropic\//, "").replace(/^parall\//, "");
60137
- model = runtimeModelName(canonicalModel, runtimeType, config);
59367
+ const resolved = runtimeModelConfig(canonicalModel, runtimeType, config);
59368
+ model = resolved?.model ?? null;
59369
+ contextWindow = resolved?.contextWindow ?? null;
60138
59370
  }
60139
59371
  let thinkingEffort = null;
60140
59372
  if (typeof defaults.thinking_effort === "string" && defaults.thinking_effort) {
60141
59373
  thinkingEffort = defaults.thinking_effort;
60142
59374
  }
60143
- return { model, thinkingEffort };
59375
+ return { model, thinkingEffort, contextWindow };
60144
59376
  }
60145
59377
  function createPlatformConfigManager(opts) {
60146
59378
  const { client, stateDir, runtimeType, log: log2 } = opts;
@@ -60148,6 +59380,7 @@ function createPlatformConfigManager(opts) {
60148
59380
  let currentDefaults = {
60149
59381
  model: null,
60150
59382
  thinkingEffort: null,
59383
+ contextWindow: null,
60151
59384
  modelIsPin: void 0
60152
59385
  };
60153
59386
  let currentRawConfig = null;
@@ -60422,7 +59655,9 @@ parall approvals wait prll://apr_xxx --timeout 300
60422
59655
  # List all your pending approvals
60423
59656
  parall approvals list
60424
59657
 
60425
- # List available approvable actions
59658
+ # List available approvable actions \u2014 the output includes each documented
59659
+ # action's payload contract (exact field names, and where a CAS base like
59660
+ # expected_version is read from). Check it before hand-writing a --payload.
60426
59661
  parall approvals actions
60427
59662
 
60428
59663
  # Cancel a pending request you made
@@ -60608,8 +59843,19 @@ parall tasks update prll://tsk_xxx --planned-start none
60608
59843
  # Move a task to the end of its status column
60609
59844
  parall tasks update prll://tsk_xxx --placement end
60610
59845
 
60611
- # Add a comment
60612
- parall tasks comments add prll://tsk_xxx --body "Progress update..."
59846
+ # Add a comment \u2014 same shell rules as messages: the body runs through a
59847
+ # shell, so pass real content via --body-file (a written file, or a quoted
59848
+ # heredoc into stdin with '-'). --body "..." only for short literals with
59849
+ # no $, backtick, or quote (single or double). A bare --body - is refused,
59850
+ # not stdin.
59851
+ parall tasks comments add prll://tsk_xxx --body-file - <<'PARALL_EOF'
59852
+ Progress update: fixed the $1,000 rounding bug, it's in review.
59853
+ PARALL_EOF
59854
+ parall tasks comments add prll://tsk_xxx --body-file /tmp/comment.md
59855
+ parall tasks comments add prll://tsk_xxx --body "On it"
59856
+
59857
+ # Long or multi-line description \u2192 same file / stdin channel
59858
+ parall tasks create --title "Write the runbook" --project-id prll://prj_xxx --description-file /tmp/description.md
60613
59859
  \`\`\`
60614
59860
 
60615
59861
  Ordering: to append a task to the end of a status column, always use
@@ -60686,7 +59932,7 @@ When you receive \`[Event: task.comment.created]\`, someone commented on a task
60686
59932
 
60687
59933
  1. Resolve the project and read its current description as described above
60688
59934
  2. Review the comment content and task context
60689
- 3. Reply via comment: \`tasks comments add prll://tsk_xxx --body "Response..."\`
59935
+ 3. Reply via comment: \`tasks comments add prll://tsk_xxx --body-file -\` with a quoted heredoc (\`--body "..."\` only for short literals with no \`$\`, backtick, or quote \u2014 single or double)
60690
59936
  4. If the comment requests status changes, update accordingly
60691
59937
 
60692
59938
  CLI success output is JSON; errors print a JSON line plus, on a \`PERMISSION_DENIED\`, an optional plain-text \`Request approval:\` line \u2014 read both.
@@ -61720,10 +60966,10 @@ function stepIdFilePathForSession(stateDir, sessionKey) {
61720
60966
  }
61721
60967
 
61722
60968
  // ts/claude-agent/dist/dispatch.js
61723
- import * as fs7 from "node:fs";
61724
- import * as path8 from "node:path";
61725
- import { randomUUID as randomUUID3 } from "node:crypto";
61726
60969
  import { execSync as execSync2, spawn } from "node:child_process";
60970
+ import { randomUUID as randomUUID3 } from "node:crypto";
60971
+ import * as fs7 from "node:fs";
60972
+ import * as path9 from "node:path";
61727
60973
 
61728
60974
  // ts/agent-core/dist/internal/attachment-input.js
61729
60975
  import { execSync } from "node:child_process";
@@ -62660,6 +61906,48 @@ function extractResultMeta(frame, isError, numTurns) {
62660
61906
  return meta;
62661
61907
  }
62662
61908
 
61909
+ // ts/claude-agent/dist/spawn-env.js
61910
+ import * as path8 from "node:path";
61911
+ function buildSpawnEnv(parentEnv, claudeHome, context2, opts) {
61912
+ const env = { ...parentEnv };
61913
+ if (!opts.allowApiKey) {
61914
+ delete env.ANTHROPIC_API_KEY;
61915
+ delete env.ANTHROPIC_AUTH_TOKEN;
61916
+ }
61917
+ const result = {
61918
+ ...env,
61919
+ HOME: claudeHome,
61920
+ PRLL_API_URL: context2.apiUrl,
61921
+ PRLL_API_KEY: context2.apiKey,
61922
+ PRLL_ORG_ID: context2.orgId,
61923
+ PRLL_SESSION_ID: context2.sessionId ?? "",
61924
+ PRLL_CHAT_ID: context2.chatId ?? "",
61925
+ PRLL_TRIGGER_MESSAGE_ID: context2.triggerMessageId ?? "",
61926
+ PRLL_NO_REPLY: context2.noReply ? "1" : "",
61927
+ PRLL_CONTEXT_FILE: context2.contextFilePath ?? "",
61928
+ PRLL_STEP_ID_FILE: context2.stepIdFilePath ?? "",
61929
+ // Per-lane dispatch context directory (stable for the bridge's lifetime,
61930
+ // so pinning it at spawn is safe even for long-lived subprocesses). The
61931
+ // CLI keys into it by send target to derive dispatch effect keys.
61932
+ PRLL_CONTEXT_DIR: context2.contextDirPath ?? ""
61933
+ };
61934
+ if (!result.PRLL_WIKI_MOUNT_ROOT?.trim() && opts.wikiMountRoot) {
61935
+ result.PRLL_WIKI_MOUNT_ROOT = opts.wikiMountRoot;
61936
+ }
61937
+ if (opts.effortLevel) {
61938
+ result.CLAUDE_CODE_EFFORT_LEVEL = opts.effortLevel;
61939
+ }
61940
+ if (typeof opts.contextWindow === "number" && Number.isSafeInteger(opts.contextWindow) && opts.contextWindow > 0) {
61941
+ result.CLAUDE_CODE_MAX_CONTEXT_TOKENS = String(opts.contextWindow);
61942
+ }
61943
+ if (opts.capabilityBinDir) {
61944
+ const pathKey = process.platform === "win32" ? Object.keys(result).find((k) => k.toUpperCase() === "PATH") ?? "PATH" : "PATH";
61945
+ const existing = result[pathKey];
61946
+ result[pathKey] = existing ? `${opts.capabilityBinDir}${path8.delimiter}${existing}` : opts.capabilityBinDir;
61947
+ }
61948
+ return result;
61949
+ }
61950
+
62663
61951
  // ts/claude-agent/dist/turn-outcome.js
62664
61952
  var LIMIT_TEXT = /you'?ve (hit|reached) your .*limit|usage limit reached|weekly limit/i;
62665
61953
  var AUTH_TEXT = /not logged in|please run \/login|authentication_error|invalid api key|oauth token (has )?expired|\[action required\]/i;
@@ -62803,42 +62091,6 @@ function killWin32Tree(pid) {
62803
62091
  return false;
62804
62092
  }
62805
62093
  }
62806
- function buildSpawnEnv(parentEnv, claudeHome, context2, opts) {
62807
- const env = { ...parentEnv };
62808
- if (!opts.allowApiKey) {
62809
- delete env.ANTHROPIC_API_KEY;
62810
- delete env.ANTHROPIC_AUTH_TOKEN;
62811
- }
62812
- const result = {
62813
- ...env,
62814
- HOME: claudeHome,
62815
- PRLL_API_URL: context2.apiUrl,
62816
- PRLL_API_KEY: context2.apiKey,
62817
- PRLL_ORG_ID: context2.orgId,
62818
- PRLL_SESSION_ID: context2.sessionId ?? "",
62819
- PRLL_CHAT_ID: context2.chatId ?? "",
62820
- PRLL_TRIGGER_MESSAGE_ID: context2.triggerMessageId ?? "",
62821
- PRLL_NO_REPLY: context2.noReply ? "1" : "",
62822
- PRLL_CONTEXT_FILE: context2.contextFilePath ?? "",
62823
- PRLL_STEP_ID_FILE: context2.stepIdFilePath ?? "",
62824
- // Per-lane dispatch context directory (stable for the bridge's lifetime,
62825
- // so pinning it at spawn is safe even for long-lived subprocesses). The
62826
- // CLI keys into it by send target to derive dispatch effect keys.
62827
- PRLL_CONTEXT_DIR: context2.contextDirPath ?? ""
62828
- };
62829
- if (!result.PRLL_WIKI_MOUNT_ROOT?.trim() && opts.wikiMountRoot) {
62830
- result.PRLL_WIKI_MOUNT_ROOT = opts.wikiMountRoot;
62831
- }
62832
- if (opts.effortLevel) {
62833
- result.CLAUDE_CODE_EFFORT_LEVEL = opts.effortLevel;
62834
- }
62835
- if (opts.capabilityBinDir) {
62836
- const pathKey = process.platform === "win32" ? Object.keys(result).find((k) => k.toUpperCase() === "PATH") ?? "PATH" : "PATH";
62837
- const existing = result[pathKey];
62838
- result[pathKey] = existing ? `${opts.capabilityBinDir}${path8.delimiter}${existing}` : opts.capabilityBinDir;
62839
- }
62840
- return result;
62841
- }
62842
62094
  var ClaudeCodeAdapter = class {
62843
62095
  opts;
62844
62096
  inputLifecycleMode = "explicit";
@@ -62848,9 +62100,11 @@ var ClaudeCodeAdapter = class {
62848
62100
  shuttingDown = false;
62849
62101
  _model;
62850
62102
  _effortLevel;
62103
+ _contextWindow;
62851
62104
  constructor(opts) {
62852
62105
  this.opts = opts;
62853
62106
  this._model = opts.model;
62107
+ this._contextWindow = opts.contextWindow;
62854
62108
  }
62855
62109
  get currentModel() {
62856
62110
  return this._model;
@@ -62861,11 +62115,14 @@ var ClaudeCodeAdapter = class {
62861
62115
  updateConfig(config) {
62862
62116
  const modelChanged = config.model !== void 0 && config.model !== this._model;
62863
62117
  const effortChanged = config.effort !== void 0 && config.effort !== this._effortLevel;
62118
+ const contextWindowChanged = config.contextWindow !== void 0 && config.contextWindow !== this._contextWindow;
62864
62119
  if (modelChanged)
62865
62120
  this._model = config.model ?? void 0;
62866
62121
  if (effortChanged)
62867
62122
  this._effortLevel = config.effort ?? void 0;
62868
- if (modelChanged || effortChanged) {
62123
+ if (contextWindowChanged)
62124
+ this._contextWindow = config.contextWindow ?? void 0;
62125
+ if (modelChanged || effortChanged || contextWindowChanged) {
62869
62126
  this.requestProcessRestart();
62870
62127
  }
62871
62128
  }
@@ -62980,7 +62237,7 @@ var ClaudeCodeAdapter = class {
62980
62237
  if (!sessionId)
62981
62238
  return void 0;
62982
62239
  const projectSlug = this.opts.workspaceDir.replace(/[/.]/g, "-");
62983
- const filePath = path8.join(this.opts.claudeHome, ".claude", "projects", projectSlug, `${sessionId}.jsonl`);
62240
+ const filePath = path9.join(this.opts.claudeHome, ".claude", "projects", projectSlug, `${sessionId}.jsonl`);
62984
62241
  return fs7.existsSync(filePath) ? filePath : void 0;
62985
62242
  }
62986
62243
  forkSession({ sessionKey }) {
@@ -63270,11 +62527,12 @@ var ClaudeCodeAdapter = class {
63270
62527
  const args = this.buildArgs(sessionKey, resume);
63271
62528
  const env = buildSpawnEnv(process.env, this.opts.claudeHome, this.buildPlaceholderContext(sessionKey), {
63272
62529
  allowApiKey: this.opts.allowApiKey,
62530
+ contextWindow: this._contextWindow,
63273
62531
  effortLevel: this._effortLevel,
63274
62532
  wikiMountRoot: this.opts.workspaceDir,
63275
62533
  capabilityBinDir: this.opts.capabilityBinDir
63276
62534
  });
63277
- log2?.info(`spawn long-lived ${this.opts.claudeBin} (session ${sessionKey}, model=${this._model || "default"}, effort=${this._effortLevel || "default"}, mode=${this.opts.permissionMode})`);
62535
+ log2?.info(`spawn long-lived ${this.opts.claudeBin} (session ${sessionKey}, model=${this._model || "default"}, context=${this._contextWindow || "cli-default"}, effort=${this._effortLevel || "default"}, mode=${this.opts.permissionMode})`);
63278
62536
  const proc = spawn(IS_WIN32 ? quoteWin32Arg(this.opts.claudeBin) : this.opts.claudeBin, IS_WIN32 ? args.map(quoteWin32Arg) : args, {
63279
62537
  cwd: this.opts.workspaceDir,
63280
62538
  env,
@@ -63370,7 +62628,7 @@ var ClaudeCodeAdapter = class {
63370
62628
  if (this.opts.disallowedTools.length > 0) {
63371
62629
  args.push("--disallowedTools", this.opts.disallowedTools.join(","));
63372
62630
  }
63373
- args.push("--append-system-prompt-file", path8.join(this.opts.workspaceDir, ".parall", "system-prompt.md"));
62631
+ args.push("--append-system-prompt-file", path9.join(this.opts.workspaceDir, ".parall", "system-prompt.md"));
63374
62632
  if (this.opts.appendSystemPrompt) {
63375
62633
  args.push("--append-system-prompt", this.opts.appendSystemPrompt);
63376
62634
  }
@@ -63404,7 +62662,7 @@ var ClaudeCodeAdapter = class {
63404
62662
 
63405
62663
  // ts/claude-agent/dist/session-manager.js
63406
62664
  import * as fs8 from "node:fs";
63407
- import * as path9 from "node:path";
62665
+ import * as path10 from "node:path";
63408
62666
  import { randomUUID as randomUUID4 } from "node:crypto";
63409
62667
  var ClaudeSessionManager = class _ClaudeSessionManager {
63410
62668
  mainSessionKey;
@@ -63569,7 +62827,7 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
63569
62827
  }
63570
62828
  persist(sessionId) {
63571
62829
  try {
63572
- fs8.mkdirSync(path9.dirname(this.stateFilePath), { recursive: true });
62830
+ fs8.mkdirSync(path10.dirname(this.stateFilePath), { recursive: true });
63573
62831
  fs8.writeFileSync(this.stateFilePath, JSON.stringify({
63574
62832
  runtimeKey: this.mainSessionKey,
63575
62833
  sessionId
@@ -63582,20 +62840,20 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
63582
62840
 
63583
62841
  // ts/claude-agent/dist/workspace.js
63584
62842
  import * as fs9 from "node:fs";
63585
- import * as path10 from "node:path";
62843
+ import * as path11 from "node:path";
63586
62844
  function buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
63587
62845
  return buildBridgePlatformInstructions(workspaceDir, agentIdentity, capabilityFragments);
63588
62846
  }
63589
62847
  function writeClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments) {
63590
- const parallDir = path10.join(workspaceDir, ".parall");
62848
+ const parallDir = path11.join(workspaceDir, ".parall");
63591
62849
  fs9.mkdirSync(parallDir, { recursive: true });
63592
- fs9.writeFileSync(path10.join(parallDir, "system-prompt.md"), buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments), "utf8");
62850
+ fs9.writeFileSync(path11.join(parallDir, "system-prompt.md"), buildClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments), "utf8");
63593
62851
  }
63594
62852
  function ensureClaudeWorkspace(workspaceDir, _log, agentIdentity, capabilityFragments) {
63595
62853
  fs9.mkdirSync(workspaceDir, { recursive: true });
63596
- fs9.mkdirSync(path10.join(workspaceDir, ".claude"), { recursive: true });
62854
+ fs9.mkdirSync(path11.join(workspaceDir, ".claude"), { recursive: true });
63597
62855
  writeClaudeSystemPrompt(workspaceDir, agentIdentity, capabilityFragments);
63598
- writeSkillFiles(path10.join(workspaceDir, ".parall", "skills"));
62856
+ writeSkillFiles(path11.join(workspaceDir, ".parall", "skills"));
63599
62857
  ensureLocalAttachmentGitExclude(workspaceDir);
63600
62858
  }
63601
62859
 
@@ -63615,10 +62873,10 @@ async function getAgentMeWithLegacyFallback(client, orgId) {
63615
62873
  }
63616
62874
  function resolveProviderEnv() {
63617
62875
  const pc = parseProviderConfig(process.env);
62876
+ const source = llmSource(pc);
63618
62877
  if (!pc)
63619
- return;
62878
+ return source;
63620
62879
  clearAllProviderCreds(process.env);
63621
- const source = llmSource(pc);
63622
62880
  if (source === "parall") {
63623
62881
  process.env.ANTHROPIC_AUTH_TOKEN = process.env.PRLL_API_KEY;
63624
62882
  process.env.ANTHROPIC_BASE_URL = `${process.env.PRLL_API_URL}/api/llm`;
@@ -63631,13 +62889,14 @@ function resolveProviderEnv() {
63631
62889
  if (pc.anthropic_base_url)
63632
62890
  process.env.ANTHROPIC_BASE_URL = pc.anthropic_base_url;
63633
62891
  }
62892
+ return source;
63634
62893
  }
63635
62894
  async function main() {
63636
62895
  configureHttpKeepAlive();
63637
62896
  const telemetry = await initAgentTelemetry("parall-claude-agent", "claude-code");
63638
62897
  activeLog = createOtelLogger("agent", "claude-agent");
63639
62898
  try {
63640
- resolveProviderEnv();
62899
+ const activeLLMSource = resolveProviderEnv();
63641
62900
  const config = resolveClaudeAgentConfig(process.env);
63642
62901
  if (config.allowApiKey && (process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN)) {
63643
62902
  activeLog.warn("PRLL_CLAUDE_ALLOW_API_KEY=1 \u2014 ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN will reach the Claude CLI; billing routes through Anthropic API pay-per-use instead of Claude.ai OAuth.");
@@ -63679,16 +62938,20 @@ async function main() {
63679
62938
  ensureClaudeWorkspace(config.workspaceDir, agentLog, agentIdentity, bootCapabilityFragments);
63680
62939
  const platformModelOverride = deriveModelIsPin(platformDefaults, me.agent_profile);
63681
62940
  const resolvedModel = resolveRuntimeModel(platformModelOverride, platformDefaults.model, config.model);
62941
+ const resolvedContextWindow = resolveRuntimeContextWindow(resolvedModel, platformDefaults, activeLLMSource);
63682
62942
  const resolvedEffort = platformDefaults.thinkingEffort ?? (process.env.CLAUDE_CODE_EFFORT_LEVEL?.trim() || void 0);
63683
62943
  if (platformDefaults.model)
63684
62944
  agentLog.info(`platform config: model=${platformDefaults.model} \u2192 resolved=${resolvedModel ?? "cli-default"} (${platformModelOverride ? "pin/override" : "floor"})`);
63685
62945
  if (platformDefaults.thinkingEffort)
63686
62946
  agentLog.info(`platform config: thinking_effort=${platformDefaults.thinkingEffort}`);
62947
+ if (resolvedContextWindow)
62948
+ agentLog.info(`platform config: context_window=${resolvedContextWindow}`);
63687
62949
  const adapter = new ClaudeCodeAdapter({
63688
62950
  claudeBin: config.claudeBin,
63689
62951
  claudeHome: config.claudeHome,
63690
62952
  workspaceDir: config.workspaceDir,
63691
62953
  model: resolvedModel,
62954
+ contextWindow: resolvedContextWindow,
63692
62955
  permissionMode: config.permissionMode,
63693
62956
  allowedTools: config.allowedTools,
63694
62957
  disallowedTools: config.disallowedTools,
@@ -63726,8 +62989,10 @@ async function main() {
63726
62989
  }
63727
62990
  const isPin = deriveModelIsPin(updated, lastKnownAgentProfile);
63728
62991
  const localEffort = process.env.CLAUDE_CODE_EFFORT_LEVEL?.trim() || null;
62992
+ const model = resolveRuntimeModel(isPin, updated.model, config.model) ?? null;
63729
62993
  adapter.updateConfig({
63730
- model: resolveRuntimeModel(isPin, updated.model, config.model) ?? null,
62994
+ model,
62995
+ contextWindow: resolveRuntimeContextWindow(model, updated, activeLLMSource) ?? null,
63731
62996
  effort: updated.thinkingEffort ?? localEffort
63732
62997
  });
63733
62998
  const fragments = applyChannelCapabilities();