@parall/daemon 1.66.0 → 1.67.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.
@@ -52323,7 +52323,7 @@ async function persistRuntimeObservation(persister, sessionId, target, event, lo
52323
52323
  }
52324
52324
  }
52325
52325
 
52326
- // ts/agent-core/dist/fork-prefix.js
52326
+ // ts/agent-core/dist/gateway/fork-prefix.js
52327
52327
  function sanitizeMeta(value) {
52328
52328
  return value.replace(/[\r\n]+/g, " ").replace(/[[\]|]/g, " ").trim();
52329
52329
  }
@@ -52361,7 +52361,7 @@ function buildForkResultPrefix(results) {
52361
52361
  return blocks.join("\n\n") + "\n\n---\n\n";
52362
52362
  }
52363
52363
 
52364
- // ts/agent-core/dist/gateway-runtime-step.js
52364
+ // ts/agent-core/dist/gateway/runtime-step.js
52365
52365
  import { randomUUID as randomUUID2 } from "node:crypto";
52366
52366
  async function createRuntimeStep(host, sessionId, target, runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2) {
52367
52367
  switch (runtimeEvent.type) {
@@ -52463,7 +52463,7 @@ async function createRuntimeStep(host, sessionId, target, runtimeEvent, stepIdFi
52463
52463
  }
52464
52464
  }
52465
52465
 
52466
- // ts/agent-core/dist/dispatch-recovery.js
52466
+ // ts/agent-core/dist/gateway/recovery.js
52467
52467
  var DispatchRecovery = class {
52468
52468
  scan;
52469
52469
  stopped;
@@ -52498,9 +52498,6 @@ var DispatchRecovery = class {
52498
52498
  }
52499
52499
  };
52500
52500
 
52501
- // ts/agent-core/dist/gateway-base.js
52502
- import * as os from "node:os";
52503
-
52504
52501
  // ts/agent-core/dist/change-source.js
52505
52502
  var CHANGE_REASONS = /* @__PURE__ */ new Set([
52506
52503
  "edited",
@@ -52519,10 +52516,19 @@ function splitChangeSource(sourceId) {
52519
52516
  return { messageId: sourceId.slice(0, i), reason };
52520
52517
  }
52521
52518
 
52522
- // ts/agent-core/dist/gateway-base.js
52519
+ // ts/agent-core/dist/gateway/base.js
52523
52520
  import * as fs4 from "node:fs";
52524
52521
  import * as path5 from "node:path";
52525
- import { randomUUID as randomUUID4 } from "node:crypto";
52522
+
52523
+ // ts/sdk/dist/browser-use-contract.generated.js
52524
+ var browserUseContract = { "actions": { "read": { "grant": "browser.read", "target": "optional_tab", "params": { "required": [], "properties": { "url": { "type": "string", "min_length": 1, "max_length": 8192, "schemes": ["http", "https", "about:blank"] } }, "rules": ["exactly one of params.url or target is required", "params.url creates a hidden Profile-bound tab and closes it before terminal success or failure"], "additional_properties": false }, "success": { "base": null, "fields": { "profile_id": "ebp_identifier", "url": "string", "title": "string", "article": "nullable_article" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "tabs": { "grant": "browser.read", "target": "none", "params": { "required": [], "properties": {}, "additional_properties": false }, "success": { "base": null, "fields": { "tabs": "tab_summary_array" } }, "errors": ["TAB_GONE"] }, "wait": { "grant": "browser.read", "target": "tab", "params": { "required": [], "properties": { "selector": { "type": "string", "min_length": 1, "max_length": 4096 }, "state": { "enum": ["attached", "detached", "visible", "hidden", "load"], "default": "attached" }, "timeout_ms": { "type": "integer", "minimum": 1, "maximum": 3e4, "default": 1e4 } }, "rules": ["selector is required unless state=load", "state=load forbids selector"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "matched": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "snapshot": { "grant": "browser.read", "target": "tab", "params": { "required": [], "properties": { "interactive": { "type": "boolean", "default": false }, "compact": { "type": "boolean", "default": false }, "depth": { "type": "integer", "minimum": 0, "maximum": 64 } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "snapshot": "string", "snapshot_id": "identifier" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "get": { "grant": "browser.read", "target": "tab_or_ref", "params": { "required": ["prop"], "properties": { "selector": { "type": "string", "min_length": 1, "max_length": 4096 }, "prop": { "enum": ["text", "html", "value", "attr", "title", "url"] }, "name": { "type": "string", "min_length": 1, "max_length": 256 } }, "rules": ["title/url forbid locator and name", "text/html/value require exactly one locator", "attr requires exactly one locator and name"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "value": "nullable_string" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "STALE_REF", "PAGE_LOAD_FAILED"] }, "screenshot": { "grant": "browser.read", "target": "tab", "params": { "required": [], "properties": {}, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "format": { "const": "png" }, "base64": "canonical_base64" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "open": { "grant": "browser.interact", "target": "none", "params": { "required": ["url"], "properties": { "url": { "type": "string", "min_length": 1, "max_length": 8192, "schemes": ["http", "https", "about:blank"] }, "hidden": { "type": "boolean", "default": false }, "viewport": { "type": "viewport" } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": {} }, "errors": ["PAGE_LOAD_FAILED"] }, "navigate": { "grant": "browser.interact", "target": "tab", "params": { "required": ["url"], "properties": { "url": { "type": "string", "min_length": 1, "max_length": 8192, "schemes": ["http", "https", "about:blank"] } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": {} }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "viewport": { "grant": "browser.interact", "target": "tab", "params": { "required": ["width", "height"], "properties": { "width": { "type": "integer", "minimum": 320, "maximum": 3840 }, "height": { "type": "integer", "minimum": 240, "maximum": 2160 } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "viewport": "viewport" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE"] }, "click": { "grant": "browser.interact", "target": "tab_or_ref", "params": { "required": [], "properties": { "selector": "selector" }, "rules": ["exactly one of params.selector or target.ref"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "clicked": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "STALE_REF", "PAGE_LOAD_FAILED"] }, "fill": { "grant": "browser.interact", "target": "tab_or_ref", "params": { "required": ["text"], "properties": { "selector": "selector", "text": { "type": "string", "allow_empty": true } }, "rules": ["exactly one of params.selector or target.ref"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "filled": { "const": true }, "characters": "non_negative_integer" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "STALE_REF", "PAGE_LOAD_FAILED"] }, "type": { "grant": "browser.interact", "target": "tab_or_ref", "params": { "required": ["text"], "properties": { "selector": "selector", "text": { "type": "string", "min_length": 1 } }, "rules": ["exactly one of params.selector or target.ref"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "typed": { "const": true }, "characters": "non_negative_integer" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "STALE_REF", "PAGE_LOAD_FAILED"] }, "press": { "grant": "browser.interact", "target": "tab", "params": { "required": ["key"], "properties": { "key": "single_unicode_character_or_named_key" }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "pressed": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "scroll": { "grant": "browser.interact", "target": "tab", "params": { "required": [], "properties": { "direction": { "enum": ["up", "down", "left", "right"], "default": "down" }, "pixels": { "type": "integer", "minimum": 1, "maximum": 1e5, "default": 500 } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "scrolled": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "close": { "grant": "browser.interact", "target": "tab", "params": { "required": [], "properties": {}, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "closed": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE"] }, "recover": { "grant": "browser.interact", "target": "tab", "params": { "required": [], "properties": {}, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "recovered_from_tab_id": "identifier" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "eval": { "grant": "browser.advanced", "target": "tab", "params": { "required": ["expression"], "properties": { "expression": { "type": "string", "min_length": 1 }, "timeout_ms": { "type": "integer", "minimum": 1, "maximum": 15e3, "default": 15e3 } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "value": "json_value_max_256_kib" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] } }, "successShapes": { "tab_state": { "required": ["tab_id", "profile_id", "browser_generation", "document_generation", "url", "title"], "fields": { "tab_id": "identifier", "profile_id": "ebp_identifier", "browser_generation": "positive_integer", "document_generation": "positive_integer", "url": "string", "title": "string" }, "additional_properties": false }, "tab_summary": { "base": "tab_state", "required_additions": ["loading"], "fields": { "loading": "boolean" }, "additional_properties": false }, "article": { "required": ["title", "byline", "excerpt", "text", "published_time", "site_name", "length"], "fields": { "title": "nullable_string", "byline": "nullable_string", "excerpt": "nullable_string", "text": "string", "published_time": "nullable_string", "site_name": "nullable_string", "length": "non_negative_integer" }, "additional_properties": false } } };
52525
+
52526
+ // ts/sdk/dist/browser-use-validation.js
52527
+ var BROWSER_USE_ACTION_SCHEMAS = browserUseContract.actions;
52528
+ var BROWSER_USE_ACTIONS = Object.freeze(Object.keys(BROWSER_USE_ACTION_SCHEMAS));
52529
+
52530
+ // ts/sdk/dist/browser-use-receipt.js
52531
+ var KEYS = "contract_version operation_id request_id profile_id profile_version profile_config_revision action required_grant phase dispatched receipt_id receipt_digest occurred_at tab_id browser_generation duration_ms result_digest result_available result_expires_at data error deadline accepted_at started_at terminal_at updated_at".split(" ");
52526
52532
 
52527
52533
  // ts/sdk/dist/browser-viewer.js
52528
52534
  var BROWSER_VIEWER_READINESS_TIMEOUT_MS = 6e4;
@@ -52535,17 +52541,13 @@ function browserViewerRequestOptions(command, opts) {
52535
52541
  };
52536
52542
  }
52537
52543
 
52538
- // ts/sdk/dist/slack-endpoints.js
52539
- function slackEndpoints(apiBase) {
52544
+ // ts/sdk/dist/attachment-endpoints.js
52545
+ function attachmentEndpoints(apiBase) {
52540
52546
  return {
52541
- SLACK_CHANNELS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/channels`,
52542
- SLACK_USERS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/users`,
52543
- SLACK_REPLIES: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/replies`,
52544
- SLACK_HISTORY: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/history`,
52545
- SLACK_MEMBERS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/members`,
52546
- SLACK_STATUS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/status`,
52547
- SLACK_FILE: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/file`,
52548
- SLACK_FILES: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/files`
52547
+ UPLOAD_PRESIGN: (orgId) => `${apiBase}/orgs/${orgId}/upload/presign`,
52548
+ UPLOAD_COMPLETE: (orgId) => `${apiBase}/orgs/${orgId}/upload/complete`,
52549
+ UPLOAD_ABORT: (orgId) => `${apiBase}/orgs/${orgId}/upload/abort`,
52550
+ FILE: (id) => `${apiBase}/files/${id}`
52549
52551
  };
52550
52552
  }
52551
52553
 
@@ -52557,16 +52559,6 @@ var clipConnectionEndpoints = {
52557
52559
  CLIP_CONNECTION: (orgId, connId) => `/api/v1/orgs/${orgId}/clip-connections/${connId}`
52558
52560
  };
52559
52561
 
52560
- // ts/sdk/dist/attachment-endpoints.js
52561
- function attachmentEndpoints(apiBase) {
52562
- return {
52563
- UPLOAD_PRESIGN: (orgId) => `${apiBase}/orgs/${orgId}/upload/presign`,
52564
- UPLOAD_COMPLETE: (orgId) => `${apiBase}/orgs/${orgId}/upload/complete`,
52565
- UPLOAD_ABORT: (orgId) => `${apiBase}/orgs/${orgId}/upload/abort`,
52566
- FILE: (id) => `${apiBase}/files/${id}`
52567
- };
52568
- }
52569
-
52570
52562
  // ts/sdk/dist/edge-endpoints.js
52571
52563
  var API_BASE = "/api/v1";
52572
52564
  var edgeEndpoints = {
@@ -52583,6 +52575,20 @@ var edgeEndpoints = {
52583
52575
  ORG_EDGE_PROFILE_OPERATION_CONFIRM: (orgId, edgeId, operationId) => `${API_BASE}/orgs/${orgId}/edge/${edgeId}/profile-operations/${operationId}/confirm`
52584
52576
  };
52585
52577
 
52578
+ // ts/sdk/dist/slack-endpoints.js
52579
+ function slackEndpoints(apiBase) {
52580
+ return {
52581
+ SLACK_CHANNELS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/channels`,
52582
+ SLACK_USERS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/users`,
52583
+ SLACK_REPLIES: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/replies`,
52584
+ SLACK_HISTORY: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/history`,
52585
+ SLACK_MEMBERS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/members`,
52586
+ SLACK_STATUS: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/status`,
52587
+ SLACK_FILE: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/file`,
52588
+ SLACK_FILES: (orgId) => `${apiBase}/orgs/${orgId}/agents/me/slack/files`
52589
+ };
52590
+ }
52591
+
52586
52592
  // ts/sdk/dist/wechat-endpoints.js
52587
52593
  function wechatEndpoints(apiBase) {
52588
52594
  const agentBase = (orgId) => `${apiBase}/orgs/${orgId}/agents/me/wechat`;
@@ -52800,6 +52806,13 @@ var ENDPOINTS = {
52800
52806
  // Labels (org-scoped vocabulary; writes are admin-gated)
52801
52807
  LABELS: (orgId) => `${API_BASE2}/orgs/${orgId}/labels`,
52802
52808
  LABEL: (orgId, labelId) => `${API_BASE2}/orgs/${orgId}/labels/${labelId}`,
52809
+ // Mini Apps (project-scoped entity; routes exist only under cap:mini-apps)
52810
+ MINI_APPS: (orgId) => `${API_BASE2}/orgs/${orgId}/apps`,
52811
+ MINI_APP: (orgId, appId) => `${API_BASE2}/orgs/${orgId}/apps/${appId}`,
52812
+ MINI_APP_ARCHIVE: (orgId, appId) => `${API_BASE2}/orgs/${orgId}/apps/${appId}/archive`,
52813
+ MINI_APP_RESTORE: (orgId, appId) => `${API_BASE2}/orgs/${orgId}/apps/${appId}/restore`,
52814
+ MINI_APP_AUTHORS: (orgId, appId) => `${API_BASE2}/orgs/${orgId}/apps/${appId}/authors`,
52815
+ MINI_APP_AUTHOR: (orgId, appId, userId) => `${API_BASE2}/orgs/${orgId}/apps/${appId}/authors/${userId}`,
52803
52816
  // Projects (org-scoped)
52804
52817
  PROJECTS: (orgId) => `${API_BASE2}/orgs/${orgId}/projects`,
52805
52818
  PROJECT_TASK_SUMMARY: (orgId) => `${API_BASE2}/orgs/${orgId}/projects/task-summary`,
@@ -53457,8 +53470,48 @@ var WechatClient = class extends TaskLabelClient {
53457
53470
  }
53458
53471
  };
53459
53472
 
53473
+ // ts/sdk/dist/mini-app-client.js
53474
+ var MiniAppClient = class extends WechatClient {
53475
+ async getMiniApps(orgId, query = {}) {
53476
+ const response = await this.request("GET", ENDPOINTS.MINI_APPS(orgId), void 0, {
53477
+ project_id: query.project_id,
53478
+ include_archived: query.include_archived ? "true" : void 0
53479
+ });
53480
+ return response.data;
53481
+ }
53482
+ async getMiniApp(orgId, appId) {
53483
+ return this.request("GET", ENDPOINTS.MINI_APP(orgId, appId));
53484
+ }
53485
+ async createMiniApp(orgId, data) {
53486
+ return this.request("POST", ENDPOINTS.MINI_APPS(orgId), data);
53487
+ }
53488
+ async updateMiniApp(orgId, appId, data) {
53489
+ return this.request("PATCH", ENDPOINTS.MINI_APP(orgId, appId), data);
53490
+ }
53491
+ async archiveMiniApp(orgId, appId) {
53492
+ return this.request("POST", ENDPOINTS.MINI_APP_ARCHIVE(orgId, appId));
53493
+ }
53494
+ async restoreMiniApp(orgId, appId) {
53495
+ return this.request("POST", ENDPOINTS.MINI_APP_RESTORE(orgId, appId));
53496
+ }
53497
+ async getMiniAppAuthors(orgId, appId) {
53498
+ const response = await this.request("GET", ENDPOINTS.MINI_APP_AUTHORS(orgId, appId));
53499
+ return response.data;
53500
+ }
53501
+ /** Idempotent: re-adding an existing author returns the roster unchanged. */
53502
+ async addMiniAppAuthor(orgId, appId, userId) {
53503
+ const response = await this.request("POST", ENDPOINTS.MINI_APP_AUTHORS(orgId, appId), {
53504
+ user_id: userId
53505
+ });
53506
+ return response.data;
53507
+ }
53508
+ async removeMiniAppAuthor(orgId, appId, userId) {
53509
+ return this.request("DELETE", ENDPOINTS.MINI_APP_AUTHOR(orgId, appId, userId));
53510
+ }
53511
+ };
53512
+
53460
53513
  // ts/sdk/dist/llm-provider-client.js
53461
- var LLMProviderClient = class extends WechatClient {
53514
+ var LLMProviderClient = class extends MiniAppClient {
53462
53515
  async getLLMProviders(orgId) {
53463
53516
  const response = await this.request("GET", ENDPOINTS.LLM_PROVIDERS(orgId));
53464
53517
  return response.data;
@@ -57044,67 +57097,7 @@ var ParallWs = class {
57044
57097
  }
57045
57098
  };
57046
57099
 
57047
- // ts/sdk/dist/browser-use-contract.generated.js
57048
- var browserUseContract = { "actions": { "read": { "grant": "browser.read", "target": "optional_tab", "params": { "required": [], "properties": { "url": { "type": "string", "min_length": 1, "max_length": 8192, "schemes": ["http", "https", "about:blank"] } }, "rules": ["exactly one of params.url or target is required", "params.url creates a hidden Profile-bound tab and closes it before terminal success or failure"], "additional_properties": false }, "success": { "base": null, "fields": { "profile_id": "ebp_identifier", "url": "string", "title": "string", "article": "nullable_article" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "tabs": { "grant": "browser.read", "target": "none", "params": { "required": [], "properties": {}, "additional_properties": false }, "success": { "base": null, "fields": { "tabs": "tab_summary_array" } }, "errors": ["TAB_GONE"] }, "wait": { "grant": "browser.read", "target": "tab", "params": { "required": [], "properties": { "selector": { "type": "string", "min_length": 1, "max_length": 4096 }, "state": { "enum": ["attached", "detached", "visible", "hidden", "load"], "default": "attached" }, "timeout_ms": { "type": "integer", "minimum": 1, "maximum": 3e4, "default": 1e4 } }, "rules": ["selector is required unless state=load", "state=load forbids selector"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "matched": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "snapshot": { "grant": "browser.read", "target": "tab", "params": { "required": [], "properties": { "interactive": { "type": "boolean", "default": false }, "compact": { "type": "boolean", "default": false }, "depth": { "type": "integer", "minimum": 0, "maximum": 64 } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "snapshot": "string", "snapshot_id": "identifier" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "get": { "grant": "browser.read", "target": "tab_or_ref", "params": { "required": ["prop"], "properties": { "selector": { "type": "string", "min_length": 1, "max_length": 4096 }, "prop": { "enum": ["text", "html", "value", "attr", "title", "url"] }, "name": { "type": "string", "min_length": 1, "max_length": 256 } }, "rules": ["title/url forbid locator and name", "text/html/value require exactly one locator", "attr requires exactly one locator and name"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "value": "nullable_string" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "STALE_REF", "PAGE_LOAD_FAILED"] }, "screenshot": { "grant": "browser.read", "target": "tab", "params": { "required": [], "properties": {}, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "format": { "const": "png" }, "base64": "canonical_base64" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "open": { "grant": "browser.interact", "target": "none", "params": { "required": ["url"], "properties": { "url": { "type": "string", "min_length": 1, "max_length": 8192, "schemes": ["http", "https", "about:blank"] }, "hidden": { "type": "boolean", "default": false }, "viewport": { "type": "viewport" } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": {} }, "errors": ["PAGE_LOAD_FAILED"] }, "navigate": { "grant": "browser.interact", "target": "tab", "params": { "required": ["url"], "properties": { "url": { "type": "string", "min_length": 1, "max_length": 8192, "schemes": ["http", "https", "about:blank"] } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": {} }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "viewport": { "grant": "browser.interact", "target": "tab", "params": { "required": ["width", "height"], "properties": { "width": { "type": "integer", "minimum": 320, "maximum": 3840 }, "height": { "type": "integer", "minimum": 240, "maximum": 2160 } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "viewport": "viewport" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE"] }, "click": { "grant": "browser.interact", "target": "tab_or_ref", "params": { "required": [], "properties": { "selector": "selector" }, "rules": ["exactly one of params.selector or target.ref"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "clicked": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "STALE_REF", "PAGE_LOAD_FAILED"] }, "fill": { "grant": "browser.interact", "target": "tab_or_ref", "params": { "required": ["text"], "properties": { "selector": "selector", "text": { "type": "string", "allow_empty": true } }, "rules": ["exactly one of params.selector or target.ref"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "filled": { "const": true }, "characters": "non_negative_integer" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "STALE_REF", "PAGE_LOAD_FAILED"] }, "type": { "grant": "browser.interact", "target": "tab_or_ref", "params": { "required": ["text"], "properties": { "selector": "selector", "text": { "type": "string", "min_length": 1 } }, "rules": ["exactly one of params.selector or target.ref"], "additional_properties": false }, "success": { "base": "tab_state", "fields": { "typed": { "const": true }, "characters": "non_negative_integer" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "STALE_REF", "PAGE_LOAD_FAILED"] }, "press": { "grant": "browser.interact", "target": "tab", "params": { "required": ["key"], "properties": { "key": "single_unicode_character_or_named_key" }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "pressed": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "scroll": { "grant": "browser.interact", "target": "tab", "params": { "required": [], "properties": { "direction": { "enum": ["up", "down", "left", "right"], "default": "down" }, "pixels": { "type": "integer", "minimum": 1, "maximum": 1e5, "default": 500 } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "scrolled": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "close": { "grant": "browser.interact", "target": "tab", "params": { "required": [], "properties": {}, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "closed": { "const": true } } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE"] }, "recover": { "grant": "browser.interact", "target": "tab", "params": { "required": [], "properties": {}, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "recovered_from_tab_id": "identifier" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] }, "eval": { "grant": "browser.advanced", "target": "tab", "params": { "required": ["expression"], "properties": { "expression": { "type": "string", "min_length": 1 }, "timeout_ms": { "type": "integer", "minimum": 1, "maximum": 15e3, "default": 15e3 } }, "additional_properties": false }, "success": { "base": "tab_state", "fields": { "value": "json_value_max_256_kib" } }, "errors": ["TAB_NOT_FOUND", "TAB_GONE", "PAGE_LOAD_FAILED"] } }, "successShapes": { "tab_state": { "required": ["tab_id", "profile_id", "browser_generation", "document_generation", "url", "title"], "fields": { "tab_id": "identifier", "profile_id": "ebp_identifier", "browser_generation": "positive_integer", "document_generation": "positive_integer", "url": "string", "title": "string" }, "additional_properties": false }, "tab_summary": { "base": "tab_state", "required_additions": ["loading"], "fields": { "loading": "boolean" }, "additional_properties": false }, "article": { "required": ["title", "byline", "excerpt", "text", "published_time", "site_name", "length"], "fields": { "title": "nullable_string", "byline": "nullable_string", "excerpt": "nullable_string", "text": "string", "published_time": "nullable_string", "site_name": "nullable_string", "length": "non_negative_integer" }, "additional_properties": false } } };
57049
-
57050
- // ts/sdk/dist/browser-use-validation.js
57051
- var BROWSER_USE_ACTION_SCHEMAS = browserUseContract.actions;
57052
- var BROWSER_USE_ACTIONS = Object.freeze(Object.keys(BROWSER_USE_ACTION_SCHEMAS));
57053
-
57054
- // ts/sdk/dist/browser-use-receipt.js
57055
- var KEYS = "contract_version operation_id request_id profile_id profile_version profile_config_revision action required_grant phase dispatched receipt_id receipt_digest occurred_at tab_id browser_generation duration_ms result_digest result_available result_expires_at data error deadline accepted_at started_at terminal_at updated_at".split(" ");
57056
-
57057
- // ts/agent-core/dist/fork-state.js
57058
- var FORK_CONTINUATION_RETRY_CAP = 256;
57059
- function forkContinuationRetryKey(event) {
57060
- if (event.type === "message" || event.type === "channel_message") {
57061
- return event.messageId ? `message:${event.messageId}` : void 0;
57062
- }
57063
- return event.dispatchEventId ? `dispatch:${event.dispatchEventId}` : void 0;
57064
- }
57065
- function resolveForkContinuationPrefix(pendingResults, retries, event) {
57066
- const retryKey = forkContinuationRetryKey(event);
57067
- const retained = retryKey ? retries.get(retryKey) : void 0;
57068
- if (retained)
57069
- return retained;
57070
- const prefix = buildForkResultPrefix(pendingResults.filter((result) => result.sourceEvent.targetId === event.targetId));
57071
- return prefix || void 0;
57072
- }
57073
- function retainForkContinuationRetries(retries, events, prefix) {
57074
- if (!prefix)
57075
- return;
57076
- for (const event of events) {
57077
- const key = forkContinuationRetryKey(event);
57078
- if (!key)
57079
- continue;
57080
- if (retries.delete(key) === false && retries.size >= FORK_CONTINUATION_RETRY_CAP) {
57081
- const oldest = retries.keys().next().value;
57082
- if (oldest !== void 0)
57083
- retries.delete(oldest);
57084
- }
57085
- retries.set(key, prefix);
57086
- }
57087
- }
57088
- function clearForkContinuationRetries(retries, events) {
57089
- for (const event of events) {
57090
- const key = forkContinuationRetryKey(event);
57091
- if (key)
57092
- retries.delete(key);
57093
- }
57094
- }
57095
- function createActiveForkState(fork, targetId, continuationPrefix) {
57096
- return {
57097
- fork,
57098
- targetId,
57099
- queue: [],
57100
- processedEvents: [],
57101
- continuationPrefix,
57102
- deadlineTimer: null,
57103
- deadlineExceeded: false
57104
- };
57105
- }
57106
-
57107
- // ts/agent-core/dist/gateway-steer.js
57100
+ // ts/agent-core/dist/gateway/steer.js
57108
57101
  var pendingSteers = /* @__PURE__ */ new WeakMap();
57109
57102
  function hasMainSteers(state) {
57110
57103
  return (pendingSteers.get(state)?.size ?? 0) > 0;
@@ -58013,7 +58006,7 @@ function createOtelLogger(layer, prefix) {
58013
58006
  };
58014
58007
  }
58015
58008
 
58016
- // ts/agent-core/dist/gateway-lane-settle.js
58009
+ // ts/agent-core/dist/gateway/lane-settle.js
58017
58010
  async function settleNonCleanTurn(host, sessionKey, lane) {
58018
58011
  const ledger = host.laneLedger;
58019
58012
  const settled = host.consumeTurnOutcome(sessionKey);
@@ -58071,10 +58064,10 @@ async function attachLiveSteers(host, opts, lane, live) {
58071
58064
  return void 0;
58072
58065
  }
58073
58066
 
58074
- // ts/agent-core/dist/lane-ledger.js
58067
+ // ts/agent-core/dist/lane/ledger.js
58075
58068
  import * as fs3 from "node:fs";
58076
58069
 
58077
- // ts/agent-core/dist/lane-key.js
58070
+ // ts/agent-core/dist/lane/key.js
58078
58071
  import * as path4 from "node:path";
58079
58072
  function laneKeyForTarget(targetUri, threadRootId) {
58080
58073
  return Buffer.from(`${targetUri}
@@ -58087,7 +58080,7 @@ function laneContextFilePath(contextDir, targetUri, threadRootId) {
58087
58080
  return path4.join(contextDir, `${laneKeyForTarget(targetUri, threadRootId)}.json`);
58088
58081
  }
58089
58082
 
58090
- // ts/agent-core/dist/lane-target.js
58083
+ // ts/agent-core/dist/lane/target.js
58091
58084
  var PRLL_SCHEME = "prll://";
58092
58085
  var CHAT_LANE_PREFIX = "cht_";
58093
58086
  var CHANNEL_LANE_PREFIX = `${PRLL_SCHEME}chv_`;
@@ -58110,7 +58103,7 @@ function isTypedEvent(event) {
58110
58103
  return event.type !== "message" && laneTargetUri(event) === void 0;
58111
58104
  }
58112
58105
 
58113
- // ts/agent-core/dist/lane-outcome.js
58106
+ // ts/agent-core/dist/lane/outcome.js
58114
58107
  function errorWireClass(cls) {
58115
58108
  if (!cls || cls === "ok" || cls === "usage_limit")
58116
58109
  return void 0;
@@ -58126,7 +58119,7 @@ function isTurnToken(token) {
58126
58119
  return token.startsWith("turn_");
58127
58120
  }
58128
58121
 
58129
- // ts/agent-core/dist/lane-input-receipts.js
58122
+ // ts/agent-core/dist/lane/input-receipts.js
58130
58123
  var LaneInputReceipts = class {
58131
58124
  opts;
58132
58125
  confirmations;
@@ -58223,7 +58216,7 @@ var LaneInputReceipts = class {
58223
58216
  }
58224
58217
  };
58225
58218
 
58226
- // ts/agent-core/dist/lane-confirmations.js
58219
+ // ts/agent-core/dist/lane/confirmations.js
58227
58220
  var LaneConfirmations = class {
58228
58221
  opts;
58229
58222
  pending = /* @__PURE__ */ new Map();
@@ -58273,12 +58266,12 @@ var LaneConfirmations = class {
58273
58266
  async run(token, pending) {
58274
58267
  if (pending.running || pending.blocked || this.pending.get(token) !== pending)
58275
58268
  return;
58276
- const recovered = pending.failures > 0;
58269
+ let recovered = pending.failures > 0;
58277
58270
  pending.running = Promise.resolve().then(async () => {
58278
58271
  while (pending.writes.length && this.pending.get(token) === pending) {
58279
58272
  const write = pending.writes[0];
58280
58273
  try {
58281
- await write.send();
58274
+ recovered = await write.send() || recovered;
58282
58275
  pending.writes.shift();
58283
58276
  if (this.pending.get(token) === pending)
58284
58277
  write.onAttempt?.("sent");
@@ -58352,7 +58345,7 @@ var LaneConfirmations = class {
58352
58345
  }
58353
58346
  };
58354
58347
 
58355
- // ts/agent-core/dist/lane-ledger.js
58348
+ // ts/agent-core/dist/lane/ledger.js
58356
58349
  var LedgerUnsupportedError = class extends Error {
58357
58350
  };
58358
58351
  function bindLaneSession(lane, agentSessionId) {
@@ -58400,7 +58393,7 @@ var LaneLedger = class {
58400
58393
  get contextDir() {
58401
58394
  return this.opts.contextDir;
58402
58395
  }
58403
- /** Message-lane events (chat, channel conversation — lane-target.ts) ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
58396
+ /** Message-lane events (chat, channel conversation — lane/target.ts) ride (target, thread) lanes; typed events ride single-member dsp lanes (claimTyped). */
58404
58397
  handles(event) {
58405
58398
  return laneTargetUri(event) !== void 0;
58406
58399
  }
@@ -58717,8 +58710,9 @@ ${frame}` : frame;
58717
58710
  await this.confirmations.submit(lane.lane, {
58718
58711
  label: "complete",
58719
58712
  send: async () => {
58713
+ let result;
58720
58714
  try {
58721
- await this.opts.client.completeDispatch(this.opts.orgId, fallback ? {
58715
+ result = await this.opts.client.completeDispatch(this.opts.orgId, fallback ? {
58722
58716
  lane: request3.lane,
58723
58717
  target_uri: request3.target_uri,
58724
58718
  thread_root_id: request3.thread_root_id,
@@ -58728,7 +58722,7 @@ ${frame}` : frame;
58728
58722
  if (!fallback && outcome === "deferred" && err instanceof ApiError && err.status === 400) {
58729
58723
  this.deferredUnsupported = true;
58730
58724
  fallback = true;
58731
- await this.opts.client.completeDispatch(this.opts.orgId, {
58725
+ result = await this.opts.client.completeDispatch(this.opts.orgId, {
58732
58726
  lane: request3.lane,
58733
58727
  target_uri: request3.target_uri,
58734
58728
  thread_root_id: request3.thread_root_id,
@@ -58737,7 +58731,7 @@ ${frame}` : frame;
58737
58731
  } else
58738
58732
  throw err;
58739
58733
  }
58740
- this.forgetLane(lane);
58734
+ return this.forgetLane(lane) && Boolean(result.redriven || result.released);
58741
58735
  }
58742
58736
  });
58743
58737
  }
@@ -58805,7 +58799,7 @@ ${frame}` : frame;
58805
58799
  label: "release",
58806
58800
  send: async () => {
58807
58801
  await this.opts.client.releaseDispatchLane(this.opts.orgId, lane.lane, reason, outcome);
58808
- this.forgetLane(lane);
58802
+ return this.forgetLane(lane);
58809
58803
  }
58810
58804
  });
58811
58805
  }
@@ -58957,11 +58951,14 @@ ${frame}` : frame;
58957
58951
  dispose() {
58958
58952
  this.confirmations.dispose();
58959
58953
  }
58954
+ /** False when a newer lane already took this key: a late confirmation touches nothing. */
58960
58955
  forgetLane(lane) {
58961
58956
  if (this.lanes.get(lane.laneKey) !== lane)
58962
- return;
58957
+ return false;
58963
58958
  this.lanes.delete(lane.laneKey);
58959
+ this.opts.releaseLocalClaims?.([...lane.folded.keys()]);
58964
58960
  this.removeLaneContext(lane);
58961
+ return true;
58965
58962
  }
58966
58963
  /**
58967
58964
  * Remove the per-lane context file (and its CLI sidecar) when the lane
@@ -58980,7 +58977,7 @@ ${frame}` : frame;
58980
58977
  }
58981
58978
  };
58982
58979
 
58983
- // ts/agent-core/dist/gateway-lane-flow.js
58980
+ // ts/agent-core/dist/gateway/lane-flow.js
58984
58981
  function shiftMainBufferGroup(host, groupKey, preserveInjectedFrameBoundary) {
58985
58982
  const events = [];
58986
58983
  while (host.dispatchState.mainBuffer[0] && host.dispatchGroupKey(host.dispatchState.mainBuffer[0]) === groupKey && (!preserveInjectedFrameBoundary || events.length === 0)) {
@@ -59289,6 +59286,7 @@ async function consumeLaneWorkItem(host, event) {
59289
59286
  if (host.dispatchState.mainBuffer.some((e) => e.messageId === event.messageId))
59290
59287
  return;
59291
59288
  if (host.laneLedger && !host.ledgerDisabled && host.laneLedger.seenInFrame(event.targetId, event.threadRootId, event.messageId)) {
59289
+ host.dispatchedMessages.delete(event.messageId);
59292
59290
  return;
59293
59291
  }
59294
59292
  try {
@@ -59339,7 +59337,7 @@ function releaseErrorInfo(err, knownValues = []) {
59339
59337
  };
59340
59338
  }
59341
59339
 
59342
- // ts/agent-core/dist/gateway-idle-compact.js
59340
+ // ts/agent-core/dist/gateway/idle-compact.js
59343
59341
  var COMPACT_BUDGET_MS = 18e4;
59344
59342
  function createIdleCompactState() {
59345
59343
  return { inFlight: null, abort: null };
@@ -59434,7 +59432,7 @@ async function handleCompactSignal(host, data) {
59434
59432
  }
59435
59433
  }
59436
59434
 
59437
- // ts/agent-core/dist/gateway-runtime-turns.js
59435
+ // ts/agent-core/dist/gateway/runtime-turns.js
59438
59436
  var UNTARGETED_STEP = { target_type: "" };
59439
59437
  function handleRuntimeActivity(host, event) {
59440
59438
  if (event.kind === "observation") {
@@ -59583,7 +59581,7 @@ async function closeRuntimeChildSession(host, sessionKey, reason) {
59583
59581
  }
59584
59582
  }
59585
59583
 
59586
- // ts/agent-core/dist/gateway-drain.js
59584
+ // ts/agent-core/dist/gateway/drain.js
59587
59585
  var DrainGate = class {
59588
59586
  isDrained;
59589
59587
  waiters = [];
@@ -59623,7 +59621,7 @@ var DrainGate = class {
59623
59621
  }
59624
59622
  };
59625
59623
 
59626
- // ts/agent-core/dist/gateway-session-binding.js
59624
+ // ts/agent-core/dist/gateway/session-binding.js
59627
59625
  var LIVE_SESSION_STATUSES = /* @__PURE__ */ new Set(["open", "active", "idle"]);
59628
59626
  async function bindRuntimeSession(host, sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2) {
59629
59627
  const runtimeLaneKey = runtimeEvent.runtimeLaneKey || sessionKey;
@@ -59676,21 +59674,7 @@ async function bindRuntimeSession(host, sessionKey, runtimeEvent, contextFilePat
59676
59674
  return binding;
59677
59675
  }
59678
59676
 
59679
- // ts/agent-core/dist/runtime-declaration.js
59680
- async function declareAgentRuntimeReport(client, input) {
59681
- const components = [];
59682
- if (input.runtimeVersion) {
59683
- components.push({ component: "bridge", version_raw: input.runtimeVersion, status: "ok" });
59684
- }
59685
- components.push({ component: "node", version_raw: process.versions.node, status: "ok" });
59686
- await client.putAgentRuntimeReport(input.orgId, {
59687
- ws_session_id: input.wsSessionId,
59688
- components,
59689
- features: ["runtime_contract"]
59690
- });
59691
- }
59692
-
59693
- // ts/agent-core/dist/dispatch-inactivity-deadline.js
59677
+ // ts/agent-core/dist/gateway/inactivity-deadline.js
59694
59678
  var DispatchInactivityDeadline = class {
59695
59679
  timeoutMs;
59696
59680
  onExpire;
@@ -59767,30 +59751,7 @@ var DispatchInactivityDeadlines = class {
59767
59751
  }
59768
59752
  };
59769
59753
 
59770
- // ts/agent-core/dist/routing.js
59771
- var MAX_CONCURRENT_FORKS = 20;
59772
- var defaultRoutingStrategy = (event, state) => {
59773
- if (state.mainCurrentTargetId === event.targetId) {
59774
- return { action: "buffer-main" };
59775
- }
59776
- const existingForkKey = state.activeForks.get(event.targetId);
59777
- if (existingForkKey)
59778
- return { action: "buffer-fork", forkKey: existingForkKey };
59779
- if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
59780
- return { action: "buffer-main" };
59781
- }
59782
- return { action: "new-fork" };
59783
- };
59784
- function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
59785
- const existingForkKey = state.activeForks.get(event.targetId);
59786
- if (existingForkKey)
59787
- return { action: "buffer-fork", forkKey: existingForkKey };
59788
- if (!state.mainDispatching)
59789
- return { action: "main" };
59790
- return strategy(event, state);
59791
- }
59792
-
59793
- // ts/agent-core/dist/step-retry-queue.js
59754
+ // ts/agent-core/dist/session/step-retry-queue.js
59794
59755
  var DEFAULT_RETRY_DELAYS_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
59795
59756
  async function raceWithDeadline(work, ms) {
59796
59757
  let timer;
@@ -60021,7 +59982,7 @@ var StepRetryQueue = class {
60021
59982
  }
60022
59983
  };
60023
59984
 
60024
- // ts/agent-core/dist/step-persister.js
59985
+ // ts/agent-core/dist/session/step-persister.js
60025
59986
  function isRetryableStepError(err) {
60026
59987
  return err instanceof ApiError && (err.status === 0 || err.status >= 500);
60027
59988
  }
@@ -60126,7 +60087,7 @@ var StepPersister = class {
60126
60087
  }
60127
60088
  };
60128
60089
 
60129
- // ts/agent-core/dist/session-lifecycle.js
60090
+ // ts/agent-core/dist/session/lifecycle.js
60130
60091
  var DEFAULT_RETRY_DELAYS_MS2 = [5e3, 15e3, 45e3, 135e3, 405e3];
60131
60092
  var defaultScheduler = {
60132
60093
  setTimeout(fn, ms) {
@@ -60500,7 +60461,7 @@ async function raceWithDeadline2(work, ms) {
60500
60461
  }
60501
60462
  }
60502
60463
 
60503
- // ts/agent-core/dist/fork-session-finalizer.js
60464
+ // ts/agent-core/dist/session/fork-finalizer.js
60504
60465
  var ForkSessionFinalizer = class {
60505
60466
  opts;
60506
60467
  // Ownership ledger: a session being finalized has exactly one finalization
@@ -60558,7 +60519,7 @@ var ForkSessionFinalizer = class {
60558
60519
  }
60559
60520
  };
60560
60521
 
60561
- // ts/agent-core/dist/session-state.js
60522
+ // ts/agent-core/dist/session/state.js
60562
60523
  function normalizeSessionKey(sessionKey) {
60563
60524
  return sessionKey.toLowerCase();
60564
60525
  }
@@ -60633,46 +60594,8 @@ function recordToolCall(sessionKey) {
60633
60594
  m.tool_call_count++;
60634
60595
  }
60635
60596
 
60636
- // ts/agent-core/dist/gateway-base.js
60637
- var AUTH_INVALID_EXIT_CODE = 86;
60638
- function classifyStartupFailure(err) {
60639
- const authRejection = authRejectionFrom(err);
60640
- return { exitCode: authRejection ? AUTH_INVALID_EXIT_CODE : 1, authRejection };
60641
- }
60642
- var TYPED_EVENT_KINDS = {
60643
- task_assign: { type: "task", ackSourceType: "task_activity" },
60644
- task_update: { type: "task", ackSourceType: "task_activity" },
60645
- task_comment: { type: "task_comment", ackSourceType: "comment" },
60646
- wiki_comment: { type: "wiki_comment", ackSourceType: "comment" },
60647
- "schedule.fire": { type: "schedule", ackSourceType: "schedule_run" },
60648
- external_trigger: { type: "external_trigger", ackSourceType: "external_trigger_run" },
60649
- channel_message: { type: "channel_message", ackSourceType: "channel_message" },
60650
- approval_decided: { type: "approval", ackSourceType: "approval" }
60651
- };
60652
- function parseShutdownDeadlineMs(raw) {
60653
- if (!raw)
60654
- return void 0;
60655
- const n = Number(raw);
60656
- if (!Number.isFinite(n) || n <= 0)
60657
- return void 0;
60658
- return Math.floor(n);
60659
- }
60660
- function parseForkDeadlineMs(raw) {
60661
- if (!raw)
60662
- return void 0;
60663
- const n = Number(raw);
60664
- if (!Number.isFinite(n) || n <= 0 || n > 2147483647)
60665
- return void 0;
60666
- return Math.floor(n);
60667
- }
60668
- function parseDispatchDeadlineMs(raw) {
60669
- if (!raw)
60670
- return void 0;
60671
- const n = Number(raw);
60672
- if (!Number.isFinite(n) || n < 0 || n > 2147483647)
60673
- return void 0;
60674
- return Math.floor(n);
60675
- }
60597
+ // ts/agent-core/dist/gateway/input-steps.js
60598
+ import { randomUUID as randomUUID4 } from "node:crypto";
60676
60599
  function inputStepIdempotencyKey(event) {
60677
60600
  if (event.type === "message" || event.type === "channel_message") {
60678
60601
  return event.messageId ? `input:${event.messageId}` : randomUUID4();
@@ -60751,52 +60674,1259 @@ function inputTriggerRef(event) {
60751
60674
  };
60752
60675
  }
60753
60676
  }
60754
- var ParallAgentGateway = class {
60755
- opts;
60756
- // In-process in-flight guard for message WorkItems (see LaneFlowHost).
60757
- dispatchedMessages = /* @__PURE__ */ new Set();
60758
- /**
60759
- * Consumption fence: no WorkItem is claimed before this connection's
60760
- * runtime contract is declared (handleHello). A claim made before the
60761
- * declaration would get no frame — and a frameless claim has nothing to
60762
- * run. Open until the first hello starts a declaration.
60763
- */
60764
- contractReady = Promise.resolve();
60765
- /** One re-declaration at a time; a burst of frameless claims collapses into it. */
60766
- redeclareInFlight = null;
60767
- injectedMainBufferEvents = /* @__PURE__ */ new WeakSet();
60768
- // Per-WorkItem failure backoff for typed dispatch consumption — see
60769
- // LaneFlowHost.typedRedriveBackoff in gateway-lane-flow.ts.
60770
- typedRedriveBackoff = /* @__PURE__ */ new Map();
60771
- forkStates = /* @__PURE__ */ new Map();
60772
- forkContinuationRetries = /* @__PURE__ */ new Map();
60773
- dispatchState = {
60774
- mainDispatching: false,
60775
- activeForks: /* @__PURE__ */ new Map(),
60776
- pendingForkResults: [],
60777
- mainBuffer: []
60778
- };
60779
- sessionId = "";
60780
- activeSessionId;
60781
- sessionBindings = /* @__PURE__ */ new Map();
60782
- heartbeatTimer = null;
60783
- lastHeartbeatAt = Date.now();
60784
- draining = false;
60785
- // Idle auto-compact hold on the main lane (gateway-idle-compact.ts).
60786
- idleCompact = createIdleCompactState();
60787
- /**
60788
- * Typed WorkItem ids whose drain group left the buffer but has not settled
60789
- * yet. isBufferedTypedWorkItem treats them as still buffered — a re-drive
60790
- * claim taken inside this window would turn the drain's fence-less close
60791
- * stale (its dedupe cleared, its release re-driving handled work) (#1149).
60792
- */
60793
- drainingTypedIds = /* @__PURE__ */ new Set();
60794
- // Graceful shutdown state. When SIGTERM / abort fires, `shuttingDown` flips
60795
- // to true so no new dispatches start, and `inFlightDispatches` counts runs
60796
- // still in progress. `shutdown()` awaits drain up to SHUTDOWN_DEADLINE_MS
60797
- // before tearing down the WS; see handleTermination caller.
60798
- shuttingDown = false;
60799
- inFlightDispatches = 0;
60677
+
60678
+ // ts/agent-core/dist/gateway/run-dispatch.js
60679
+ async function runDispatch(host, event, sessionKey, bodyForAgent, earlierEvents = [], captureText, inputLifecycle) {
60680
+ if (host.shuttingDown) {
60681
+ host.opts.log?.info(`skipping dispatch for ${event.messageId} (shutting down) \u2014 leaving unacked for catch-up on replacement pod`);
60682
+ return false;
60683
+ }
60684
+ if (host.pendingRestartNotification) {
60685
+ bodyForAgent = host.pendingRestartNotification + "\n\n---\n\n" + bodyForAgent;
60686
+ host.pendingRestartNotification = null;
60687
+ }
60688
+ resetDispatchMetrics(sessionKey);
60689
+ host.turnOutcomes.delete(sessionKey);
60690
+ return runInDispatchTrace({
60691
+ event,
60692
+ runtimeType: host.opts.runtimeType,
60693
+ sessionKey,
60694
+ dispatchEventId: event.dispatchEventId
60695
+ }, async (dispatchSpan) => {
60696
+ setSessionChatId(sessionKey, event.targetId);
60697
+ setSessionMessageId(sessionKey, event.messageId);
60698
+ setDispatchMessageId(sessionKey, event.messageId);
60699
+ setDispatchNoReply(sessionKey, event.noReply ?? false);
60700
+ const dispatchContext = host.buildDispatchContext(event, sessionKey);
60701
+ const contextFilePath = dispatchContext.contextFilePath;
60702
+ const stepIdFilePath = dispatchContext.stepIdFilePath;
60703
+ const stepTarget = resolveStepTarget(event);
60704
+ const activeLane = host.ledgerDisabled ? void 0 : host.laneLedger?.getForEvent(event);
60705
+ const laneContextFilePath2 = activeLane ? host.laneLedger?.laneContextPath(activeLane) : void 0;
60706
+ const contextBody = {
60707
+ session_id: dispatchContext.sessionId ?? null,
60708
+ chat_id: dispatchContext.chatId ?? null,
60709
+ trigger_message_id: dispatchContext.triggerMessageId ?? null,
60710
+ no_reply: dispatchContext.noReply,
60711
+ step_id: null,
60712
+ dispatch_event_id: activeLane?.typedDispatchEventId ?? activeLane?.folded.get(event.messageId) ?? null,
60713
+ lane: activeLane?.lane ?? null,
60714
+ settlement_mode: activeLane?.settlementMode ?? "legacy",
60715
+ target_uri: activeLane?.targetUri ?? null,
60716
+ thread_root_id: activeLane?.threadRootId ?? null,
60717
+ // Typed binding hint for the CLI: which task this dispatch is about
60718
+ // (parall task update attaches the typed effect only on a match).
60719
+ task_id: event.type === "task" ? event.targetId : null
60720
+ };
60721
+ if (contextFilePath) {
60722
+ host.writeContextFile(contextFilePath, contextBody);
60723
+ }
60724
+ if (laneContextFilePath2) {
60725
+ host.writeContextFile(laneContextFilePath2, contextBody);
60726
+ }
60727
+ patchDispatchContext({
60728
+ dispatchEventId: contextBody.dispatch_event_id,
60729
+ lane: contextBody.lane,
60730
+ targetUri: contextBody.target_uri,
60731
+ threadRootId: contextBody.thread_root_id
60732
+ });
60733
+ host.inFlightDispatches++;
60734
+ const abortAfterMs = host.DISPATCH_DEADLINE_MS;
60735
+ const dispatchDeadline = host.dispatchInactivityDeadlines.start(sessionKey, abortAfterMs > 0 ? abortAfterMs : host.INACTIVITY_WARN_MS, () => {
60736
+ if (abortAfterMs > 0) {
60737
+ host.opts.log?.warn(`dispatch inactivity deadline exceeded (${abortAfterMs}ms) for ${event.messageId} on ${sessionKey}; aborting`);
60738
+ try {
60739
+ host.opts.dispatchAdapter.abortDispatch?.(sessionKey);
60740
+ } catch (err) {
60741
+ host.opts.log?.warn(`abortDispatch threw for ${sessionKey}: ${String(err)}`);
60742
+ }
60743
+ return;
60744
+ }
60745
+ host.opts.log?.warn(`no runtime output for ${Math.round(host.INACTIVITY_WARN_MS / 6e4)} min on ${sessionKey} (${event.messageId}); the turn stays open \u2014 only the runtime finishing or a process restart ends it`);
60746
+ dispatchDeadline.rearm();
60747
+ });
60748
+ let binding = host.sessionBindings.get(sessionKey);
60749
+ let inputStepsCreated = false;
60750
+ let turnHandle;
60751
+ let dispatchError;
60752
+ let turnOutcomeEvent;
60753
+ let sawErrorEvent = false;
60754
+ const pendingSendCallIds = /* @__PURE__ */ new Set();
60755
+ const ensureTurnBegun = async () => {
60756
+ if (turnHandle || !binding)
60757
+ return;
60758
+ turnHandle = await host.sessionLifecycle.beginTurn(binding.agentSessionId, event.messageId);
60759
+ };
60760
+ try {
60761
+ await runInPhaseSpan("turn", async () => {
60762
+ for await (const runtimeEvent of host.opts.dispatchAdapter.dispatch({
60763
+ event,
60764
+ earlierEvents,
60765
+ bodyForAgent,
60766
+ sessionKey,
60767
+ context: dispatchContext,
60768
+ inputLifecycle,
60769
+ noteActivity: dispatchDeadline.touch
60770
+ })) {
60771
+ if (runtimeEvent.type !== "observation")
60772
+ dispatchDeadline.touch();
60773
+ if (runtimeEvent.type === "runtime_session") {
60774
+ const priorAgentSessionId = binding?.agentSessionId;
60775
+ binding = await runInPhaseSpan("session", () => host.bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2));
60776
+ if (activeLane) {
60777
+ bindLaneSession(activeLane, binding.agentSessionId);
60778
+ await host.laneLedger?.syncInputAttribution(activeLane);
60779
+ }
60780
+ if (event.targetType === "channel_conversation" && binding.agentSessionId !== priorAgentSessionId) {
60781
+ try {
60782
+ await host.opts.client.setChannelConversationSession(host.opts.config.org_id, event.targetId, binding.agentSessionId);
60783
+ } catch (err) {
60784
+ host.opts.log?.warn(`failed to record session mapping for channel conversation ${event.targetId}: ${String(err)}`);
60785
+ }
60786
+ }
60787
+ if (!inputStepsCreated) {
60788
+ await ensureTurnBegun();
60789
+ if (earlierEvents.length > 0) {
60790
+ await host.createInputStepsForEarlierEvents(binding.agentSessionId, earlierEvents);
60791
+ }
60792
+ await host.createInputStep(binding.agentSessionId, event);
60793
+ inputStepsCreated = true;
60794
+ }
60795
+ continue;
60796
+ }
60797
+ if (runtimeEvent.type === "observation") {
60798
+ if (binding?.runtimeSessionId === runtimeEvent.runtimeSessionId) {
60799
+ await host.createRuntimeStep(binding.agentSessionId, stepTarget, runtimeEvent);
60800
+ } else {
60801
+ host.opts.log?.warn("runtime observation has no matching active session binding");
60802
+ }
60803
+ continue;
60804
+ }
60805
+ if (runtimeEvent.type === "turn_outcome") {
60806
+ const outcomeEvent = redactTurnOutcome(runtimeEvent, [host.opts.config.api_key]);
60807
+ turnOutcomeEvent = outcomeEvent;
60808
+ if (outcomeEvent.outcome === "ok") {
60809
+ host.turnOutcomes.delete(sessionKey);
60810
+ continue;
60811
+ }
60812
+ host.recordTurnClassification(sessionKey, outcomeEvent.outcome === "usage_limit" ? {
60813
+ kind: "deferred",
60814
+ outcomeClass: outcomeEvent.outcome,
60815
+ ...outcomeEvent.retryAt ? { retryAt: outcomeEvent.retryAt } : {}
60816
+ } : {
60817
+ kind: "error",
60818
+ outcomeClass: outcomeEvent.outcome,
60819
+ ...outcomeEvent.detail ? { detail: outcomeEvent.detail } : {}
60820
+ });
60821
+ const failure = describeTurnOutcomeFailure(outcomeEvent);
60822
+ host.opts.log?.warn(`turn outcome: ${failure.warn} (dispatch=${contextBody.dispatch_event_id ?? "-"} lane=${contextBody.lane ?? "-"})`);
60823
+ if (binding) {
60824
+ await ensureTurnBegun();
60825
+ if (!inputStepsCreated) {
60826
+ if (earlierEvents.length > 0) {
60827
+ await host.createInputStepsForEarlierEvents(binding.agentSessionId, earlierEvents);
60828
+ }
60829
+ await host.createInputStep(binding.agentSessionId, event);
60830
+ inputStepsCreated = true;
60831
+ }
60832
+ await host.createRuntimeStep(binding.agentSessionId, stepTarget, {
60833
+ type: "error",
60834
+ message: failure.stepMessage
60835
+ }, stepIdFilePath, contextFilePath, laneContextFilePath2);
60836
+ }
60837
+ continue;
60838
+ }
60839
+ if (!binding) {
60840
+ const detail = runtimeEvent.type === "error" ? `: ${runtimeEvent.message}` : "";
60841
+ throw new Error(`runtime emitted ${runtimeEvent.type} before runtime_session${detail}`);
60842
+ }
60843
+ await ensureTurnBegun();
60844
+ if (!inputStepsCreated) {
60845
+ if (earlierEvents.length > 0) {
60846
+ await host.createInputStepsForEarlierEvents(binding.agentSessionId, earlierEvents);
60847
+ }
60848
+ await host.createInputStep(binding.agentSessionId, event);
60849
+ inputStepsCreated = true;
60850
+ }
60851
+ if (activeLane && !host.ledgerDisabled) {
60852
+ host.laneLedger?.maybeRenew(activeLane);
60853
+ }
60854
+ if (captureText && runtimeEvent.type === "text" && runtimeEvent.text) {
60855
+ captureText.push(runtimeEvent.text);
60856
+ }
60857
+ if (runtimeEvent.type === "text" && runtimeEvent.text.length > 0) {
60858
+ recordDeliverText(sessionKey, runtimeEvent.text.length);
60859
+ } else if (runtimeEvent.type === "tool_call") {
60860
+ recordToolCall(sessionKey);
60861
+ const cmd = extractShellCommand(runtimeEvent.input);
60862
+ if (isParallSendCommand(cmd)) {
60863
+ pendingSendCallIds.add(runtimeEvent.callId);
60864
+ } else if (isParallNoReplyCommand(cmd)) {
60865
+ recordNoReply(sessionKey);
60866
+ }
60867
+ } else if (runtimeEvent.type === "tool_result" && pendingSendCallIds.delete(runtimeEvent.callId)) {
60868
+ recordMessageSend(sessionKey, !runtimeEvent.error);
60869
+ }
60870
+ if (runtimeEvent.type === "error") {
60871
+ sawErrorEvent = true;
60872
+ host.recordTurnErrorSignal(sessionKey, runtimeEvent.message);
60873
+ }
60874
+ await host.createRuntimeStep(binding.agentSessionId, stepTarget, runtimeEvent.type === "error" ? { ...runtimeEvent, message: host.redactRuntimeText(runtimeEvent.message) } : runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2);
60875
+ }
60876
+ if (!binding) {
60877
+ binding = host.sessionBindings.get(sessionKey);
60878
+ }
60879
+ if (!binding) {
60880
+ throw new Error("runtime completed without runtime_session");
60881
+ }
60882
+ if (!inputStepsCreated) {
60883
+ await ensureTurnBegun();
60884
+ if (earlierEvents.length > 0) {
60885
+ await host.createInputStepsForEarlierEvents(binding.agentSessionId, earlierEvents);
60886
+ }
60887
+ await host.createInputStep(binding.agentSessionId, event);
60888
+ }
60889
+ });
60890
+ } catch (err) {
60891
+ dispatchError = err;
60892
+ let staleDetected = host.isSessionNotLiveError(err);
60893
+ if (!staleDetected && binding) {
60894
+ try {
60895
+ await ensureTurnBegun();
60896
+ await host.createRuntimeStep(binding.agentSessionId, stepTarget, {
60897
+ type: "error",
60898
+ message: `Dispatch failed: ${host.redactRuntimeText(String(err))}`
60899
+ }, stepIdFilePath, contextFilePath, laneContextFilePath2);
60900
+ } catch (stepErr) {
60901
+ if (host.isSessionNotLiveError(stepErr))
60902
+ staleDetected = true;
60903
+ }
60904
+ }
60905
+ if (staleDetected && binding) {
60906
+ host.opts.log?.warn?.(`session ${binding.agentSessionId} is stale (mid-dispatch), triggering recovery for ${sessionKey}`);
60907
+ host.sessionBindings.delete(sessionKey);
60908
+ host.stepPersister.dropSession(binding.agentSessionId);
60909
+ host.sessionLifecycle.dropSession(binding.agentSessionId);
60910
+ if (sessionKey === host.opts.runtimeKey) {
60911
+ host.activeSessionId = void 0;
60912
+ }
60913
+ try {
60914
+ await host.opts.onSessionStale?.(sessionKey);
60915
+ } catch (e) {
60916
+ host.opts.log?.warn?.(`onSessionStale failed: ${e}`);
60917
+ }
60918
+ host.opts.log?.info?.(`stale session self-heal complete for ${sessionKey} \u2014 next dispatch will create a fresh session`);
60919
+ binding = void 0;
60920
+ }
60921
+ throw err;
60922
+ } finally {
60923
+ dispatchDeadline.dispose();
60924
+ const metricsSnapshot = getDispatchMetrics(sessionKey);
60925
+ const durationMs = metricsSnapshot ? Date.now() - metricsSnapshot.started_at : 0;
60926
+ const effectiveOutcome = turnOutcomeEvent?.outcome ?? (dispatchError || sawErrorEvent ? "runtime_crash" : "ok");
60927
+ annotateDispatchSpan(dispatchSpan, metricsSnapshot, dispatchError, turnOutcomeEvent);
60928
+ recordDispatchMetric(event, host.opts.runtimeType, durationMs, effectiveOutcome);
60929
+ recordTurnUsage(turnOutcomeEvent?.usage, host.opts.runtimeType);
60930
+ if (metricsSnapshot && !dispatchError && event.type === "message" && event.targetId?.startsWith("cht_") && !event.noReply && metricsSnapshot.deliver_text_chunks > 0 && metricsSnapshot.message_send_successes === 0 && !metricsSnapshot.no_reply_called) {
60931
+ recordMissingReply(host.opts.runtimeType, effectiveOutcome);
60932
+ }
60933
+ clearDispatchMetrics(sessionKey);
60934
+ if (turnHandle) {
60935
+ host.sessionLifecycle.finishTurn(turnHandle);
60936
+ }
60937
+ clearSessionMessageId(sessionKey);
60938
+ clearDispatchMessageId(sessionKey);
60939
+ clearDispatchNoReply(sessionKey);
60940
+ if (contextFilePath) {
60941
+ host.updateContextFileStepId(contextFilePath, null);
60942
+ } else if (stepIdFilePath) {
60943
+ host.clearStepIdFile(stepIdFilePath);
60944
+ }
60945
+ if (laneContextFilePath2) {
60946
+ host.updateContextFileStepId(laneContextFilePath2, null);
60947
+ }
60948
+ host.inFlightDispatches--;
60949
+ host.notifyDrainWaiters();
60950
+ }
60951
+ return true;
60952
+ });
60953
+ }
60954
+
60955
+ // ts/agent-core/dist/gateway/fork-state.js
60956
+ var FORK_CONTINUATION_RETRY_CAP = 256;
60957
+ function forkContinuationRetryKey(event) {
60958
+ if (event.type === "message" || event.type === "channel_message") {
60959
+ return event.messageId ? `message:${event.messageId}` : void 0;
60960
+ }
60961
+ return event.dispatchEventId ? `dispatch:${event.dispatchEventId}` : void 0;
60962
+ }
60963
+ function resolveForkContinuationPrefix(pendingResults, retries, event) {
60964
+ const retryKey = forkContinuationRetryKey(event);
60965
+ const retained = retryKey ? retries.get(retryKey) : void 0;
60966
+ if (retained)
60967
+ return retained;
60968
+ const prefix = buildForkResultPrefix(pendingResults.filter((result) => result.sourceEvent.targetId === event.targetId));
60969
+ return prefix || void 0;
60970
+ }
60971
+ function retainForkContinuationRetries(retries, events, prefix) {
60972
+ if (!prefix)
60973
+ return;
60974
+ for (const event of events) {
60975
+ const key = forkContinuationRetryKey(event);
60976
+ if (!key)
60977
+ continue;
60978
+ if (retries.delete(key) === false && retries.size >= FORK_CONTINUATION_RETRY_CAP) {
60979
+ const oldest = retries.keys().next().value;
60980
+ if (oldest !== void 0)
60981
+ retries.delete(oldest);
60982
+ }
60983
+ retries.set(key, prefix);
60984
+ }
60985
+ }
60986
+ function clearForkContinuationRetries(retries, events) {
60987
+ for (const event of events) {
60988
+ const key = forkContinuationRetryKey(event);
60989
+ if (key)
60990
+ retries.delete(key);
60991
+ }
60992
+ }
60993
+ function createActiveForkState(fork, targetId, continuationPrefix) {
60994
+ return {
60995
+ fork,
60996
+ targetId,
60997
+ queue: [],
60998
+ processedEvents: [],
60999
+ continuationPrefix,
61000
+ deadlineTimer: null,
61001
+ deadlineExceeded: false
61002
+ };
61003
+ }
61004
+
61005
+ // ts/agent-core/dist/gateway/fork-drain.js
61006
+ function abortFork(host, targetId, reason) {
61007
+ const forkState = host.forkStates.get(targetId);
61008
+ if (!forkState)
61009
+ return;
61010
+ host.opts.log?.warn(`aborting fork for ${targetId}: ${reason}`);
61011
+ forkState.deadlineExceeded = true;
61012
+ if (forkState.deadlineTimer) {
61013
+ clearTimeout(forkState.deadlineTimer);
61014
+ forkState.deadlineTimer = null;
61015
+ }
61016
+ host.dispatchState.activeForks.delete(targetId);
61017
+ host.forkStates.delete(targetId);
61018
+ retainForkContinuationRetries(host.forkContinuationRetries, forkState.queue.map((item) => item.event), forkState.continuationPrefix);
61019
+ for (const item of forkState.queue.splice(0)) {
61020
+ item.resolve(false);
61021
+ }
61022
+ if (host.opts.dispatchAdapter.cleanupFork) {
61023
+ const forkBinding = host.sessionBindings.get(forkState.fork.sessionKey);
61024
+ const cleanupOpts = {
61025
+ fork: forkState.fork,
61026
+ context: {
61027
+ accountId: host.opts.accountId,
61028
+ apiUrl: host.opts.config.parall_url,
61029
+ apiKey: host.opts.config.api_key,
61030
+ orgId: host.opts.config.org_id,
61031
+ agentUserId: host.opts.agentUserId,
61032
+ runtimeType: host.opts.runtimeType,
61033
+ runtimeKey: host.opts.runtimeKey,
61034
+ sessionId: forkBinding?.agentSessionId,
61035
+ noReply: false,
61036
+ client: host.opts.client,
61037
+ log: host.opts.log
61038
+ }
61039
+ };
61040
+ void Promise.resolve().then(() => host.opts.dispatchAdapter.cleanupFork?.(cleanupOpts)).catch((err) => {
61041
+ host.opts.log?.warn(`abortFork cleanupFork error for ${targetId}: ${String(err)}`);
61042
+ });
61043
+ }
61044
+ }
61045
+ function runForkDrainLoop(host, fork) {
61046
+ return runOutsideDispatchScope(() => host.forkDrainLoop(fork));
61047
+ }
61048
+ async function forkDrainLoop(host, fork) {
61049
+ let lastCapturedText = [];
61050
+ try {
61051
+ while (fork.queue.length > 0) {
61052
+ if (host.shuttingDown || fork.deadlineExceeded) {
61053
+ for (const item of fork.queue.splice(0))
61054
+ item.resolve(false);
61055
+ break;
61056
+ }
61057
+ let items;
61058
+ const head = fork.queue[0];
61059
+ if (head && host.usesLaneLedger(head.event)) {
61060
+ const headKey = host.dispatchGroupKey(head.event);
61061
+ const splitAt = fork.queue.findIndex((it) => host.dispatchGroupKey(it.event) !== headKey);
61062
+ items = splitAt === -1 ? fork.queue.splice(0) : fork.queue.splice(0, splitAt);
61063
+ } else {
61064
+ items = fork.queue.splice(0);
61065
+ }
61066
+ const events = items.map((item) => item.event);
61067
+ const last = events[events.length - 1];
61068
+ const earlier = events.slice(0, -1);
61069
+ retainForkContinuationRetries(host.forkContinuationRetries, events, fork.continuationPrefix);
61070
+ try {
61071
+ const batchText = [];
61072
+ const bodyPrefix = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last);
61073
+ const body = bodyPrefix + eventBody(last);
61074
+ let dispatched;
61075
+ if (host.usesLaneLedger(last)) {
61076
+ const outcome = await host.dispatchLaneGroup({
61077
+ events,
61078
+ sessionKey: fork.fork.sessionKey,
61079
+ bodyPrefix,
61080
+ earlier,
61081
+ captureText: batchText,
61082
+ // Per-LANE residue check (parity with the main-buffer path):
61083
+ // the fork queue can hold several lanes (channel + thread of
61084
+ // the same chat). A whole-queue check would defer THIS lane's
61085
+ // complete behind another lane's items and never revisit it —
61086
+ // its members would sit received until lease expiry.
61087
+ hasMoreLocal: () => fork.queue.some((it) => host.dispatchGroupKey(it.event) === host.dispatchGroupKey(last))
61088
+ });
61089
+ if (outcome === "foreign") {
61090
+ for (const item of items)
61091
+ item.resolve(false);
61092
+ break;
61093
+ }
61094
+ if (outcome === "failed" || outcome === "deferred") {
61095
+ for (const item of items)
61096
+ item.resolve(false);
61097
+ continue;
61098
+ }
61099
+ dispatched = outcome === "dispatched";
61100
+ } else {
61101
+ dispatched = await host.runDispatch(last, fork.fork.sessionKey, body, earlier, batchText);
61102
+ if (dispatched && host.typedLedgerEventIds(events) && host.consumeTurnError(fork.fork.sessionKey)) {
61103
+ host.opts.log?.info(`typed fork turn for ${last.messageId} surfaced a runtime error \u2014 releasing for retry`);
61104
+ for (const item of items)
61105
+ item.resolve(false);
61106
+ continue;
61107
+ }
61108
+ }
61109
+ if (!dispatched) {
61110
+ for (const item of items) {
61111
+ item.resolve(false);
61112
+ }
61113
+ break;
61114
+ }
61115
+ if (batchText.length > 0)
61116
+ lastCapturedText = batchText;
61117
+ clearForkContinuationRetries(host.forkContinuationRetries, events);
61118
+ fork.continuationPrefix = void 0;
61119
+ fork.processedEvents.push(...events);
61120
+ for (const item of items) {
61121
+ item.resolve(true);
61122
+ }
61123
+ } catch (err) {
61124
+ host.opts.log?.error(`fork dispatch failed for ${last.messageId}: ${String(err)}`);
61125
+ for (const item of items) {
61126
+ item.resolve(false);
61127
+ }
61128
+ break;
61129
+ }
61130
+ }
61131
+ for (const remaining of fork.queue.splice(0)) {
61132
+ remaining.resolve(false);
61133
+ }
61134
+ } finally {
61135
+ host.turnOutcomes.delete(fork.fork.sessionKey);
61136
+ if (fork.deadlineTimer) {
61137
+ clearTimeout(fork.deadlineTimer);
61138
+ fork.deadlineTimer = null;
61139
+ }
61140
+ if (fork.processedEvents.length > 0) {
61141
+ const first = fork.processedEvents[0];
61142
+ const agentSummary = lastCapturedText.join("").trim() || void 0;
61143
+ let historyPath;
61144
+ try {
61145
+ historyPath = host.opts.dispatchAdapter.getSessionHistoryPath?.(fork.fork.sessionKey);
61146
+ } catch (err) {
61147
+ host.opts.log?.warn?.(`failed to resolve fork history path: ${String(err)}`);
61148
+ }
61149
+ host.dispatchState.pendingForkResults.push({
61150
+ forkSessionKey: fork.fork.sessionKey,
61151
+ sourceEvent: {
61152
+ type: first.type,
61153
+ targetId: fork.targetId,
61154
+ summary: fork.processedEvents.length === 1 ? `${first.type} in ${fork.targetId}` : `${fork.processedEvents.length} events in ${fork.targetId}`
61155
+ },
61156
+ eventBodies: fork.processedEvents.map((e) => forkResultBody(e)),
61157
+ actions: [],
61158
+ agentSummary,
61159
+ historyPath
61160
+ });
61161
+ }
61162
+ if (host.forkStates.get(fork.targetId) === fork) {
61163
+ host.forkStates.delete(fork.targetId);
61164
+ }
61165
+ if (host.dispatchState.activeForks.get(fork.targetId) === fork.fork.sessionKey) {
61166
+ host.dispatchState.activeForks.delete(fork.targetId);
61167
+ }
61168
+ const forkBinding = host.sessionBindings.get(fork.fork.sessionKey);
61169
+ if (host.opts.dispatchAdapter.cleanupFork) {
61170
+ const cleanupOpts = {
61171
+ fork: fork.fork,
61172
+ context: {
61173
+ accountId: host.opts.accountId,
61174
+ apiUrl: host.opts.config.parall_url,
61175
+ apiKey: host.opts.config.api_key,
61176
+ orgId: host.opts.config.org_id,
61177
+ agentUserId: host.opts.agentUserId,
61178
+ runtimeType: host.opts.runtimeType,
61179
+ runtimeKey: host.opts.runtimeKey,
61180
+ sessionId: forkBinding?.agentSessionId,
61181
+ noReply: false,
61182
+ client: host.opts.client,
61183
+ log: host.opts.log
61184
+ }
61185
+ };
61186
+ try {
61187
+ await host.opts.dispatchAdapter.cleanupFork(cleanupOpts);
61188
+ } catch (err) {
61189
+ host.opts.log?.warn(`fork cleanupFork error for ${fork.targetId}: ${String(err)}`);
61190
+ }
61191
+ }
61192
+ if (forkBinding) {
61193
+ await host.forkFinalizer.finalize(forkBinding.agentSessionId, () => {
61194
+ if (host.sessionBindings.get(fork.fork.sessionKey) === forkBinding) {
61195
+ host.sessionBindings.delete(fork.fork.sessionKey);
61196
+ }
61197
+ });
61198
+ }
61199
+ }
61200
+ }
61201
+
61202
+ // ts/agent-core/dist/gateway/main-drain.js
61203
+ async function mainDrainLoop(host) {
61204
+ if (host.draining)
61205
+ return;
61206
+ host.draining = true;
61207
+ try {
61208
+ while (host.idleCompact.inFlight)
61209
+ await host.idleCompact.inFlight;
61210
+ while (host.dispatchState.mainBuffer.length > 0) {
61211
+ while (hasMainSteers(host.dispatchState))
61212
+ await waitForMainSteers(host.dispatchState);
61213
+ if (host.shuttingDown) {
61214
+ host.opts.log?.info(`drainMainBuffer halted (shutting down) \u2014 ${host.dispatchState.mainBuffer.length} buffered, ${host.dispatchState.pendingForkResults.length} pending fork results left for catch-up`);
61215
+ break;
61216
+ }
61217
+ const groupKey = host.dispatchGroupKey(host.dispatchState.mainBuffer[0]);
61218
+ const hasPendingInjections = host.opts.dispatchAdapter.hasPendingInjections?.(host.opts.runtimeKey) ?? false;
61219
+ const events = shiftMainBufferGroup(host.laneFlowHost(), groupKey, hasPendingInjections && host.opts.dispatchAdapter.inputLifecycleMode === "explicit");
61220
+ const event = events[events.length - 1];
61221
+ const earlier = events.slice(0, -1);
61222
+ const pendingFork = hasPendingInjections ? [] : host.dispatchState.pendingForkResults.splice(0);
61223
+ const forkPrefix = buildForkResultPrefix(pendingFork);
61224
+ host.dispatchState.mainCurrentTargetId = event.targetId;
61225
+ host.mainCurrentGroupKey = groupKey;
61226
+ host.dispatchState.mainPreDispatchBranchPoint = host.opts.dispatchAdapter.getBranchPoint?.(host.opts.runtimeKey);
61227
+ if (host.usesLaneLedger(event)) {
61228
+ let outcome;
61229
+ try {
61230
+ outcome = await host.dispatchLaneGroup({
61231
+ events,
61232
+ sessionKey: host.opts.runtimeKey,
61233
+ bodyPrefix: forkPrefix,
61234
+ earlier,
61235
+ hasMoreLocal: () => host.dispatchState.mainBuffer.some((e) => host.dispatchGroupKey(e) === groupKey)
61236
+ });
61237
+ } catch (err) {
61238
+ host.opts.log?.error(`lane dispatch failed for ${event.messageId}: ${String(err)}`);
61239
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61240
+ for (const ev of events)
61241
+ host.dispatchedMessages.delete(ev.messageId);
61242
+ continue;
61243
+ }
61244
+ if (outcome === "shutdown") {
61245
+ host.dispatchState.mainBuffer.unshift(...events);
61246
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61247
+ break;
61248
+ }
61249
+ if (outcome === "foreign") {
61250
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61251
+ continue;
61252
+ }
61253
+ if (outcome === "failed" || outcome === "deferred") {
61254
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61255
+ continue;
61256
+ }
61257
+ continue;
61258
+ }
61259
+ const typedRefs = host.typedLedgerEventIds(events);
61260
+ const drainingIds = events.map((ev) => ev.dispatchEventId).filter((id) => !!id);
61261
+ for (const id of drainingIds)
61262
+ host.drainingTypedIds.add(id);
61263
+ try {
61264
+ if (!typedRefs) {
61265
+ try {
61266
+ await host.emitDispatchReceived(event);
61267
+ } catch (err) {
61268
+ host.opts.log?.warn?.(`mark-received failed for buffered dispatch, leaving unacked for retry: ${String(err)}`);
61269
+ host.dispatchState.mainBuffer.unshift(...events);
61270
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61271
+ break;
61272
+ }
61273
+ }
61274
+ const isTypedGroup = events.every(isTypedEvent);
61275
+ const body = isTypedGroup && events.length > 1 && host.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => eventBody(ev)).join("\n\n") : eventBody(event);
61276
+ let dispatched;
61277
+ try {
61278
+ dispatched = await host.runDispatch(event, host.opts.runtimeKey, forkPrefix + body, earlier);
61279
+ } catch (err) {
61280
+ if (!isTypedGroup)
61281
+ throw err;
61282
+ host.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}): ${String(err)}`);
61283
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61284
+ continue;
61285
+ }
61286
+ if (!dispatched) {
61287
+ host.dispatchState.mainBuffer.unshift(...events);
61288
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61289
+ break;
61290
+ }
61291
+ if (typedRefs) {
61292
+ await settleDrainedTypedGroup(host.laneFlowHost(), events, typedRefs, host.consumeTurnError(host.opts.runtimeKey));
61293
+ continue;
61294
+ }
61295
+ for (const bufferedEvent of events) {
61296
+ const sourceType = bufferedEvent.ackSourceType ?? (bufferedEvent.type === "task" ? "task_activity" : "message");
61297
+ const sourceId = bufferedEvent.ackSourceId ?? bufferedEvent.messageId;
61298
+ host.opts.client.ackDispatch(host.opts.config.org_id, {
61299
+ source_type: sourceType,
61300
+ source_id: sourceId
61301
+ }).catch(() => {
61302
+ });
61303
+ }
61304
+ } finally {
61305
+ for (const id of drainingIds)
61306
+ host.drainingTypedIds.delete(id);
61307
+ }
61308
+ }
61309
+ } finally {
61310
+ host.draining = false;
61311
+ host.dispatchState.mainDispatching = false;
61312
+ host.dispatchState.mainCurrentTargetId = void 0;
61313
+ host.mainCurrentGroupKey = void 0;
61314
+ host.dispatchState.mainPreDispatchBranchPoint = void 0;
61315
+ if (!host.shuttingDown && host.dispatchState.mainBuffer.length > 0) {
61316
+ setTimeout(() => {
61317
+ if (!host.draining && !host.dispatchState.mainDispatching && host.dispatchState.mainBuffer.length > 0) {
61318
+ host.dispatchState.mainDispatching = true;
61319
+ void host.drainMainBuffer();
61320
+ }
61321
+ }, 5e3).unref();
61322
+ }
61323
+ }
61324
+ }
61325
+
61326
+ // ts/agent-core/dist/routing.js
61327
+ var MAX_CONCURRENT_FORKS = 20;
61328
+ var defaultRoutingStrategy = (event, state) => {
61329
+ if (state.mainCurrentTargetId === event.targetId) {
61330
+ return { action: "buffer-main" };
61331
+ }
61332
+ const existingForkKey = state.activeForks.get(event.targetId);
61333
+ if (existingForkKey)
61334
+ return { action: "buffer-fork", forkKey: existingForkKey };
61335
+ if (state.activeForks.size >= MAX_CONCURRENT_FORKS) {
61336
+ return { action: "buffer-main" };
61337
+ }
61338
+ return { action: "new-fork" };
61339
+ };
61340
+ function routeTrigger(event, state, strategy = defaultRoutingStrategy) {
61341
+ const existingForkKey = state.activeForks.get(event.targetId);
61342
+ if (existingForkKey)
61343
+ return { action: "buffer-fork", forkKey: existingForkKey };
61344
+ if (!state.mainDispatching)
61345
+ return { action: "main" };
61346
+ return strategy(event, state);
61347
+ }
61348
+
61349
+ // ts/agent-core/dist/gateway/inbound.js
61350
+ async function handleInboundEvent(host, event) {
61351
+ let disposition = routeTrigger(event, host.dispatchState);
61352
+ if (host.idleCompact.inFlight && (disposition.action === "main" || disposition.action === "new-fork")) {
61353
+ disposition = { action: "buffer-main" };
61354
+ }
61355
+ if (disposition.action === "main") {
61356
+ clearForkContinuationRetries(host.forkContinuationRetries, [event]);
61357
+ }
61358
+ switch (disposition.action) {
61359
+ case "main": {
61360
+ const pendingFork = host.dispatchState.pendingForkResults.splice(0);
61361
+ const forkPrefix = buildForkResultPrefix(pendingFork);
61362
+ host.dispatchState.mainDispatching = true;
61363
+ host.dispatchState.mainCurrentTargetId = event.targetId;
61364
+ host.mainCurrentGroupKey = host.dispatchGroupKey(event);
61365
+ host.dispatchState.mainPreDispatchBranchPoint = host.opts.dispatchAdapter.getBranchPoint?.(host.opts.runtimeKey);
61366
+ if (host.usesLaneLedger(event)) {
61367
+ let outcome = "shutdown";
61368
+ try {
61369
+ try {
61370
+ outcome = await host.dispatchLaneGroup({
61371
+ events: [event],
61372
+ sessionKey: host.opts.runtimeKey,
61373
+ bodyPrefix: forkPrefix,
61374
+ earlier: [],
61375
+ hasMoreLocal: () => host.dispatchState.mainBuffer.some((e) => host.dispatchGroupKey(e) === host.dispatchGroupKey(event))
61376
+ });
61377
+ } catch (err) {
61378
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61379
+ throw err;
61380
+ }
61381
+ if (outcome !== "dispatched") {
61382
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61383
+ }
61384
+ } finally {
61385
+ await host.drainMainBuffer();
61386
+ }
61387
+ return outcome === "dispatched";
61388
+ }
61389
+ const typedRefs = host.typedLedgerEventIds([event]);
61390
+ if (!typedRefs) {
61391
+ try {
61392
+ await host.emitDispatchReceived(event);
61393
+ } catch (err) {
61394
+ host.opts.log?.warn?.(`mark-received failed, leaving unacked for retry: ${String(err)}`);
61395
+ host.dispatchState.mainDispatching = false;
61396
+ host.dispatchState.mainCurrentTargetId = void 0;
61397
+ host.mainCurrentGroupKey = void 0;
61398
+ host.dispatchState.mainPreDispatchBranchPoint = void 0;
61399
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61400
+ return false;
61401
+ }
61402
+ }
61403
+ let dispatched = false;
61404
+ try {
61405
+ dispatched = await host.runDispatch(event, host.opts.runtimeKey, forkPrefix + eventBody(event));
61406
+ if (dispatched && typedRefs && host.consumeTurnError(host.opts.runtimeKey)) {
61407
+ host.opts.log?.info(`typed dispatch turn for ${event.messageId} surfaced a runtime error \u2014 releasing for retry`);
61408
+ dispatched = false;
61409
+ }
61410
+ if (!dispatched) {
61411
+ host.dispatchState.pendingForkResults.unshift(...pendingFork);
61412
+ }
61413
+ } finally {
61414
+ await host.drainMainBuffer();
61415
+ }
61416
+ return dispatched;
61417
+ }
61418
+ case "buffer-main": {
61419
+ if (host.shuttingDown) {
61420
+ return false;
61421
+ }
61422
+ if (host.isBufferedTypedWorkItem(event.dispatchEventId)) {
61423
+ return false;
61424
+ }
61425
+ host.dispatchState.mainBuffer.push(event);
61426
+ const typedAheadInBuffer = host.dispatchState.mainBuffer.some(isTypedEvent);
61427
+ if (host.usesLaneLedger(event)) {
61428
+ if (!host.idleCompact.inFlight && !typedAheadInBuffer && host.mainCurrentGroupKey === host.dispatchGroupKey(event) && host.opts.dispatchAdapter.enqueueDuringDispatch != null) {
61429
+ await steerLaneMessage(host.laneFlowHost(), event);
61430
+ }
61431
+ } else if (
61432
+ // Lane events only. A typed event (task_comment/schedule/…)
61433
+ // rides the typed-consume contract — buffer-main resolves false and
61434
+ // the claim releases for re-drive — so an injection here is exactly
61435
+ // the forbidden un-folded injection: the LLM sees the content while
61436
+ // the WorkItem stays live, and every re-drive injects it AGAIN (the
61437
+ // 7/16 watcher duplicate-delivery loop, #1149). Typed events stay
61438
+ // buffered; the drain claims them as their own turn.
61439
+ !isTypedEvent(event) && event.frame != null && !host.idleCompact.inFlight && !typedAheadInBuffer && host.dispatchState.mainCurrentTargetId === event.targetId && await host.opts.dispatchAdapter.enqueueDuringDispatch?.(host.opts.runtimeKey, eventBody(event))
61440
+ ) {
61441
+ host.opts.log?.info(`steer injected for ${event.messageId} (will drain for bookkeeping)`);
61442
+ }
61443
+ if (!host.dispatchState.mainDispatching && !host.draining && host.dispatchState.mainBuffer.length > 0) {
61444
+ host.dispatchState.mainDispatching = true;
61445
+ void host.drainMainBuffer();
61446
+ }
61447
+ return false;
61448
+ }
61449
+ case "buffer-fork": {
61450
+ const activeFork = host.forkStates.get(event.targetId);
61451
+ if (!activeFork) {
61452
+ host.dispatchState.mainBuffer.push(event);
61453
+ return false;
61454
+ }
61455
+ return new Promise((resolve3) => {
61456
+ activeFork.queue.push({ event, resolve: resolve3 });
61457
+ });
61458
+ }
61459
+ case "new-fork": {
61460
+ if (!host.opts.dispatchAdapter.forkSession) {
61461
+ host.dispatchState.mainBuffer.push(event);
61462
+ return false;
61463
+ }
61464
+ const continuationPrefix = resolveForkContinuationPrefix(host.dispatchState.pendingForkResults, host.forkContinuationRetries, event);
61465
+ if (!host.usesLaneLedger(event) && !host.typedLedgerEventIds([event])) {
61466
+ try {
61467
+ await host.emitDispatchReceived(event);
61468
+ } catch (err) {
61469
+ host.opts.log?.warn?.(`mark-received failed for fork dispatch, leaving unacked for retry: ${String(err)}`);
61470
+ host.dispatchState.mainBuffer.push(event);
61471
+ return false;
61472
+ }
61473
+ }
61474
+ const fork = await host.opts.dispatchAdapter.forkSession({
61475
+ sessionKey: host.opts.runtimeKey,
61476
+ context: host.buildDispatchContext(event, host.opts.runtimeKey),
61477
+ preDispatchBranchPoint: host.dispatchState.mainPreDispatchBranchPoint
61478
+ });
61479
+ if (!fork) {
61480
+ host.opts.log?.warn(`fork failed, buffering event for main session`);
61481
+ host.dispatchState.mainBuffer.push(event);
61482
+ return false;
61483
+ }
61484
+ const activeFork = createActiveForkState(fork, event.targetId, continuationPrefix);
61485
+ host.forkStates.set(event.targetId, activeFork);
61486
+ host.dispatchState.activeForks.set(event.targetId, fork.sessionKey);
61487
+ if (host.FORK_DEADLINE_MS > 0) {
61488
+ activeFork.deadlineTimer = setTimeout(() => {
61489
+ host.abortFork(event.targetId, `deadline exceeded (${host.FORK_DEADLINE_MS}ms)`);
61490
+ }, host.FORK_DEADLINE_MS);
61491
+ }
61492
+ const firstEventPromise = new Promise((resolve3) => {
61493
+ activeFork.queue.push({ event, resolve: resolve3 });
61494
+ });
61495
+ host.runForkDrainLoop(activeFork).catch((err) => {
61496
+ host.opts.log?.error(`fork drain loop error: ${String(err)}`);
61497
+ });
61498
+ return firstEventPromise;
61499
+ }
61500
+ }
61501
+ }
61502
+
61503
+ // ts/agent-core/dist/gateway/work-items.js
61504
+ var TYPED_EVENT_KINDS = {
61505
+ task_assign: { type: "task", ackSourceType: "task_activity" },
61506
+ task_update: { type: "task", ackSourceType: "task_activity" },
61507
+ task_comment: { type: "task_comment", ackSourceType: "comment" },
61508
+ wiki_comment: { type: "wiki_comment", ackSourceType: "comment" },
61509
+ "schedule.fire": { type: "schedule", ackSourceType: "schedule_run" },
61510
+ external_trigger: { type: "external_trigger", ackSourceType: "external_trigger_run" },
61511
+ channel_message: { type: "channel_message", ackSourceType: "channel_message" },
61512
+ approval_decided: { type: "approval", ackSourceType: "approval" }
61513
+ };
61514
+ async function consumeWorkItem(host, item) {
61515
+ await host.contractReady;
61516
+ if (host.shuttingDown)
61517
+ return;
61518
+ if (item.event_type === "message") {
61519
+ if (!item.chat_id || !item.source_id)
61520
+ return;
61521
+ await consumeMessageWorkItem(host.laneFlowHost(), {
61522
+ id: item.id,
61523
+ source_id: item.source_id,
61524
+ chat_id: item.chat_id,
61525
+ actor_id: item.actor_id,
61526
+ thread_root_id: item.thread_root_id,
61527
+ delivery_reason: item.delivery_reason
61528
+ });
61529
+ return;
61530
+ }
61531
+ const channelLane = channelLaneTargetUri(item);
61532
+ if (channelLane) {
61533
+ await consumeChannelWorkItem(host.laneFlowHost(), { ...item, target_uri: channelLane });
61534
+ return;
61535
+ }
61536
+ if (!TYPED_EVENT_KINDS[item.event_type]) {
61537
+ host.opts.log?.info(`dispatch with unhandled event_type=${String(item.event_type)} (id=${item.id}) \u2014 no-op`);
61538
+ return;
61539
+ }
61540
+ if (host.isBufferedTypedWorkItem(item.id)) {
61541
+ host.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping re-claim`);
61542
+ return;
61543
+ }
61544
+ await host.consumeTypedDispatch({ dispatchEventId: item.id }, (lane) => host.runTypedFrame(item, lane), { legacyAck: () => host.ackDispatchEvent(item.id) });
61545
+ }
61546
+ async function runTypedFrame(host, item, lane) {
61547
+ if (host.shuttingDown)
61548
+ return false;
61549
+ const wake = host.laneLedger?.takeFrame(lane);
61550
+ if (!wake?.frame) {
61551
+ host.opts.log?.warn(`typed dispatch ${item.id} (${String(item.event_type)}) claimed without a frame \u2014 leaving it pending`);
61552
+ host.redeclareRuntimeContract();
61553
+ return false;
61554
+ }
61555
+ const kind = TYPED_EVENT_KINDS[item.event_type];
61556
+ const targetId = wake.input?.subject || item.task_id || item.chat_id || item.source_id || item.id;
61557
+ const event = {
61558
+ type: kind.type,
61559
+ targetId,
61560
+ targetType: wake.input?.step_target?.type,
61561
+ senderId: wake.input?.sender_id ?? item.actor_id ?? "system",
61562
+ messageId: item.source_id,
61563
+ deliveryReason: item.delivery_reason ?? void 0,
61564
+ ackSourceType: kind.ackSourceType,
61565
+ ackSourceId: item.source_id,
61566
+ dispatchEventId: item.id
61567
+ };
61568
+ applyWake(event, wake);
61569
+ host.opts.log?.info(`${String(item.event_type)} ${item.source_id} \u2192 ${targetId} (dispatch=${item.id})`);
61570
+ return host.handleInboundEvent(event);
61571
+ }
61572
+
61573
+ // ts/agent-core/dist/gateway/catch-up.js
61574
+ async function catchUpFromDispatch(host) {
61575
+ const OVERFLOW_THRESHOLD = 500;
61576
+ const EXPIRE_AGE_HOURS = 24;
61577
+ const CATCHUP_MAX = 10;
61578
+ let expireSummary = null;
61579
+ let overflowMode = false;
61580
+ try {
61581
+ const { count } = await host.opts.client.getDispatchPendingCount(host.opts.config.org_id);
61582
+ if (count > OVERFLOW_THRESHOLD) {
61583
+ overflowMode = true;
61584
+ const result = await host.opts.client.expireDispatch(host.opts.config.org_id, EXPIRE_AGE_HOURS);
61585
+ if (result.total > 0) {
61586
+ host.opts.log?.warn(`dispatch catch-up overflow: ${count} pending, expired ${result.total} events older than ${EXPIRE_AGE_HOURS}h`);
61587
+ expireSummary = host.buildOfflineSummary(result.groups);
61588
+ }
61589
+ }
61590
+ } catch (err) {
61591
+ host.opts.log?.warn(`dispatch catch-up overflow check failed: ${String(err)}`);
61592
+ }
61593
+ let cursor;
61594
+ let processed = 0;
61595
+ let skipped = 0;
61596
+ const skippedByType = /* @__PURE__ */ new Map();
61597
+ do {
61598
+ const page = await host.opts.client.getDispatch(host.opts.config.org_id, {
61599
+ limit: 50,
61600
+ cursor
61601
+ });
61602
+ for (const item of page.data ?? []) {
61603
+ if (host.shuttingDown)
61604
+ break;
61605
+ if (overflowMode && processed >= CATCHUP_MAX) {
61606
+ try {
61607
+ if (host.laneLedger && !host.ledgerDisabled && !host.typedByIdCompleteUnsupported) {
61608
+ const outcome = await host.resolveDispatchByID(item.id);
61609
+ if (outcome === "unsupported") {
61610
+ host.typedByIdCompleteUnsupported = true;
61611
+ await host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id);
61612
+ } else if (outcome === "failed") {
61613
+ throw new Error("by-id complete failed");
61614
+ }
61615
+ } else {
61616
+ await host.opts.client.ackDispatchByID(host.opts.config.org_id, item.id);
61617
+ }
61618
+ skipped++;
61619
+ const key = item.event_type;
61620
+ skippedByType.set(key, (skippedByType.get(key) ?? 0) + 1);
61621
+ } catch {
61622
+ host.opts.log?.warn(`catch-up skip ack failed for ${item.id}, leaving pending`);
61623
+ }
61624
+ continue;
61625
+ }
61626
+ processed++;
61627
+ try {
61628
+ await host.consumeWorkItem(item);
61629
+ } catch (err) {
61630
+ host.opts.log?.warn(`catch-up dispatch ${item.id} (${item.event_type}) failed: ${String(err)}`);
61631
+ }
61632
+ }
61633
+ cursor = !host.shuttingDown && page.has_more ? page.next_cursor : void 0;
61634
+ } while (cursor);
61635
+ if (expireSummary || skipped > 0) {
61636
+ const parts = [];
61637
+ if (expireSummary)
61638
+ parts.push(expireSummary);
61639
+ if (skipped > 0) {
61640
+ const recentLines = [...skippedByType.entries()].map(([type, count]) => `- ${count} recent ${type.replace(".", " ").replace("_", " ")} events`).join("\n");
61641
+ parts.push(expireSummary ? `Additionally, ${skipped} recent events exceeded the catch-up limit and were skipped:
61642
+ ${recentLines}` : `[Offline Summary] You were offline. ${skipped} pending events exceeded the catch-up limit and were skipped:
61643
+ ${recentLines}
61644
+
61645
+ Use your tools (read messages, check tasks) to review anything still relevant.`);
61646
+ }
61647
+ const fullSummary = parts.join("\n\n");
61648
+ host.pendingRestartNotification = host.pendingRestartNotification ? `${host.pendingRestartNotification}
61649
+
61650
+ ${fullSummary}` : fullSummary;
61651
+ }
61652
+ if (processed > 0 || skipped > 0) {
61653
+ host.opts.log?.info(`dispatch catch-up: processed ${processed}, skipped ${skipped}`);
61654
+ }
61655
+ }
61656
+ function buildOfflineSummary(host, groups) {
61657
+ const lines = [
61658
+ "[Offline Summary] You were offline and had a large backlog of pending events. The following old events were skipped:"
61659
+ ];
61660
+ for (const g of groups) {
61661
+ const age = host.formatAge(g.oldest);
61662
+ if (g.chat_id && g.event_type === "message") {
61663
+ const name = g.chat_name ?? g.chat_id;
61664
+ lines.push(`- ${g.count} messages in "${name}" (oldest: ${age})`);
61665
+ } else {
61666
+ const label = g.event_type.replace(".", " ").replace("_", " ");
61667
+ lines.push(`- ${g.count} ${label} events (oldest: ${age})`);
61668
+ }
61669
+ }
61670
+ lines.push("");
61671
+ lines.push("These events were too old to process individually. Use your tools (read messages, check tasks) to review anything still relevant.");
61672
+ return lines.join("\n");
61673
+ }
61674
+ function formatAge(_host, iso) {
61675
+ const ms = Date.now() - new Date(iso).getTime();
61676
+ const hours = Math.floor(ms / 36e5);
61677
+ if (hours < 24)
61678
+ return `${hours}h ago`;
61679
+ const days = Math.floor(hours / 24);
61680
+ return `${days}d ago`;
61681
+ }
61682
+
61683
+ // ts/agent-core/dist/gateway/connection.js
61684
+ import * as os from "node:os";
61685
+
61686
+ // ts/agent-core/dist/runtime-declaration.js
61687
+ async function declareAgentRuntimeReport(client, input) {
61688
+ const components = [];
61689
+ if (input.runtimeVersion) {
61690
+ components.push({ component: "bridge", version_raw: input.runtimeVersion, status: "ok" });
61691
+ }
61692
+ components.push({ component: "node", version_raw: process.versions.node, status: "ok" });
61693
+ await client.putAgentRuntimeReport(input.orgId, {
61694
+ ws_session_id: input.wsSessionId,
61695
+ components,
61696
+ features: ["runtime_contract"]
61697
+ });
61698
+ }
61699
+
61700
+ // ts/agent-core/dist/gateway/connection.js
61701
+ async function handleHello(host, data) {
61702
+ const { log: log2 } = host.opts;
61703
+ host.sessionId = data.session_id ?? "";
61704
+ if (host.forkStates.size > 0) {
61705
+ const targetIds = [...host.forkStates.keys()];
61706
+ if (host.opts.instanceId) {
61707
+ log2?.info(`${targetIds.length} active fork(s) continue across the reconnect`);
61708
+ } else {
61709
+ log2?.info(`aborting ${targetIds.length} active fork(s) on reconnect`);
61710
+ for (const targetId of targetIds) {
61711
+ host.abortFork(targetId, "ws reconnect");
61712
+ }
61713
+ }
61714
+ }
61715
+ if (host.laneLedger && !host.opts.instanceId && host.inFlightDispatches === 0 && host.laneLedger.activeCount > 0) {
61716
+ log2?.info(`releasing ${host.laneLedger.activeCount} stale lane(s) on reconnect`);
61717
+ await host.laneLedger.releaseAll();
61718
+ }
61719
+ if (host.laneLedger && host.ledgerDisabled) {
61720
+ log2?.info("re-probing dispatch ledger after reconnect (was disabled)");
61721
+ host.ledgerDisabled = false;
61722
+ }
61723
+ const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
61724
+ let openFence = () => {
61725
+ };
61726
+ host.contractReady = new Promise((resolve3) => {
61727
+ openFence = resolve3;
61728
+ });
61729
+ try {
61730
+ log2?.info("WebSocket connected");
61731
+ try {
61732
+ await host.declareRuntimeContract();
61733
+ } finally {
61734
+ openFence();
61735
+ }
61736
+ await host.opts.onSessionReady?.({
61737
+ activeSessionId: host.activeSessionId,
61738
+ ws: host.opts.ws,
61739
+ runtimeKey: host.opts.runtimeKey
61740
+ });
61741
+ if (host.heartbeatTimer)
61742
+ clearInterval(host.heartbeatTimer);
61743
+ host.lastHeartbeatAt = Date.now();
61744
+ host.heartbeatTimer = setInterval(() => {
61745
+ const now = Date.now();
61746
+ const expectedMs = intervalSec * 1e3;
61747
+ const drift = now - host.lastHeartbeatAt - expectedMs;
61748
+ if (drift > 15e3) {
61749
+ log2?.warn(`heartbeat drift ${drift}ms \u2014 event loop may be blocked`);
61750
+ }
61751
+ host.lastHeartbeatAt = now;
61752
+ if (host.opts.ws.state !== "connected")
61753
+ return;
61754
+ host.opts.ws.sendAgentHeartbeat(host.sessionId, {
61755
+ hostname: os.hostname(),
61756
+ cores: os.cpus().length,
61757
+ mem_total: os.totalmem(),
61758
+ mem_free: os.freemem(),
61759
+ uptime: os.uptime()
61760
+ });
61761
+ }, intervalSec * 1e3);
61762
+ await host.laneLedger?.retryConfirmations();
61763
+ host.catchUpFromDispatch().catch((err) => {
61764
+ log2?.warn(`dispatch catch-up failed: ${String(err)}`);
61765
+ });
61766
+ } catch (err) {
61767
+ log2?.error(`hello handling failed: ${String(err)}`);
61768
+ }
61769
+ }
61770
+ function redeclareRuntimeContract(host) {
61771
+ if (host.redeclareInFlight || !host.sessionId)
61772
+ return;
61773
+ host.opts.log?.info("re-declaring the runtime contract after a frameless claim");
61774
+ host.redeclareInFlight = host.declareRuntimeContract().finally(() => {
61775
+ host.redeclareInFlight = null;
61776
+ });
61777
+ }
61778
+ async function declareRuntimeContract(host) {
61779
+ const session = host.sessionId;
61780
+ if (!session)
61781
+ return;
61782
+ for (let attempt = 0; ; attempt++) {
61783
+ try {
61784
+ await declareAgentRuntimeReport(host.opts.client, {
61785
+ orgId: host.opts.config.org_id,
61786
+ wsSessionId: session,
61787
+ runtimeVersion: host.opts.runtimeVersion
61788
+ });
61789
+ host.opts.log?.info("runtime contract declared (server-rendered frames)");
61790
+ return;
61791
+ } catch (err) {
61792
+ if (err instanceof ApiError && err.status === 404) {
61793
+ host.opts.log?.warn("server predates the runtime contract \u2014 it renders no wake frames; WorkItems stay pending");
61794
+ return;
61795
+ }
61796
+ if (err instanceof ApiError && err.status === 409) {
61797
+ host.opts.log?.info("runtime contract already declared by a newer connection");
61798
+ return;
61799
+ }
61800
+ const delayMs = Math.min(3e4, 2e3 * 2 ** Math.min(attempt, 4));
61801
+ host.opts.log?.warn(`runtime contract declaration failed (retry in ${delayMs / 1e3}s): ${String(err)}`);
61802
+ await new Promise((resolve3) => {
61803
+ const timer = setTimeout(resolve3, delayMs);
61804
+ timer.unref?.();
61805
+ });
61806
+ if (host.shuttingDown || host.sessionId !== session)
61807
+ return;
61808
+ }
61809
+ }
61810
+ }
61811
+ async function shutdown(host, opts = { skipDrain: false }) {
61812
+ host.shuttingDown = true;
61813
+ host.idleCompact.abort?.();
61814
+ if (opts.skipDrain && !host.isDrained()) {
61815
+ host.opts.log?.warn(`skipping drain (credential rejected): ${host.inFlightDispatches} dispatch(es), ${host.inFlightRuntimeTurns} runtime-initiated turn(s) abandoned to server redelivery`);
61816
+ } else if (!host.isDrained()) {
61817
+ host.opts.log?.info(`draining ${host.inFlightDispatches} in-flight dispatch(es), ${host.inFlightRuntimeTurns} runtime-initiated turn(s), runtime busy=${host.adapterBusy()}, deadline ${host.SHUTDOWN_DEADLINE_MS}ms`);
61818
+ await host.drainGate.wait(host.SHUTDOWN_DEADLINE_MS);
61819
+ if (!host.isDrained()) {
61820
+ host.opts.log?.warn(`drain deadline hit; ${host.inFlightDispatches} dispatch(es), ${host.inFlightRuntimeTurns} runtime-initiated turn(s), runtime busy=${host.adapterBusy()} \u2014 they will be killed by process exit`);
61821
+ } else {
61822
+ host.opts.log?.info(`drain complete`);
61823
+ }
61824
+ }
61825
+ if (host.heartbeatTimer)
61826
+ clearInterval(host.heartbeatTimer);
61827
+ if (host.laneLedger) {
61828
+ host.opts.log?.info(`releasing ${host.laneLedger.activeCount} lane(s) on shutdown`);
61829
+ await host.laneLedger.releaseAll();
61830
+ }
61831
+ await host.opts.onBeforeDisconnect?.();
61832
+ if (host.inFlightRuntimeTurns > 0) {
61833
+ await host.drainGate.wait(5e3, () => host.inFlightRuntimeTurns === 0);
61834
+ }
61835
+ if (host.stepPersister.pendingTotal() > 0) {
61836
+ const remaining = await host.stepPersister.flush(1e4);
61837
+ if (remaining > 0) {
61838
+ host.opts.log?.warn(`${remaining} parked step write(s) could not be flushed at shutdown; they are permanently lost`);
61839
+ }
61840
+ }
61841
+ host.stepPersister.dispose();
61842
+ const lifecycleRemaining = await host.sessionLifecycle.flush(5e3);
61843
+ if (lifecycleRemaining > 0) {
61844
+ host.opts.log?.warn(`${lifecycleRemaining} session lifecycle write(s) unreconciled at shutdown`);
61845
+ }
61846
+ host.sessionLifecycle.dispose();
61847
+ await host.laneLedger?.retryConfirmations();
61848
+ host.laneLedger?.dispose();
61849
+ host.opts.ws.disconnect();
61850
+ host.unsubscribeRuntimeActivity?.();
61851
+ host.opts.log?.info(`disconnected`);
61852
+ }
61853
+
61854
+ // ts/agent-core/dist/gateway/base.js
61855
+ var AUTH_INVALID_EXIT_CODE = 86;
61856
+ function classifyStartupFailure(err) {
61857
+ const authRejection = authRejectionFrom(err);
61858
+ return { exitCode: authRejection ? AUTH_INVALID_EXIT_CODE : 1, authRejection };
61859
+ }
61860
+ function parseShutdownDeadlineMs(raw) {
61861
+ if (!raw)
61862
+ return void 0;
61863
+ const n = Number(raw);
61864
+ if (!Number.isFinite(n) || n <= 0)
61865
+ return void 0;
61866
+ return Math.floor(n);
61867
+ }
61868
+ function parseForkDeadlineMs(raw) {
61869
+ if (!raw)
61870
+ return void 0;
61871
+ const n = Number(raw);
61872
+ if (!Number.isFinite(n) || n <= 0 || n > 2147483647)
61873
+ return void 0;
61874
+ return Math.floor(n);
61875
+ }
61876
+ function parseDispatchDeadlineMs(raw) {
61877
+ if (!raw)
61878
+ return void 0;
61879
+ const n = Number(raw);
61880
+ if (!Number.isFinite(n) || n < 0 || n > 2147483647)
61881
+ return void 0;
61882
+ return Math.floor(n);
61883
+ }
61884
+ var ParallAgentGateway = class {
61885
+ opts;
61886
+ // In-process in-flight guard for message WorkItems (see LaneFlowHost).
61887
+ dispatchedMessages = /* @__PURE__ */ new Set();
61888
+ /**
61889
+ * Consumption fence: no WorkItem is claimed before this connection's
61890
+ * runtime contract is declared (handleHello). A claim made before the
61891
+ * declaration would get no frame — and a frameless claim has nothing to
61892
+ * run. Open until the first hello starts a declaration.
61893
+ */
61894
+ contractReady = Promise.resolve();
61895
+ /** One re-declaration at a time; a burst of frameless claims collapses into it. */
61896
+ redeclareInFlight = null;
61897
+ injectedMainBufferEvents = /* @__PURE__ */ new WeakSet();
61898
+ // Per-WorkItem failure backoff for typed dispatch consumption — see
61899
+ // LaneFlowHost.typedRedriveBackoff in gateway/lane-flow.ts.
61900
+ typedRedriveBackoff = /* @__PURE__ */ new Map();
61901
+ forkStates = /* @__PURE__ */ new Map();
61902
+ forkContinuationRetries = /* @__PURE__ */ new Map();
61903
+ dispatchState = {
61904
+ mainDispatching: false,
61905
+ activeForks: /* @__PURE__ */ new Map(),
61906
+ pendingForkResults: [],
61907
+ mainBuffer: []
61908
+ };
61909
+ sessionId = "";
61910
+ activeSessionId;
61911
+ sessionBindings = /* @__PURE__ */ new Map();
61912
+ heartbeatTimer = null;
61913
+ lastHeartbeatAt = Date.now();
61914
+ draining = false;
61915
+ // Idle auto-compact hold on the main lane (gateway/idle-compact.ts).
61916
+ idleCompact = createIdleCompactState();
61917
+ /**
61918
+ * Typed WorkItem ids whose drain group left the buffer but has not settled
61919
+ * yet. isBufferedTypedWorkItem treats them as still buffered — a re-drive
61920
+ * claim taken inside this window would turn the drain's fence-less close
61921
+ * stale (its dedupe cleared, its release re-driving handled work) (#1149).
61922
+ */
61923
+ drainingTypedIds = /* @__PURE__ */ new Set();
61924
+ // Graceful shutdown state. When SIGTERM / abort fires, `shuttingDown` flips
61925
+ // to true so no new dispatches start, and `inFlightDispatches` counts runs
61926
+ // still in progress. `shutdown()` awaits drain up to SHUTDOWN_DEADLINE_MS
61927
+ // before tearing down the WS; see handleTermination caller.
61928
+ shuttingDown = false;
61929
+ inFlightDispatches = 0;
60800
61930
  drainGate = new DrainGate(() => this.isDrained());
60801
61931
  // Turns the runtime started on its own (RuntimeInitiatedTurn) currently
60802
61932
  // being persisted — drained by shutdown() alongside dispatches.
@@ -61065,7 +62195,7 @@ var ParallAgentGateway = class {
61065
62195
  * the process lifetime.
61066
62196
  */
61067
62197
  typedByIdCompleteUnsupported = false;
61068
- // Typed-face ledger helpers live in gateway-lane-flow.ts; thin delegates
62198
+ // Typed-face ledger helpers live in gateway/lane-flow.ts; thin delegates
61069
62199
  // keep the site code and tests on the class surface.
61070
62200
  typedLedgerEventIds(events) {
61071
62201
  return typedLedgerEventIds(this.laneFlowHost(), events);
@@ -61095,7 +62225,7 @@ var ParallAgentGateway = class {
61095
62225
  }
61096
62226
  return isTypedEvent(event) ? `typed:${event.targetId}` : event.targetId;
61097
62227
  }
61098
- // Lane-flow protocols live in gateway-lane-flow.ts; these thin delegates
62228
+ // Lane-flow protocols live in gateway/lane-flow.ts; these thin delegates
61099
62229
  // keep call sites and tests on the class surface.
61100
62230
  laneFlowHost() {
61101
62231
  return this;
@@ -61233,495 +62363,29 @@ var ParallAgentGateway = class {
61233
62363
  }
61234
62364
  }
61235
62365
  async createInputStepsForEarlierEvents(sessionId, events) {
61236
- for (const event of events) {
61237
- await this.createInputStep(sessionId, event);
61238
- }
61239
- }
61240
- bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2) {
61241
- return bindRuntimeSession(this, sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2);
61242
- }
61243
- // Returns true if the dispatch actually ran; false if skipped because we
61244
- // are shutting down. Callers MUST treat `false` as "not dispatched" and
61245
- // skip the server-side ack so the event stays in the dispatch queue for
61246
- // catch-up on the replacement pod — otherwise we silently drop work.
61247
- async runDispatch(event, sessionKey, bodyForAgent, earlierEvents = [], captureText, inputLifecycle) {
61248
- if (this.shuttingDown) {
61249
- this.opts.log?.info(`skipping dispatch for ${event.messageId} (shutting down) \u2014 leaving unacked for catch-up on replacement pod`);
61250
- return false;
61251
- }
61252
- if (this.pendingRestartNotification) {
61253
- bodyForAgent = this.pendingRestartNotification + "\n\n---\n\n" + bodyForAgent;
61254
- this.pendingRestartNotification = null;
61255
- }
61256
- resetDispatchMetrics(sessionKey);
61257
- this.turnOutcomes.delete(sessionKey);
61258
- return runInDispatchTrace({
61259
- event,
61260
- runtimeType: this.opts.runtimeType,
61261
- sessionKey,
61262
- dispatchEventId: event.dispatchEventId
61263
- }, async (dispatchSpan) => {
61264
- setSessionChatId(sessionKey, event.targetId);
61265
- setSessionMessageId(sessionKey, event.messageId);
61266
- setDispatchMessageId(sessionKey, event.messageId);
61267
- setDispatchNoReply(sessionKey, event.noReply ?? false);
61268
- const dispatchContext = this.buildDispatchContext(event, sessionKey);
61269
- const contextFilePath = dispatchContext.contextFilePath;
61270
- const stepIdFilePath = dispatchContext.stepIdFilePath;
61271
- const stepTarget = resolveStepTarget(event);
61272
- const activeLane = this.ledgerDisabled ? void 0 : this.laneLedger?.getForEvent(event);
61273
- const laneContextFilePath2 = activeLane ? this.laneLedger?.laneContextPath(activeLane) : void 0;
61274
- const contextBody = {
61275
- session_id: dispatchContext.sessionId ?? null,
61276
- chat_id: dispatchContext.chatId ?? null,
61277
- trigger_message_id: dispatchContext.triggerMessageId ?? null,
61278
- no_reply: dispatchContext.noReply,
61279
- step_id: null,
61280
- dispatch_event_id: activeLane?.typedDispatchEventId ?? activeLane?.folded.get(event.messageId) ?? null,
61281
- lane: activeLane?.lane ?? null,
61282
- settlement_mode: activeLane?.settlementMode ?? "legacy",
61283
- target_uri: activeLane?.targetUri ?? null,
61284
- thread_root_id: activeLane?.threadRootId ?? null,
61285
- // Typed binding hint for the CLI: which task this dispatch is about
61286
- // (parall task update attaches the typed effect only on a match).
61287
- task_id: event.type === "task" ? event.targetId : null
61288
- };
61289
- if (contextFilePath) {
61290
- this.writeContextFile(contextFilePath, contextBody);
61291
- }
61292
- if (laneContextFilePath2) {
61293
- this.writeContextFile(laneContextFilePath2, contextBody);
61294
- }
61295
- patchDispatchContext({
61296
- dispatchEventId: contextBody.dispatch_event_id,
61297
- lane: contextBody.lane,
61298
- targetUri: contextBody.target_uri,
61299
- threadRootId: contextBody.thread_root_id
61300
- });
61301
- this.inFlightDispatches++;
61302
- const abortAfterMs = this.DISPATCH_DEADLINE_MS;
61303
- const dispatchDeadline = this.dispatchInactivityDeadlines.start(sessionKey, abortAfterMs > 0 ? abortAfterMs : this.INACTIVITY_WARN_MS, () => {
61304
- if (abortAfterMs > 0) {
61305
- this.opts.log?.warn(`dispatch inactivity deadline exceeded (${abortAfterMs}ms) for ${event.messageId} on ${sessionKey}; aborting`);
61306
- try {
61307
- this.opts.dispatchAdapter.abortDispatch?.(sessionKey);
61308
- } catch (err) {
61309
- this.opts.log?.warn(`abortDispatch threw for ${sessionKey}: ${String(err)}`);
61310
- }
61311
- return;
61312
- }
61313
- this.opts.log?.warn(`no runtime output for ${Math.round(this.INACTIVITY_WARN_MS / 6e4)} min on ${sessionKey} (${event.messageId}); the turn stays open \u2014 only the runtime finishing or a process restart ends it`);
61314
- dispatchDeadline.rearm();
61315
- });
61316
- let binding = this.sessionBindings.get(sessionKey);
61317
- let inputStepsCreated = false;
61318
- let turnHandle;
61319
- let dispatchError;
61320
- let turnOutcomeEvent;
61321
- let sawErrorEvent = false;
61322
- const pendingSendCallIds = /* @__PURE__ */ new Set();
61323
- const ensureTurnBegun = async () => {
61324
- if (turnHandle || !binding)
61325
- return;
61326
- turnHandle = await this.sessionLifecycle.beginTurn(binding.agentSessionId, event.messageId);
61327
- };
61328
- try {
61329
- await runInPhaseSpan("turn", async () => {
61330
- for await (const runtimeEvent of this.opts.dispatchAdapter.dispatch({
61331
- event,
61332
- earlierEvents,
61333
- bodyForAgent,
61334
- sessionKey,
61335
- context: dispatchContext,
61336
- inputLifecycle,
61337
- noteActivity: dispatchDeadline.touch
61338
- })) {
61339
- if (runtimeEvent.type !== "observation")
61340
- dispatchDeadline.touch();
61341
- if (runtimeEvent.type === "runtime_session") {
61342
- const priorAgentSessionId = binding?.agentSessionId;
61343
- binding = await runInPhaseSpan("session", () => this.bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2));
61344
- if (activeLane) {
61345
- bindLaneSession(activeLane, binding.agentSessionId);
61346
- await this.laneLedger?.syncInputAttribution(activeLane);
61347
- }
61348
- if (event.targetType === "channel_conversation" && binding.agentSessionId !== priorAgentSessionId) {
61349
- try {
61350
- await this.opts.client.setChannelConversationSession(this.opts.config.org_id, event.targetId, binding.agentSessionId);
61351
- } catch (err) {
61352
- this.opts.log?.warn(`failed to record session mapping for channel conversation ${event.targetId}: ${String(err)}`);
61353
- }
61354
- }
61355
- if (!inputStepsCreated) {
61356
- await ensureTurnBegun();
61357
- if (earlierEvents.length > 0) {
61358
- await this.createInputStepsForEarlierEvents(binding.agentSessionId, earlierEvents);
61359
- }
61360
- await this.createInputStep(binding.agentSessionId, event);
61361
- inputStepsCreated = true;
61362
- }
61363
- continue;
61364
- }
61365
- if (runtimeEvent.type === "observation") {
61366
- if (binding?.runtimeSessionId === runtimeEvent.runtimeSessionId) {
61367
- await this.createRuntimeStep(binding.agentSessionId, stepTarget, runtimeEvent);
61368
- } else {
61369
- this.opts.log?.warn("runtime observation has no matching active session binding");
61370
- }
61371
- continue;
61372
- }
61373
- if (runtimeEvent.type === "turn_outcome") {
61374
- const outcomeEvent = redactTurnOutcome(runtimeEvent, [this.opts.config.api_key]);
61375
- turnOutcomeEvent = outcomeEvent;
61376
- if (outcomeEvent.outcome === "ok") {
61377
- this.turnOutcomes.delete(sessionKey);
61378
- continue;
61379
- }
61380
- this.recordTurnClassification(sessionKey, outcomeEvent.outcome === "usage_limit" ? {
61381
- kind: "deferred",
61382
- outcomeClass: outcomeEvent.outcome,
61383
- ...outcomeEvent.retryAt ? { retryAt: outcomeEvent.retryAt } : {}
61384
- } : {
61385
- kind: "error",
61386
- outcomeClass: outcomeEvent.outcome,
61387
- ...outcomeEvent.detail ? { detail: outcomeEvent.detail } : {}
61388
- });
61389
- const failure = describeTurnOutcomeFailure(outcomeEvent);
61390
- this.opts.log?.warn(`turn outcome: ${failure.warn} (dispatch=${contextBody.dispatch_event_id ?? "-"} lane=${contextBody.lane ?? "-"})`);
61391
- if (binding) {
61392
- await ensureTurnBegun();
61393
- if (!inputStepsCreated) {
61394
- if (earlierEvents.length > 0) {
61395
- await this.createInputStepsForEarlierEvents(binding.agentSessionId, earlierEvents);
61396
- }
61397
- await this.createInputStep(binding.agentSessionId, event);
61398
- inputStepsCreated = true;
61399
- }
61400
- await this.createRuntimeStep(binding.agentSessionId, stepTarget, {
61401
- type: "error",
61402
- message: failure.stepMessage
61403
- }, stepIdFilePath, contextFilePath, laneContextFilePath2);
61404
- }
61405
- continue;
61406
- }
61407
- if (!binding) {
61408
- const detail = runtimeEvent.type === "error" ? `: ${runtimeEvent.message}` : "";
61409
- throw new Error(`runtime emitted ${runtimeEvent.type} before runtime_session${detail}`);
61410
- }
61411
- await ensureTurnBegun();
61412
- if (!inputStepsCreated) {
61413
- if (earlierEvents.length > 0) {
61414
- await this.createInputStepsForEarlierEvents(binding.agentSessionId, earlierEvents);
61415
- }
61416
- await this.createInputStep(binding.agentSessionId, event);
61417
- inputStepsCreated = true;
61418
- }
61419
- if (activeLane && !this.ledgerDisabled) {
61420
- this.laneLedger?.maybeRenew(activeLane);
61421
- }
61422
- if (captureText && runtimeEvent.type === "text" && runtimeEvent.text) {
61423
- captureText.push(runtimeEvent.text);
61424
- }
61425
- if (runtimeEvent.type === "text" && runtimeEvent.text.length > 0) {
61426
- recordDeliverText(sessionKey, runtimeEvent.text.length);
61427
- } else if (runtimeEvent.type === "tool_call") {
61428
- recordToolCall(sessionKey);
61429
- const cmd = extractShellCommand(runtimeEvent.input);
61430
- if (isParallSendCommand(cmd)) {
61431
- pendingSendCallIds.add(runtimeEvent.callId);
61432
- } else if (isParallNoReplyCommand(cmd)) {
61433
- recordNoReply(sessionKey);
61434
- }
61435
- } else if (runtimeEvent.type === "tool_result" && pendingSendCallIds.delete(runtimeEvent.callId)) {
61436
- recordMessageSend(sessionKey, !runtimeEvent.error);
61437
- }
61438
- if (runtimeEvent.type === "error") {
61439
- sawErrorEvent = true;
61440
- this.recordTurnErrorSignal(sessionKey, runtimeEvent.message);
61441
- }
61442
- await this.createRuntimeStep(binding.agentSessionId, stepTarget, runtimeEvent.type === "error" ? { ...runtimeEvent, message: this.redactRuntimeText(runtimeEvent.message) } : runtimeEvent, stepIdFilePath, contextFilePath, laneContextFilePath2);
61443
- }
61444
- if (!binding) {
61445
- binding = this.sessionBindings.get(sessionKey);
61446
- }
61447
- if (!binding) {
61448
- throw new Error("runtime completed without runtime_session");
61449
- }
61450
- if (!inputStepsCreated) {
61451
- await ensureTurnBegun();
61452
- if (earlierEvents.length > 0) {
61453
- await this.createInputStepsForEarlierEvents(binding.agentSessionId, earlierEvents);
61454
- }
61455
- await this.createInputStep(binding.agentSessionId, event);
61456
- }
61457
- });
61458
- } catch (err) {
61459
- dispatchError = err;
61460
- let staleDetected = this.isSessionNotLiveError(err);
61461
- if (!staleDetected && binding) {
61462
- try {
61463
- await ensureTurnBegun();
61464
- await this.createRuntimeStep(binding.agentSessionId, stepTarget, {
61465
- type: "error",
61466
- message: `Dispatch failed: ${this.redactRuntimeText(String(err))}`
61467
- }, stepIdFilePath, contextFilePath, laneContextFilePath2);
61468
- } catch (stepErr) {
61469
- if (this.isSessionNotLiveError(stepErr))
61470
- staleDetected = true;
61471
- }
61472
- }
61473
- if (staleDetected && binding) {
61474
- this.opts.log?.warn?.(`session ${binding.agentSessionId} is stale (mid-dispatch), triggering recovery for ${sessionKey}`);
61475
- this.sessionBindings.delete(sessionKey);
61476
- this.stepPersister.dropSession(binding.agentSessionId);
61477
- this.sessionLifecycle.dropSession(binding.agentSessionId);
61478
- if (sessionKey === this.opts.runtimeKey) {
61479
- this.activeSessionId = void 0;
61480
- }
61481
- try {
61482
- await this.opts.onSessionStale?.(sessionKey);
61483
- } catch (e) {
61484
- this.opts.log?.warn?.(`onSessionStale failed: ${e}`);
61485
- }
61486
- this.opts.log?.info?.(`stale session self-heal complete for ${sessionKey} \u2014 next dispatch will create a fresh session`);
61487
- binding = void 0;
61488
- }
61489
- throw err;
61490
- } finally {
61491
- dispatchDeadline.dispose();
61492
- const metricsSnapshot = getDispatchMetrics(sessionKey);
61493
- const durationMs = metricsSnapshot ? Date.now() - metricsSnapshot.started_at : 0;
61494
- const effectiveOutcome = turnOutcomeEvent?.outcome ?? (dispatchError || sawErrorEvent ? "runtime_crash" : "ok");
61495
- annotateDispatchSpan(dispatchSpan, metricsSnapshot, dispatchError, turnOutcomeEvent);
61496
- recordDispatchMetric(event, this.opts.runtimeType, durationMs, effectiveOutcome);
61497
- recordTurnUsage(turnOutcomeEvent?.usage, this.opts.runtimeType);
61498
- if (metricsSnapshot && !dispatchError && event.type === "message" && event.targetId?.startsWith("cht_") && !event.noReply && metricsSnapshot.deliver_text_chunks > 0 && metricsSnapshot.message_send_successes === 0 && !metricsSnapshot.no_reply_called) {
61499
- recordMissingReply(this.opts.runtimeType, effectiveOutcome);
61500
- }
61501
- clearDispatchMetrics(sessionKey);
61502
- if (turnHandle) {
61503
- this.sessionLifecycle.finishTurn(turnHandle);
61504
- }
61505
- clearSessionMessageId(sessionKey);
61506
- clearDispatchMessageId(sessionKey);
61507
- clearDispatchNoReply(sessionKey);
61508
- if (contextFilePath) {
61509
- this.updateContextFileStepId(contextFilePath, null);
61510
- } else if (stepIdFilePath) {
61511
- this.clearStepIdFile(stepIdFilePath);
61512
- }
61513
- if (laneContextFilePath2) {
61514
- this.updateContextFileStepId(laneContextFilePath2, null);
61515
- }
61516
- this.inFlightDispatches--;
61517
- this.notifyDrainWaiters();
61518
- }
61519
- return true;
61520
- });
62366
+ for (const event of events) {
62367
+ await this.createInputStep(sessionId, event);
62368
+ }
62369
+ }
62370
+ bindRuntimeSession(sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2) {
62371
+ return bindRuntimeSession(this, sessionKey, runtimeEvent, contextFilePath, laneContextFilePath2);
62372
+ }
62373
+ async runDispatch(event, sessionKey, bodyForAgent, earlierEvents = [], captureText, inputLifecycle) {
62374
+ return runDispatch(this, event, sessionKey, bodyForAgent, earlierEvents, captureText, inputLifecycle);
61521
62375
  }
61522
62376
  handleRuntimeActivity(event) {
61523
62377
  handleRuntimeActivity(this, event);
61524
62378
  }
61525
62379
  abortFork(targetId, reason) {
61526
- const forkState = this.forkStates.get(targetId);
61527
- if (!forkState)
61528
- return;
61529
- this.opts.log?.warn(`aborting fork for ${targetId}: ${reason}`);
61530
- forkState.deadlineExceeded = true;
61531
- if (forkState.deadlineTimer) {
61532
- clearTimeout(forkState.deadlineTimer);
61533
- forkState.deadlineTimer = null;
61534
- }
61535
- this.dispatchState.activeForks.delete(targetId);
61536
- this.forkStates.delete(targetId);
61537
- retainForkContinuationRetries(this.forkContinuationRetries, forkState.queue.map((item) => item.event), forkState.continuationPrefix);
61538
- for (const item of forkState.queue.splice(0)) {
61539
- item.resolve(false);
61540
- }
61541
- if (this.opts.dispatchAdapter.cleanupFork) {
61542
- const forkBinding = this.sessionBindings.get(forkState.fork.sessionKey);
61543
- const cleanupOpts = {
61544
- fork: forkState.fork,
61545
- context: {
61546
- accountId: this.opts.accountId,
61547
- apiUrl: this.opts.config.parall_url,
61548
- apiKey: this.opts.config.api_key,
61549
- orgId: this.opts.config.org_id,
61550
- agentUserId: this.opts.agentUserId,
61551
- runtimeType: this.opts.runtimeType,
61552
- runtimeKey: this.opts.runtimeKey,
61553
- sessionId: forkBinding?.agentSessionId,
61554
- noReply: false,
61555
- client: this.opts.client,
61556
- log: this.opts.log
61557
- }
61558
- };
61559
- void Promise.resolve().then(() => this.opts.dispatchAdapter.cleanupFork?.(cleanupOpts)).catch((err) => {
61560
- this.opts.log?.warn(`abortFork cleanupFork error for ${targetId}: ${String(err)}`);
61561
- });
61562
- }
62380
+ return abortFork(this, targetId, reason);
61563
62381
  }
61564
- // The drain loops are kicked from inside a turn's scope (a typed turn's
61565
- // finally, a fork spawn) and outlive it; run them outside any dispatch
61566
- // scope so each item they dispatch is its own trace and their logs never
61567
- // carry a finished dispatch's trace id.
61568
62382
  runForkDrainLoop(fork) {
61569
- return runOutsideDispatchScope(() => this.forkDrainLoop(fork));
62383
+ return runForkDrainLoop(this, fork);
61570
62384
  }
61571
62385
  async forkDrainLoop(fork) {
61572
- let lastCapturedText = [];
61573
- try {
61574
- while (fork.queue.length > 0) {
61575
- if (this.shuttingDown || fork.deadlineExceeded) {
61576
- for (const item of fork.queue.splice(0))
61577
- item.resolve(false);
61578
- break;
61579
- }
61580
- let items;
61581
- const head = fork.queue[0];
61582
- if (head && this.usesLaneLedger(head.event)) {
61583
- const headKey = this.dispatchGroupKey(head.event);
61584
- const splitAt = fork.queue.findIndex((it) => this.dispatchGroupKey(it.event) !== headKey);
61585
- items = splitAt === -1 ? fork.queue.splice(0) : fork.queue.splice(0, splitAt);
61586
- } else {
61587
- items = fork.queue.splice(0);
61588
- }
61589
- const events = items.map((item) => item.event);
61590
- const last = events[events.length - 1];
61591
- const earlier = events.slice(0, -1);
61592
- retainForkContinuationRetries(this.forkContinuationRetries, events, fork.continuationPrefix);
61593
- try {
61594
- const batchText = [];
61595
- const bodyPrefix = (fork.continuationPrefix ?? "") + buildForkScopePrefix(last);
61596
- const body = bodyPrefix + eventBody(last);
61597
- let dispatched;
61598
- if (this.usesLaneLedger(last)) {
61599
- const outcome = await this.dispatchLaneGroup({
61600
- events,
61601
- sessionKey: fork.fork.sessionKey,
61602
- bodyPrefix,
61603
- earlier,
61604
- captureText: batchText,
61605
- // Per-LANE residue check (parity with the main-buffer path):
61606
- // the fork queue can hold several lanes (channel + thread of
61607
- // the same chat). A whole-queue check would defer THIS lane's
61608
- // complete behind another lane's items and never revisit it —
61609
- // its members would sit received until lease expiry.
61610
- hasMoreLocal: () => fork.queue.some((it) => this.dispatchGroupKey(it.event) === this.dispatchGroupKey(last))
61611
- });
61612
- if (outcome === "foreign") {
61613
- for (const item of items)
61614
- item.resolve(false);
61615
- break;
61616
- }
61617
- if (outcome === "failed" || outcome === "deferred") {
61618
- for (const item of items)
61619
- item.resolve(false);
61620
- continue;
61621
- }
61622
- dispatched = outcome === "dispatched";
61623
- } else {
61624
- dispatched = await this.runDispatch(last, fork.fork.sessionKey, body, earlier, batchText);
61625
- if (dispatched && this.typedLedgerEventIds(events) && this.consumeTurnError(fork.fork.sessionKey)) {
61626
- this.opts.log?.info(`typed fork turn for ${last.messageId} surfaced a runtime error \u2014 releasing for retry`);
61627
- for (const item of items)
61628
- item.resolve(false);
61629
- continue;
61630
- }
61631
- }
61632
- if (!dispatched) {
61633
- for (const item of items) {
61634
- item.resolve(false);
61635
- }
61636
- break;
61637
- }
61638
- if (batchText.length > 0)
61639
- lastCapturedText = batchText;
61640
- clearForkContinuationRetries(this.forkContinuationRetries, events);
61641
- fork.continuationPrefix = void 0;
61642
- fork.processedEvents.push(...events);
61643
- for (const item of items) {
61644
- item.resolve(true);
61645
- }
61646
- } catch (err) {
61647
- this.opts.log?.error(`fork dispatch failed for ${last.messageId}: ${String(err)}`);
61648
- for (const item of items) {
61649
- item.resolve(false);
61650
- }
61651
- break;
61652
- }
61653
- }
61654
- for (const remaining of fork.queue.splice(0)) {
61655
- remaining.resolve(false);
61656
- }
61657
- } finally {
61658
- this.turnOutcomes.delete(fork.fork.sessionKey);
61659
- if (fork.deadlineTimer) {
61660
- clearTimeout(fork.deadlineTimer);
61661
- fork.deadlineTimer = null;
61662
- }
61663
- if (fork.processedEvents.length > 0) {
61664
- const first = fork.processedEvents[0];
61665
- const agentSummary = lastCapturedText.join("").trim() || void 0;
61666
- let historyPath;
61667
- try {
61668
- historyPath = this.opts.dispatchAdapter.getSessionHistoryPath?.(fork.fork.sessionKey);
61669
- } catch (err) {
61670
- this.opts.log?.warn?.(`failed to resolve fork history path: ${String(err)}`);
61671
- }
61672
- this.dispatchState.pendingForkResults.push({
61673
- forkSessionKey: fork.fork.sessionKey,
61674
- sourceEvent: {
61675
- type: first.type,
61676
- targetId: fork.targetId,
61677
- summary: fork.processedEvents.length === 1 ? `${first.type} in ${fork.targetId}` : `${fork.processedEvents.length} events in ${fork.targetId}`
61678
- },
61679
- eventBodies: fork.processedEvents.map((e) => forkResultBody(e)),
61680
- actions: [],
61681
- agentSummary,
61682
- historyPath
61683
- });
61684
- }
61685
- if (this.forkStates.get(fork.targetId) === fork) {
61686
- this.forkStates.delete(fork.targetId);
61687
- }
61688
- if (this.dispatchState.activeForks.get(fork.targetId) === fork.fork.sessionKey) {
61689
- this.dispatchState.activeForks.delete(fork.targetId);
61690
- }
61691
- const forkBinding = this.sessionBindings.get(fork.fork.sessionKey);
61692
- if (this.opts.dispatchAdapter.cleanupFork) {
61693
- const cleanupOpts = {
61694
- fork: fork.fork,
61695
- context: {
61696
- accountId: this.opts.accountId,
61697
- apiUrl: this.opts.config.parall_url,
61698
- apiKey: this.opts.config.api_key,
61699
- orgId: this.opts.config.org_id,
61700
- agentUserId: this.opts.agentUserId,
61701
- runtimeType: this.opts.runtimeType,
61702
- runtimeKey: this.opts.runtimeKey,
61703
- sessionId: forkBinding?.agentSessionId,
61704
- noReply: false,
61705
- client: this.opts.client,
61706
- log: this.opts.log
61707
- }
61708
- };
61709
- try {
61710
- await this.opts.dispatchAdapter.cleanupFork(cleanupOpts);
61711
- } catch (err) {
61712
- this.opts.log?.warn(`fork cleanupFork error for ${fork.targetId}: ${String(err)}`);
61713
- }
61714
- }
61715
- if (forkBinding) {
61716
- await this.forkFinalizer.finalize(forkBinding.agentSessionId, () => {
61717
- if (this.sessionBindings.get(fork.fork.sessionKey) === forkBinding) {
61718
- this.sessionBindings.delete(fork.fork.sessionKey);
61719
- }
61720
- });
61721
- }
61722
- }
62386
+ return forkDrainLoop(this, fork);
61723
62387
  }
61724
- /** Server-driven idle auto-compact (gateway-idle-compact.ts); exposed for the test harness. */
62388
+ /** Server-driven idle auto-compact (gateway/idle-compact.ts); exposed for the test harness. */
61725
62389
  handleCompactSignal(data) {
61726
62390
  return handleCompactSignal(this, data);
61727
62391
  }
@@ -61735,589 +62399,34 @@ var ParallAgentGateway = class {
61735
62399
  return runOutsideDispatchScope(() => this.mainDrainLoop());
61736
62400
  }
61737
62401
  async mainDrainLoop() {
61738
- if (this.draining)
61739
- return;
61740
- this.draining = true;
61741
- try {
61742
- while (this.idleCompact.inFlight)
61743
- await this.idleCompact.inFlight;
61744
- while (this.dispatchState.mainBuffer.length > 0) {
61745
- while (hasMainSteers(this.dispatchState))
61746
- await waitForMainSteers(this.dispatchState);
61747
- if (this.shuttingDown) {
61748
- this.opts.log?.info(`drainMainBuffer halted (shutting down) \u2014 ${this.dispatchState.mainBuffer.length} buffered, ${this.dispatchState.pendingForkResults.length} pending fork results left for catch-up`);
61749
- break;
61750
- }
61751
- const groupKey = this.dispatchGroupKey(this.dispatchState.mainBuffer[0]);
61752
- const hasPendingInjections = this.opts.dispatchAdapter.hasPendingInjections?.(this.opts.runtimeKey) ?? false;
61753
- const events = shiftMainBufferGroup(this.laneFlowHost(), groupKey, hasPendingInjections && this.opts.dispatchAdapter.inputLifecycleMode === "explicit");
61754
- const event = events[events.length - 1];
61755
- const earlier = events.slice(0, -1);
61756
- const pendingFork = hasPendingInjections ? [] : this.dispatchState.pendingForkResults.splice(0);
61757
- const forkPrefix = buildForkResultPrefix(pendingFork);
61758
- this.dispatchState.mainCurrentTargetId = event.targetId;
61759
- this.mainCurrentGroupKey = groupKey;
61760
- this.dispatchState.mainPreDispatchBranchPoint = this.opts.dispatchAdapter.getBranchPoint?.(this.opts.runtimeKey);
61761
- if (this.usesLaneLedger(event)) {
61762
- let outcome;
61763
- try {
61764
- outcome = await this.dispatchLaneGroup({
61765
- events,
61766
- sessionKey: this.opts.runtimeKey,
61767
- bodyPrefix: forkPrefix,
61768
- earlier,
61769
- hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === groupKey)
61770
- });
61771
- } catch (err) {
61772
- this.opts.log?.error(`lane dispatch failed for ${event.messageId}: ${String(err)}`);
61773
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61774
- for (const ev of events)
61775
- this.dispatchedMessages.delete(ev.messageId);
61776
- continue;
61777
- }
61778
- if (outcome === "shutdown") {
61779
- this.dispatchState.mainBuffer.unshift(...events);
61780
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61781
- break;
61782
- }
61783
- if (outcome === "foreign") {
61784
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61785
- continue;
61786
- }
61787
- if (outcome === "failed" || outcome === "deferred") {
61788
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61789
- continue;
61790
- }
61791
- continue;
61792
- }
61793
- const typedRefs = this.typedLedgerEventIds(events);
61794
- const drainingIds = events.map((ev) => ev.dispatchEventId).filter((id) => !!id);
61795
- for (const id of drainingIds)
61796
- this.drainingTypedIds.add(id);
61797
- try {
61798
- if (!typedRefs) {
61799
- try {
61800
- await this.emitDispatchReceived(event);
61801
- } catch (err) {
61802
- this.opts.log?.warn?.(`mark-received failed for buffered dispatch, leaving unacked for retry: ${String(err)}`);
61803
- this.dispatchState.mainBuffer.unshift(...events);
61804
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61805
- break;
61806
- }
61807
- }
61808
- const isTypedGroup = events.every(isTypedEvent);
61809
- const body = isTypedGroup && events.length > 1 && this.opts.dispatchAdapter.earlierEventsInPrompt !== true ? events.map((ev) => eventBody(ev)).join("\n\n") : eventBody(event);
61810
- let dispatched;
61811
- try {
61812
- dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + body, earlier);
61813
- } catch (err) {
61814
- if (!isTypedGroup)
61815
- throw err;
61816
- this.opts.log?.error(`typed drain dispatch failed for ${event.messageId} (group of ${events.length}): ${String(err)}`);
61817
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61818
- continue;
61819
- }
61820
- if (!dispatched) {
61821
- this.dispatchState.mainBuffer.unshift(...events);
61822
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61823
- break;
61824
- }
61825
- if (typedRefs) {
61826
- await settleDrainedTypedGroup(this.laneFlowHost(), events, typedRefs, this.consumeTurnError(this.opts.runtimeKey));
61827
- continue;
61828
- }
61829
- for (const bufferedEvent of events) {
61830
- const sourceType = bufferedEvent.ackSourceType ?? (bufferedEvent.type === "task" ? "task_activity" : "message");
61831
- const sourceId = bufferedEvent.ackSourceId ?? bufferedEvent.messageId;
61832
- this.opts.client.ackDispatch(this.opts.config.org_id, {
61833
- source_type: sourceType,
61834
- source_id: sourceId
61835
- }).catch(() => {
61836
- });
61837
- }
61838
- } finally {
61839
- for (const id of drainingIds)
61840
- this.drainingTypedIds.delete(id);
61841
- }
61842
- }
61843
- } finally {
61844
- this.draining = false;
61845
- this.dispatchState.mainDispatching = false;
61846
- this.dispatchState.mainCurrentTargetId = void 0;
61847
- this.mainCurrentGroupKey = void 0;
61848
- this.dispatchState.mainPreDispatchBranchPoint = void 0;
61849
- if (!this.shuttingDown && this.dispatchState.mainBuffer.length > 0) {
61850
- setTimeout(() => {
61851
- if (!this.draining && !this.dispatchState.mainDispatching && this.dispatchState.mainBuffer.length > 0) {
61852
- this.dispatchState.mainDispatching = true;
61853
- void this.drainMainBuffer();
61854
- }
61855
- }, 5e3).unref();
61856
- }
61857
- }
62402
+ return mainDrainLoop(this);
61858
62403
  }
61859
62404
  async handleInboundEvent(event) {
61860
- let disposition = routeTrigger(event, this.dispatchState);
61861
- if (this.idleCompact.inFlight && (disposition.action === "main" || disposition.action === "new-fork")) {
61862
- disposition = { action: "buffer-main" };
61863
- }
61864
- if (disposition.action === "main") {
61865
- clearForkContinuationRetries(this.forkContinuationRetries, [event]);
61866
- }
61867
- switch (disposition.action) {
61868
- case "main": {
61869
- const pendingFork = this.dispatchState.pendingForkResults.splice(0);
61870
- const forkPrefix = buildForkResultPrefix(pendingFork);
61871
- this.dispatchState.mainDispatching = true;
61872
- this.dispatchState.mainCurrentTargetId = event.targetId;
61873
- this.mainCurrentGroupKey = this.dispatchGroupKey(event);
61874
- this.dispatchState.mainPreDispatchBranchPoint = this.opts.dispatchAdapter.getBranchPoint?.(this.opts.runtimeKey);
61875
- if (this.usesLaneLedger(event)) {
61876
- let outcome = "shutdown";
61877
- try {
61878
- try {
61879
- outcome = await this.dispatchLaneGroup({
61880
- events: [event],
61881
- sessionKey: this.opts.runtimeKey,
61882
- bodyPrefix: forkPrefix,
61883
- earlier: [],
61884
- hasMoreLocal: () => this.dispatchState.mainBuffer.some((e) => this.dispatchGroupKey(e) === this.dispatchGroupKey(event))
61885
- });
61886
- } catch (err) {
61887
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61888
- throw err;
61889
- }
61890
- if (outcome !== "dispatched") {
61891
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61892
- }
61893
- } finally {
61894
- await this.drainMainBuffer();
61895
- }
61896
- return outcome === "dispatched";
61897
- }
61898
- const typedRefs = this.typedLedgerEventIds([event]);
61899
- if (!typedRefs) {
61900
- try {
61901
- await this.emitDispatchReceived(event);
61902
- } catch (err) {
61903
- this.opts.log?.warn?.(`mark-received failed, leaving unacked for retry: ${String(err)}`);
61904
- this.dispatchState.mainDispatching = false;
61905
- this.dispatchState.mainCurrentTargetId = void 0;
61906
- this.mainCurrentGroupKey = void 0;
61907
- this.dispatchState.mainPreDispatchBranchPoint = void 0;
61908
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61909
- return false;
61910
- }
61911
- }
61912
- let dispatched = false;
61913
- try {
61914
- dispatched = await this.runDispatch(event, this.opts.runtimeKey, forkPrefix + eventBody(event));
61915
- if (dispatched && typedRefs && this.consumeTurnError(this.opts.runtimeKey)) {
61916
- this.opts.log?.info(`typed dispatch turn for ${event.messageId} surfaced a runtime error \u2014 releasing for retry`);
61917
- dispatched = false;
61918
- }
61919
- if (!dispatched) {
61920
- this.dispatchState.pendingForkResults.unshift(...pendingFork);
61921
- }
61922
- } finally {
61923
- await this.drainMainBuffer();
61924
- }
61925
- return dispatched;
61926
- }
61927
- case "buffer-main": {
61928
- if (this.shuttingDown) {
61929
- return false;
61930
- }
61931
- if (this.isBufferedTypedWorkItem(event.dispatchEventId)) {
61932
- return false;
61933
- }
61934
- this.dispatchState.mainBuffer.push(event);
61935
- const typedAheadInBuffer = this.dispatchState.mainBuffer.some(isTypedEvent);
61936
- if (this.usesLaneLedger(event)) {
61937
- if (!this.idleCompact.inFlight && !typedAheadInBuffer && this.mainCurrentGroupKey === this.dispatchGroupKey(event) && this.opts.dispatchAdapter.enqueueDuringDispatch != null) {
61938
- await steerLaneMessage(this.laneFlowHost(), event);
61939
- }
61940
- } else if (
61941
- // Lane events only. A typed event (task_comment/schedule/…)
61942
- // rides the typed-consume contract — buffer-main resolves false and
61943
- // the claim releases for re-drive — so an injection here is exactly
61944
- // the forbidden un-folded injection: the LLM sees the content while
61945
- // the WorkItem stays live, and every re-drive injects it AGAIN (the
61946
- // 7/16 watcher duplicate-delivery loop, #1149). Typed events stay
61947
- // buffered; the drain claims them as their own turn.
61948
- !isTypedEvent(event) && event.frame != null && !this.idleCompact.inFlight && !typedAheadInBuffer && this.dispatchState.mainCurrentTargetId === event.targetId && await this.opts.dispatchAdapter.enqueueDuringDispatch?.(this.opts.runtimeKey, eventBody(event))
61949
- ) {
61950
- this.opts.log?.info(`steer injected for ${event.messageId} (will drain for bookkeeping)`);
61951
- }
61952
- if (!this.dispatchState.mainDispatching && !this.draining && this.dispatchState.mainBuffer.length > 0) {
61953
- this.dispatchState.mainDispatching = true;
61954
- void this.drainMainBuffer();
61955
- }
61956
- return false;
61957
- }
61958
- case "buffer-fork": {
61959
- const activeFork = this.forkStates.get(event.targetId);
61960
- if (!activeFork) {
61961
- this.dispatchState.mainBuffer.push(event);
61962
- return false;
61963
- }
61964
- return new Promise((resolve3) => {
61965
- activeFork.queue.push({ event, resolve: resolve3 });
61966
- });
61967
- }
61968
- case "new-fork": {
61969
- if (!this.opts.dispatchAdapter.forkSession) {
61970
- this.dispatchState.mainBuffer.push(event);
61971
- return false;
61972
- }
61973
- const continuationPrefix = resolveForkContinuationPrefix(this.dispatchState.pendingForkResults, this.forkContinuationRetries, event);
61974
- if (!this.usesLaneLedger(event) && !this.typedLedgerEventIds([event])) {
61975
- try {
61976
- await this.emitDispatchReceived(event);
61977
- } catch (err) {
61978
- this.opts.log?.warn?.(`mark-received failed for fork dispatch, leaving unacked for retry: ${String(err)}`);
61979
- this.dispatchState.mainBuffer.push(event);
61980
- return false;
61981
- }
61982
- }
61983
- const fork = await this.opts.dispatchAdapter.forkSession({
61984
- sessionKey: this.opts.runtimeKey,
61985
- context: this.buildDispatchContext(event, this.opts.runtimeKey),
61986
- preDispatchBranchPoint: this.dispatchState.mainPreDispatchBranchPoint
61987
- });
61988
- if (!fork) {
61989
- this.opts.log?.warn(`fork failed, buffering event for main session`);
61990
- this.dispatchState.mainBuffer.push(event);
61991
- return false;
61992
- }
61993
- const activeFork = createActiveForkState(fork, event.targetId, continuationPrefix);
61994
- this.forkStates.set(event.targetId, activeFork);
61995
- this.dispatchState.activeForks.set(event.targetId, fork.sessionKey);
61996
- if (this.FORK_DEADLINE_MS > 0) {
61997
- activeFork.deadlineTimer = setTimeout(() => {
61998
- this.abortFork(event.targetId, `deadline exceeded (${this.FORK_DEADLINE_MS}ms)`);
61999
- }, this.FORK_DEADLINE_MS);
62000
- }
62001
- const firstEventPromise = new Promise((resolve3) => {
62002
- activeFork.queue.push({ event, resolve: resolve3 });
62003
- });
62004
- this.runForkDrainLoop(activeFork).catch((err) => {
62005
- this.opts.log?.error(`fork drain loop error: ${String(err)}`);
62006
- });
62007
- return firstEventPromise;
62008
- }
62009
- }
62405
+ return handleInboundEvent(this, event);
62010
62406
  }
62011
- /**
62012
- * One WorkItem the server pushed (dispatch.new) or a catch-up page
62013
- * listed: messages ride their (chat, thread) lane, channel messages the
62014
- * server routed on a `prll://chv_…` lane ride that conversation lane;
62015
- * every other family (a channel message without target_uri included)
62016
- * rides its own dsp lane, claimed, run on the server frame, resolved by
62017
- * id. A typed WorkItem whose event copy is already buffered for the
62018
- * drain is left to the drain (re-claiming it would race the drain's
62019
- * fence-less settlement).
62020
- */
62021
62407
  async consumeWorkItem(item) {
62022
- await this.contractReady;
62023
- if (this.shuttingDown)
62024
- return;
62025
- if (item.event_type === "message") {
62026
- if (!item.chat_id || !item.source_id)
62027
- return;
62028
- await consumeMessageWorkItem(this.laneFlowHost(), {
62029
- id: item.id,
62030
- source_id: item.source_id,
62031
- chat_id: item.chat_id,
62032
- actor_id: item.actor_id,
62033
- thread_root_id: item.thread_root_id,
62034
- delivery_reason: item.delivery_reason
62035
- });
62036
- return;
62037
- }
62038
- const channelLane = channelLaneTargetUri(item);
62039
- if (channelLane) {
62040
- await consumeChannelWorkItem(this.laneFlowHost(), { ...item, target_uri: channelLane });
62041
- return;
62042
- }
62043
- if (!TYPED_EVENT_KINDS[item.event_type]) {
62044
- this.opts.log?.info(`dispatch with unhandled event_type=${String(item.event_type)} (id=${item.id}) \u2014 no-op`);
62045
- return;
62046
- }
62047
- if (this.isBufferedTypedWorkItem(item.id)) {
62048
- this.opts.log?.info(`typed dispatch ${item.id} already buffered for the drain \u2014 skipping re-claim`);
62049
- return;
62050
- }
62051
- await this.consumeTypedDispatch({ dispatchEventId: item.id }, (lane) => this.runTypedFrame(item, lane), { legacyAck: () => this.ackDispatchEvent(item.id) });
62408
+ return consumeWorkItem(this, item);
62052
62409
  }
62053
- /**
62054
- * Run one claimed typed WorkItem on the frame the claim returned. The
62055
- * event is addressing only: the routing target the server named
62056
- * (`input.subject` — the task, the wiki target, the schedule, the
62057
- * conversation, the chat an approval belongs to), the ids the ledger
62058
- * keys on, and the input-step metadata. No frame means nothing to run.
62059
- */
62060
62410
  async runTypedFrame(item, lane) {
62061
- if (this.shuttingDown)
62062
- return false;
62063
- const wake = this.laneLedger?.takeFrame(lane);
62064
- if (!wake?.frame) {
62065
- this.opts.log?.warn(`typed dispatch ${item.id} (${String(item.event_type)}) claimed without a frame \u2014 leaving it pending`);
62066
- this.redeclareRuntimeContract();
62067
- return false;
62068
- }
62069
- const kind = TYPED_EVENT_KINDS[item.event_type];
62070
- const targetId = wake.input?.subject || item.task_id || item.chat_id || item.source_id || item.id;
62071
- const event = {
62072
- type: kind.type,
62073
- targetId,
62074
- targetType: wake.input?.step_target?.type,
62075
- senderId: wake.input?.sender_id ?? item.actor_id ?? "system",
62076
- messageId: item.source_id,
62077
- deliveryReason: item.delivery_reason ?? void 0,
62078
- ackSourceType: kind.ackSourceType,
62079
- ackSourceId: item.source_id,
62080
- dispatchEventId: item.id
62081
- };
62082
- applyWake(event, wake);
62083
- this.opts.log?.info(`${String(item.event_type)} ${item.source_id} \u2192 ${targetId} (dispatch=${item.id})`);
62084
- return this.handleInboundEvent(event);
62411
+ return runTypedFrame(this, item, lane);
62085
62412
  }
62086
62413
  async catchUpFromDispatch() {
62087
- const OVERFLOW_THRESHOLD = 500;
62088
- const EXPIRE_AGE_HOURS = 24;
62089
- const CATCHUP_MAX = 10;
62090
- let expireSummary = null;
62091
- let overflowMode = false;
62092
- try {
62093
- const { count } = await this.opts.client.getDispatchPendingCount(this.opts.config.org_id);
62094
- if (count > OVERFLOW_THRESHOLD) {
62095
- overflowMode = true;
62096
- const result = await this.opts.client.expireDispatch(this.opts.config.org_id, EXPIRE_AGE_HOURS);
62097
- if (result.total > 0) {
62098
- this.opts.log?.warn(`dispatch catch-up overflow: ${count} pending, expired ${result.total} events older than ${EXPIRE_AGE_HOURS}h`);
62099
- expireSummary = this.buildOfflineSummary(result.groups);
62100
- }
62101
- }
62102
- } catch (err) {
62103
- this.opts.log?.warn(`dispatch catch-up overflow check failed: ${String(err)}`);
62104
- }
62105
- let cursor;
62106
- let processed = 0;
62107
- let skipped = 0;
62108
- const skippedByType = /* @__PURE__ */ new Map();
62109
- do {
62110
- const page = await this.opts.client.getDispatch(this.opts.config.org_id, {
62111
- limit: 50,
62112
- cursor
62113
- });
62114
- for (const item of page.data ?? []) {
62115
- if (this.shuttingDown)
62116
- break;
62117
- if (overflowMode && processed >= CATCHUP_MAX) {
62118
- try {
62119
- if (this.laneLedger && !this.ledgerDisabled && !this.typedByIdCompleteUnsupported) {
62120
- const outcome = await this.resolveDispatchByID(item.id);
62121
- if (outcome === "unsupported") {
62122
- this.typedByIdCompleteUnsupported = true;
62123
- await this.opts.client.ackDispatchByID(this.opts.config.org_id, item.id);
62124
- } else if (outcome === "failed") {
62125
- throw new Error("by-id complete failed");
62126
- }
62127
- } else {
62128
- await this.opts.client.ackDispatchByID(this.opts.config.org_id, item.id);
62129
- }
62130
- skipped++;
62131
- const key = item.event_type;
62132
- skippedByType.set(key, (skippedByType.get(key) ?? 0) + 1);
62133
- } catch {
62134
- this.opts.log?.warn(`catch-up skip ack failed for ${item.id}, leaving pending`);
62135
- }
62136
- continue;
62137
- }
62138
- processed++;
62139
- try {
62140
- await this.consumeWorkItem(item);
62141
- } catch (err) {
62142
- this.opts.log?.warn(`catch-up dispatch ${item.id} (${item.event_type}) failed: ${String(err)}`);
62143
- }
62144
- }
62145
- cursor = !this.shuttingDown && page.has_more ? page.next_cursor : void 0;
62146
- } while (cursor);
62147
- if (expireSummary || skipped > 0) {
62148
- const parts = [];
62149
- if (expireSummary)
62150
- parts.push(expireSummary);
62151
- if (skipped > 0) {
62152
- const recentLines = [...skippedByType.entries()].map(([type, count]) => `- ${count} recent ${type.replace(".", " ").replace("_", " ")} events`).join("\n");
62153
- parts.push(expireSummary ? `Additionally, ${skipped} recent events exceeded the catch-up limit and were skipped:
62154
- ${recentLines}` : `[Offline Summary] You were offline. ${skipped} pending events exceeded the catch-up limit and were skipped:
62155
- ${recentLines}
62156
-
62157
- Use your tools (read messages, check tasks) to review anything still relevant.`);
62158
- }
62159
- const fullSummary = parts.join("\n\n");
62160
- this.pendingRestartNotification = this.pendingRestartNotification ? `${this.pendingRestartNotification}
62161
-
62162
- ${fullSummary}` : fullSummary;
62163
- }
62164
- if (processed > 0 || skipped > 0) {
62165
- this.opts.log?.info(`dispatch catch-up: processed ${processed}, skipped ${skipped}`);
62166
- }
62414
+ return catchUpFromDispatch(this);
62167
62415
  }
62168
62416
  buildOfflineSummary(groups) {
62169
- const lines = [
62170
- "[Offline Summary] You were offline and had a large backlog of pending events. The following old events were skipped:"
62171
- ];
62172
- for (const g of groups) {
62173
- const age = this.formatAge(g.oldest);
62174
- if (g.chat_id && g.event_type === "message") {
62175
- const name = g.chat_name ?? g.chat_id;
62176
- lines.push(`- ${g.count} messages in "${name}" (oldest: ${age})`);
62177
- } else {
62178
- const label = g.event_type.replace(".", " ").replace("_", " ");
62179
- lines.push(`- ${g.count} ${label} events (oldest: ${age})`);
62180
- }
62181
- }
62182
- lines.push("");
62183
- lines.push("These events were too old to process individually. Use your tools (read messages, check tasks) to review anything still relevant.");
62184
- return lines.join("\n");
62417
+ return buildOfflineSummary(this, groups);
62185
62418
  }
62186
62419
  formatAge(iso) {
62187
- const ms = Date.now() - new Date(iso).getTime();
62188
- const hours = Math.floor(ms / 36e5);
62189
- if (hours < 24)
62190
- return `${hours}h ago`;
62191
- const days = Math.floor(hours / 24);
62192
- return `${days}d ago`;
62420
+ return formatAge(this, iso);
62193
62421
  }
62194
62422
  async handleHello(data) {
62195
- const { client, config, log: log2 } = this.opts;
62196
- this.sessionId = data.session_id ?? "";
62197
- if (this.forkStates.size > 0) {
62198
- const targetIds = [...this.forkStates.keys()];
62199
- if (this.opts.instanceId) {
62200
- log2?.info(`${targetIds.length} active fork(s) continue across the reconnect`);
62201
- } else {
62202
- log2?.info(`aborting ${targetIds.length} active fork(s) on reconnect`);
62203
- for (const targetId of targetIds) {
62204
- this.abortFork(targetId, "ws reconnect");
62205
- }
62206
- }
62207
- }
62208
- if (this.laneLedger && !this.opts.instanceId && this.inFlightDispatches === 0 && this.laneLedger.activeCount > 0) {
62209
- log2?.info(`releasing ${this.laneLedger.activeCount} stale lane(s) on reconnect`);
62210
- await this.laneLedger.releaseAll();
62211
- }
62212
- if (this.laneLedger && this.ledgerDisabled) {
62213
- log2?.info("re-probing dispatch ledger after reconnect (was disabled)");
62214
- this.ledgerDisabled = false;
62215
- }
62216
- const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
62217
- let openFence = () => {
62218
- };
62219
- this.contractReady = new Promise((resolve3) => {
62220
- openFence = resolve3;
62221
- });
62222
- try {
62223
- log2?.info("WebSocket connected");
62224
- try {
62225
- await this.declareRuntimeContract();
62226
- } finally {
62227
- openFence();
62228
- }
62229
- await this.opts.onSessionReady?.({
62230
- activeSessionId: this.activeSessionId,
62231
- ws: this.opts.ws,
62232
- runtimeKey: this.opts.runtimeKey
62233
- });
62234
- if (this.heartbeatTimer)
62235
- clearInterval(this.heartbeatTimer);
62236
- this.lastHeartbeatAt = Date.now();
62237
- this.heartbeatTimer = setInterval(() => {
62238
- const now = Date.now();
62239
- const expectedMs = intervalSec * 1e3;
62240
- const drift = now - this.lastHeartbeatAt - expectedMs;
62241
- if (drift > 15e3) {
62242
- log2?.warn(`heartbeat drift ${drift}ms \u2014 event loop may be blocked`);
62243
- }
62244
- this.lastHeartbeatAt = now;
62245
- if (this.opts.ws.state !== "connected")
62246
- return;
62247
- this.opts.ws.sendAgentHeartbeat(this.sessionId, {
62248
- hostname: os.hostname(),
62249
- cores: os.cpus().length,
62250
- mem_total: os.totalmem(),
62251
- mem_free: os.freemem(),
62252
- uptime: os.uptime()
62253
- });
62254
- }, intervalSec * 1e3);
62255
- await this.laneLedger?.retryConfirmations();
62256
- this.catchUpFromDispatch().catch((err) => {
62257
- log2?.warn(`dispatch catch-up failed: ${String(err)}`);
62258
- });
62259
- } catch (err) {
62260
- log2?.error(`failed to fetch chats: ${String(err)}`);
62261
- }
62423
+ return handleHello(this, data);
62262
62424
  }
62263
- /**
62264
- * Declare the runtime contract for this connection: the server decides
62265
- * who runs and renders the wake frame; this runtime only runs. Bound to
62266
- * the WS session id, so it repeats on every hello. Retried with backoff
62267
- * until it lands — WorkItems wait behind the fence meanwhile, nothing is
62268
- * claimed without a frame. The declaration is the agent's runtime report
62269
- * (bridge + node versions, `runtime_contract` feature); the SDK hands a
62270
- * server that predates reports the legacy contract-only declaration, and a
62271
- * server that predates both (404) renders no frames: the runtime runs
62272
- * nothing and WorkItems stay pending. A stale-session 409 means a newer
62273
- * connection already declared.
62274
- */
62275
- /**
62276
- * LaneFlowHost.redeclareRuntimeContract: a frameless claim means the server
62277
- * does not see this connection's declaration — repeat it for the current
62278
- * session so the released members render on their re-drive. Idempotent on
62279
- * the server (an unchanged report is not rewritten).
62280
- */
62281
62425
  redeclareRuntimeContract() {
62282
- if (this.redeclareInFlight || !this.sessionId)
62283
- return;
62284
- this.opts.log?.info("re-declaring the runtime contract after a frameless claim");
62285
- this.redeclareInFlight = this.declareRuntimeContract().finally(() => {
62286
- this.redeclareInFlight = null;
62287
- });
62426
+ return redeclareRuntimeContract(this);
62288
62427
  }
62289
62428
  async declareRuntimeContract() {
62290
- const session = this.sessionId;
62291
- if (!session)
62292
- return;
62293
- for (let attempt = 0; ; attempt++) {
62294
- try {
62295
- await declareAgentRuntimeReport(this.opts.client, {
62296
- orgId: this.opts.config.org_id,
62297
- wsSessionId: session,
62298
- runtimeVersion: this.opts.runtimeVersion
62299
- });
62300
- this.opts.log?.info("runtime contract declared (server-rendered frames)");
62301
- return;
62302
- } catch (err) {
62303
- if (err instanceof ApiError && err.status === 404) {
62304
- this.opts.log?.warn("server predates the runtime contract \u2014 it renders no wake frames; WorkItems stay pending");
62305
- return;
62306
- }
62307
- if (err instanceof ApiError && err.status === 409) {
62308
- this.opts.log?.info("runtime contract already declared by a newer connection");
62309
- return;
62310
- }
62311
- const delayMs = Math.min(3e4, 2e3 * 2 ** Math.min(attempt, 4));
62312
- this.opts.log?.warn(`runtime contract declaration failed (retry in ${delayMs / 1e3}s): ${String(err)}`);
62313
- await new Promise((resolve3) => {
62314
- const timer = setTimeout(resolve3, delayMs);
62315
- timer.unref?.();
62316
- });
62317
- if (this.shuttingDown || this.sessionId !== session)
62318
- return;
62319
- }
62320
- }
62429
+ return declareRuntimeContract(this);
62321
62430
  }
62322
62431
  /** Drain includes in-flight native work and unfinished steer registration. */
62323
62432
  isDrained() {
@@ -62335,46 +62444,7 @@ ${fullSummary}` : fullSummary;
62335
62444
  this.drainGate.notify();
62336
62445
  }
62337
62446
  async shutdown(opts = { skipDrain: false }) {
62338
- this.shuttingDown = true;
62339
- this.idleCompact.abort?.();
62340
- if (opts.skipDrain && !this.isDrained()) {
62341
- this.opts.log?.warn(`skipping drain (credential rejected): ${this.inFlightDispatches} dispatch(es), ${this.inFlightRuntimeTurns} runtime-initiated turn(s) abandoned to server redelivery`);
62342
- } else if (!this.isDrained()) {
62343
- this.opts.log?.info(`draining ${this.inFlightDispatches} in-flight dispatch(es), ${this.inFlightRuntimeTurns} runtime-initiated turn(s), runtime busy=${this.adapterBusy()}, deadline ${this.SHUTDOWN_DEADLINE_MS}ms`);
62344
- await this.drainGate.wait(this.SHUTDOWN_DEADLINE_MS);
62345
- if (!this.isDrained()) {
62346
- this.opts.log?.warn(`drain deadline hit; ${this.inFlightDispatches} dispatch(es), ${this.inFlightRuntimeTurns} runtime-initiated turn(s), runtime busy=${this.adapterBusy()} \u2014 they will be killed by process exit`);
62347
- } else {
62348
- this.opts.log?.info(`drain complete`);
62349
- }
62350
- }
62351
- if (this.heartbeatTimer)
62352
- clearInterval(this.heartbeatTimer);
62353
- if (this.laneLedger) {
62354
- this.opts.log?.info(`releasing ${this.laneLedger.activeCount} lane(s) on shutdown`);
62355
- await this.laneLedger.releaseAll();
62356
- }
62357
- await this.opts.onBeforeDisconnect?.();
62358
- if (this.inFlightRuntimeTurns > 0) {
62359
- await this.drainGate.wait(5e3, () => this.inFlightRuntimeTurns === 0);
62360
- }
62361
- if (this.stepPersister.pendingTotal() > 0) {
62362
- const remaining = await this.stepPersister.flush(1e4);
62363
- if (remaining > 0) {
62364
- this.opts.log?.warn(`${remaining} parked step write(s) could not be flushed at shutdown; they are permanently lost`);
62365
- }
62366
- }
62367
- this.stepPersister.dispose();
62368
- const lifecycleRemaining = await this.sessionLifecycle.flush(5e3);
62369
- if (lifecycleRemaining > 0) {
62370
- this.opts.log?.warn(`${lifecycleRemaining} session lifecycle write(s) unreconciled at shutdown`);
62371
- }
62372
- this.sessionLifecycle.dispose();
62373
- await this.laneLedger?.retryConfirmations();
62374
- this.laneLedger?.dispose();
62375
- this.opts.ws.disconnect();
62376
- this.unsubscribeRuntimeActivity?.();
62377
- this.opts.log?.info(`disconnected`);
62447
+ return shutdown(this, opts);
62378
62448
  }
62379
62449
  };
62380
62450