@bastani/atomic 0.9.57 → 0.9.58

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.
Files changed (128) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/CHANGELOG.md +18 -0
  5. package/dist/builtin/subagents/README.md +3 -1
  6. package/dist/builtin/subagents/package.json +1 -1
  7. package/dist/builtin/subagents/src/extension/index.bundle.mjs +202 -38
  8. package/dist/builtin/web-access/CHANGELOG.md +12 -0
  9. package/dist/builtin/web-access/index.bundle.mjs +2 -2
  10. package/dist/builtin/web-access/package.json +1 -1
  11. package/dist/builtin/workflows/CHANGELOG.md +42 -0
  12. package/dist/builtin/workflows/package.json +1 -1
  13. package/dist/builtin/workflows/src/extension/index.bundle.mjs +885 -228
  14. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +933 -175
  15. package/dist/builtin/workflows/src/index.js +630 -162
  16. package/dist/builtin/workflows/src/local-worker-entry.mjs +933 -175
  17. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +1 -1
  18. package/dist/builtin/workflows/src/shared/workflow-infrastructure-error.d.ts +13 -0
  19. package/dist/builtin/workflows/src/workers/public-options.d.ts +10 -0
  20. package/dist/core/agent-session-persistent-custom-messages.d.ts +5 -0
  21. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  22. package/dist/core/agent-session-persistent-custom-messages.js +16 -0
  23. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  24. package/dist/core/agent-session-tasks.d.ts.map +1 -1
  25. package/dist/core/agent-session-tasks.js +20 -0
  26. package/dist/core/agent-session-tasks.js.map +1 -1
  27. package/dist/core/child-session-options.d.ts.map +1 -1
  28. package/dist/core/child-session-options.js +3 -1
  29. package/dist/core/child-session-options.js.map +1 -1
  30. package/dist/core/sdk-types.d.ts +6 -1
  31. package/dist/core/sdk-types.d.ts.map +1 -1
  32. package/dist/core/sdk-types.js.map +1 -1
  33. package/dist/core/sdk.js +4 -2
  34. package/dist/core/sdk.js.map +1 -1
  35. package/dist/core/settings-defaults.d.ts +4 -0
  36. package/dist/core/settings-defaults.d.ts.map +1 -1
  37. package/dist/core/settings-defaults.js +4 -0
  38. package/dist/core/settings-defaults.js.map +1 -1
  39. package/dist/core/settings-manager-resource-accessors.d.ts +2 -0
  40. package/dist/core/settings-manager-resource-accessors.d.ts.map +1 -1
  41. package/dist/core/settings-manager-resource-accessors.js +6 -0
  42. package/dist/core/settings-manager-resource-accessors.js.map +1 -1
  43. package/dist/core/settings-schema.d.ts +9 -0
  44. package/dist/core/settings-schema.d.ts.map +1 -1
  45. package/dist/core/settings-schema.js +11 -0
  46. package/dist/core/settings-schema.js.map +1 -1
  47. package/dist/core/settings-types.d.ts +1 -1
  48. package/dist/core/settings-types.d.ts.map +1 -1
  49. package/dist/core/settings-types.js.map +1 -1
  50. package/dist/core/tasks/agent-adapter.d.ts +10 -1
  51. package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
  52. package/dist/core/tasks/agent-adapter.js +20 -0
  53. package/dist/core/tasks/agent-adapter.js.map +1 -1
  54. package/dist/core/tasks/contracts.d.ts +6 -0
  55. package/dist/core/tasks/contracts.d.ts.map +1 -1
  56. package/dist/core/tasks/contracts.js.map +1 -1
  57. package/dist/core/tasks/heartbeat-notice.d.ts +64 -0
  58. package/dist/core/tasks/heartbeat-notice.d.ts.map +1 -0
  59. package/dist/core/tasks/heartbeat-notice.js +98 -0
  60. package/dist/core/tasks/heartbeat-notice.js.map +1 -0
  61. package/dist/core/tasks/heartbeat.d.ts +75 -0
  62. package/dist/core/tasks/heartbeat.d.ts.map +1 -0
  63. package/dist/core/tasks/heartbeat.js +440 -0
  64. package/dist/core/tasks/heartbeat.js.map +1 -0
  65. package/dist/core/tasks/supervisor.d.ts +2 -0
  66. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  67. package/dist/core/tasks/supervisor.js +32 -4
  68. package/dist/core/tasks/supervisor.js.map +1 -1
  69. package/dist/core/tasks/task-view-source.d.ts +72 -0
  70. package/dist/core/tasks/task-view-source.d.ts.map +1 -0
  71. package/dist/core/tasks/task-view-source.js +155 -0
  72. package/dist/core/tasks/task-view-source.js.map +1 -0
  73. package/dist/core/tools/bash-pty-native.d.ts +2 -0
  74. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  75. package/dist/core/tools/bash-pty-native.js +1 -0
  76. package/dist/core/tools/bash-pty-native.js.map +1 -1
  77. package/dist/core/tools/bash.d.ts +3 -0
  78. package/dist/core/tools/bash.d.ts.map +1 -1
  79. package/dist/core/tools/bash.js +20 -2
  80. package/dist/core/tools/bash.js.map +1 -1
  81. package/dist/core/tools/powershell.d.ts +16 -8
  82. package/dist/core/tools/powershell.d.ts.map +1 -1
  83. package/dist/index.d.ts +5 -3
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +4 -2
  86. package/dist/index.js.map +1 -1
  87. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  88. package/dist/modes/interactive/components/chat-session-host-events.js +7 -0
  89. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  90. package/dist/modes/interactive/components/chat-session-host-state.d.ts +3 -0
  91. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  92. package/dist/modes/interactive/components/chat-session-host-state.js +4 -0
  93. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  94. package/dist/modes/interactive/components/chat-session-host-types.d.ts +11 -0
  95. package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
  96. package/dist/modes/interactive/components/chat-session-host-types.js.map +1 -1
  97. package/dist/modes/interactive/components/chat-session-host.d.ts +2 -0
  98. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  99. package/dist/modes/interactive/components/chat-session-host.js +15 -8
  100. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  101. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  102. package/dist/modes/interactive/components/custom-message.js +12 -0
  103. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  104. package/dist/modes/interactive/components/task-detail.d.ts.map +1 -1
  105. package/dist/modes/interactive/components/task-detail.js +5 -0
  106. package/dist/modes/interactive/components/task-detail.js.map +1 -1
  107. package/dist/modes/interactive/components/task-heartbeat-message.d.ts +14 -0
  108. package/dist/modes/interactive/components/task-heartbeat-message.d.ts.map +1 -0
  109. package/dist/modes/interactive/components/task-heartbeat-message.js +76 -0
  110. package/dist/modes/interactive/components/task-heartbeat-message.js.map +1 -0
  111. package/dist/modes/interactive/components/task-inspector.d.ts +6 -3
  112. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  113. package/dist/modes/interactive/components/task-inspector.js +53 -100
  114. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  115. package/dist/modes/interactive/skill-command-autocomplete.d.ts +22 -2
  116. package/dist/modes/interactive/skill-command-autocomplete.d.ts.map +1 -1
  117. package/dist/modes/interactive/skill-command-autocomplete.js +28 -9
  118. package/dist/modes/interactive/skill-command-autocomplete.js.map +1 -1
  119. package/docs/background-tasks.md +65 -1
  120. package/docs/sdk.md +3 -1
  121. package/docs/settings.md +12 -0
  122. package/docs/subagents/reference.md +2 -0
  123. package/docs/subagents.md +2 -0
  124. package/docs/tools.md +2 -1
  125. package/docs/workflows/operations.md +5 -3
  126. package/npm-shrinkwrap.json +32 -32
  127. package/package.json +3 -3
  128. package/schemas/settings.schema.json +24 -0
@@ -325,7 +325,7 @@ export interface ToolNodeSnapshot extends WorkflowSerializableObject {
325
325
  */
326
326
  export interface RunFailureClassification extends WorkflowSerializableObject {
327
327
  readonly kind: "auth" | "rate_limit" | "provider" | "cancelled" | "unknown";
328
- readonly code?: "login_required" | "auth_timeout" | "missing_api_key" | "invalid_api_key" | "forbidden_config" | "unknown_model" | "rate_limited" | "quota_limited" | "provider_unavailable" | "pending_stage_delivery_failed" | "cancelled" | "unknown";
328
+ readonly code?: "login_required" | "auth_timeout" | "missing_api_key" | "invalid_api_key" | "forbidden_config" | "unknown_model" | "rate_limited" | "quota_limited" | "provider_unavailable" | "pending_stage_delivery_failed" | "worker_lost" | "worker_cleanup_unconfirmed" | "worker_retry_limit" | "worker_startup_failed" | "stale_work_lease" | "intercom_unavailable" | "storage_unavailable" | "cancelled" | "unknown";
329
329
  /** Whether retrying the same work can succeed, as for a rate limit or an outage. */
330
330
  readonly retryable: boolean;
331
331
  /** Whether the run can be resumed after this failure. */
@@ -1,4 +1,6 @@
1
1
  export type WorkflowInfrastructureFault = "worker_lost" | "worker_cleanup_unconfirmed" | "worker_retry_limit" | "worker_startup_failed" | "stale_work_lease" | "intercom_unavailable" | "storage_unavailable";
2
+ /** Every infrastructure fault, as a stage or run failure records it in `failureCode`. */
3
+ export declare const WORKFLOW_INFRASTRUCTURE_FAULTS: ReadonlySet<string>;
2
4
  export declare class WorkflowInfrastructureError extends Error {
3
5
  readonly name = "WorkflowInfrastructureError";
4
6
  readonly retryable = true;
@@ -8,3 +10,14 @@ export declare class WorkflowInfrastructureError extends Error {
8
10
  export declare function isRetryableWorkflowError(error: unknown): boolean;
9
11
  export declare function workflowInfrastructureFault(message: string): WorkflowInfrastructureFault | undefined;
10
12
  export declare function asWorkflowInfrastructureError(error: unknown): WorkflowInfrastructureError | undefined;
13
+ /**
14
+ * Whether a failed run result failed on infrastructure: its classified failure, its error, or the error or failure
15
+ * code of a failed stage names an infrastructure fault. Results recorded before stage failures were classified by
16
+ * fault carry only the fault's message, which this recognizes too.
17
+ */
18
+ export declare function failedOnInfrastructureFault(result: {
19
+ readonly status?: unknown;
20
+ readonly error?: unknown;
21
+ readonly failure?: unknown;
22
+ readonly stages?: unknown;
23
+ }): boolean;
@@ -21,7 +21,17 @@ export interface LocalWorkerOptions {
21
21
  }[];
22
22
  readonly startupTimeoutMs?: number;
23
23
  readonly leaseMs?: number;
24
+ /**
25
+ * Load per CPU (the one-minute load average divided by the CPU count) above which the stages of pooled children start
26
+ * one at a time, at most one every five seconds and in the order they asked, so an overloaded machine is not given
27
+ * a burst of stage starts while earlier ones are still starting. Running stages, the subagents they start and their
28
+ * tool processes are not held. Default {@link DEFAULT_POOLED_STAGE_START_MAX_LOAD_PER_CPU}; `0` turns the pacing
29
+ * off. Not saved with the root.
30
+ */
31
+ readonly maxLoadPerCpu?: number;
24
32
  }
33
+ /** Load per CPU above which pooled stages wait to start, unless `localWorkers.maxLoadPerCpu` says otherwise. */
34
+ export declare const DEFAULT_POOLED_STAGE_START_MAX_LOAD_PER_CPU = 3;
25
35
  export interface WorkflowExecutionResources {
26
36
  readonly localWorkers?: LocalWorkerOptions;
27
37
  /**
@@ -27,6 +27,11 @@ export declare function triggerProtectedStreamingCustomMessages(session: AgentSe
27
27
  /** Record that agent-core drained and consumed the hidden reconciliation. */
28
28
  export declare function markProtectedStreamingCustomMessageConsumed(session: AgentSession, message: CustomMessage): boolean;
29
29
  export declare function markProtectedStreamingCustomMessagePersistenceFailed(session: AgentSession, message: CustomMessage): void;
30
+ /**
31
+ * Whether a durable card of this custom type is admitted but its hidden turn is still queued, so the model has not
32
+ * read it yet. Clearing the queue restores protected turns, so a queued entry ends only when it is consumed.
33
+ */
34
+ export declare function hasUnreadProtectedCustomMessage(session: AgentSession, customType: string): boolean;
30
35
  export declare function isProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean;
31
36
  /**
32
37
  * Persist a consumed hidden reconciliation exactly once. Its visible card was
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-persistent-custom-messages.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AACrE,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AE,aAAa,EAAE,EACzB,QAAQ,EAAE,iBAAiB,GACzB,OAAO,CAAC,IAAI,CAAC,CAYf;AAED,6EAA6E;AAC7E,wBAAgB,2CAA2C,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAKlH;AAED,wBAAgB,oDAAoD,CACnE,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,aAAa,GACpB,IAAI,CAGN;AAED,wBAAgB,iCAAiC,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAExG;AAED;;;;GAIG;AACH,wBAAsB,sCAAsC,CAC3D,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,aAAa,GACpB,OAAO,CAAC,OAAO,CAAC,CAkBlB;AAED,+EAA+E;AAC/E,wBAAsB,6CAA6C,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAUxG;AAED,4EAA4E;AAC5E,wBAAsB,6CAA6C,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAOxG;AAgCD;;;;GAIG;AACH,wBAAsB,kDAAkD,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAsB7G;AAED,kFAAkF;AAClF,wBAAgB,uCAAuC,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAOhH;AAED,oFAAoF;AACpF,wBAAgB,wCAAwC,CACvD,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,YAAY,EACpB,WAAW,EAAE,kBAAkB,GAC7B,IAAI,CAUN"}
1
+ {"version":3,"file":"agent-session-persistent-custom-messages.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MA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edStreamingCustomMessagePersistenceFailed(session, me
184
184
  if (entry?.phase === "consumed-unpersisted")
185
185
  entry.phase = "persistence-failed";
186
186
  }
187
+ /**
188
+ * Whether a durable card of this custom type is admitted but its hidden turn is still queued, so the model has not
189
+ * read it yet. Clearing the queue restores protected turns, so a queued entry ends only when it is consumed.
190
+ */
191
+ export function hasUnreadProtectedCustomMessage(session, customType) {
192
+ const owner = resolveWorkflowStageDeliveryTarget(session);
193
+ return protectedMessages(owner).some((entry) => {
194
+ if (entry.phase !== "queued")
195
+ return false;
196
+ const intent = completedReconciliationIntent(entry.message.details);
197
+ if (intent === undefined)
198
+ return false;
199
+ const card = owner.sessionManager.getEntry(intent);
200
+ return card?.type === "custom_message" && card.customType === customType;
201
+ });
202
+ }
187
203
  export function isProtectedStreamingCustomMessage(session, message) {
188
204
  return protectedMessages(session).some((entry) => entry.message === message);
189
205
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-persistent-custom-messages.js","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAOxE,MAAM,CAAC,MAAM,oCAAoC,GAAG,2CAA2C,CAAC;AAchG,SAAS,iBAAiB,CAAC,OAAqB;IAC/C,OAAO,CAAC,iCAAiC,KAAK,EAAE,CAAC;IACjD,OAAO,OAAO,CAAC,iCAAiC,CAAC;AAClD,CAAC;AAED,KAAK,UAAU,wBAAwB,CACtC,OAAqB,EACrB,OAAsB,EACtB,QAA2B;IAE3B,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAyD,CAAC;IAC7G,MAAM,QAAQ,GAAG,OAAqC,CAAC;IACvD,6EAA6E;IAC7E,oEAAoE;IACpE,MAAM,OAAO,GACZ,QAAQ,CAAC,iBAAiB,KAAK,SAAS;QACvC,C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AAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/C,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;YACvF,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IACD,MAAM,CAAC,iCAAiC,GAAG,QAAQ,CAAC;IACpD,iBAAiB,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { DrainedAgentQueues } from \"./agent-session-types.js\";\nimport { customMessageExcludesContext } from \"./agent-session-types.js\";\nimport type { PendingRecoveryDelivery } from \"./extensions/index.js\";\nimport type { CustomMessage, StageAdmittedCustomMessage } from \"./messages.ts\";\n\ntype ProtectedDelivery = \"steer\" | \"followUp\";\ntype ProtectedPhase = \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\nexport const PROTECTED_RECONCILIATION_CUSTOM_TYPE = \"atomic:protected-streaming-reconciliation\";\n\ninterface ProtectedReconciliationDetails {\n\tprotectedReconciliationOf: string;\n\t/** Set when resume recovery declined to replay the card to the model. */\n\trecovery?: \"dropped\";\n}\n\nexport interface ProtectedStreamingCustomMessage {\n\tmessage: CustomMessage;\n\tdelivery: ProtectedDelivery;\n\tphase: ProtectedPhase;\n}\n\nfunction protectedMessages(session: AgentSession): ProtectedStreamingCustomMessage[] {\n\tsession._protectedStreamingCustomMessages ??= [];\n\treturn session._protectedStreamingCustomMessages;\n}\n\nasync function appendDurableDisplayCard(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<{ readonly card: CustomMessage & { excludeFromContext: true }; readonly intentEntryId: string }> {\n\tconst card = { ...message, excludeFromContext: true } satisfies CustomMessage & { excludeFromContext: true };\n\tconst admitted = message as StageAdmittedCustomMessage;\n\t// A retry after a failed flush must complete the already-appended occurrence\n\t// rather than append a second visible card for the same stable key.\n\tconst partial =\n\t\tadmitted.stageAdmissionKey === undefined\n\t\t\t? undefined\n\t\t\t: session.sessionManager\n\t\t\t\t\t.getBranch()\n\t\t\t\t\t.find(\n\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\tentry.type === \"custom_message\" &&\n\t\t\t\t\t\t\tentry.stageAdmissionKey === admitted.stageAdmissionKey &&\n\t\t\t\t\t\t\tprotectedDelivery(entry.protectedReconciliation) !== undefined,\n\t\t\t\t\t);\n\t// The card and recovery marker share one append, so either both survive a\n\t// process exit or neither does.\n\tconst intentEntryId =\n\t\tpartial?.id ??\n\t\t(await session.sessionManager.appendCustomMessageEntry(\n\t\t\tcard.customType,\n\t\t\tcard.content,\n\t\t\tcard.display,\n\t\t\tcard.details,\n\t\t\ttrue,\n\t\t\t{ delivery },\n\t\t\tadmitted.stageAdmissionKey,\n\t\t));\n\tsession._entryIdsByMessage.set(card, intentEntryId);\n\tsession._refreshFinalizedContext();\n\treturn { card, intentEntryId };\n}\n\nfunction emitDurableDisplayCard(session: AgentSession, card: CustomMessage): void {\n\t// The card is already live and file-backed, and its protected reconciliation\n\t// is registered. Public listeners remain fallible, but their errors cannot\n\t// revoke admission or make the producer retry this committed occurrence.\n\ttry {\n\t\tsession._emit({ type: \"message_start\", message: card });\n\t} catch {}\n\ttry {\n\t\tsession._emit({ type: \"message_end\", message: card });\n\t} catch {}\n}\n\nfunction createProtectedReconciliation(message: CustomMessage, intentEntryId: string): CustomMessage {\n\treturn {\n\t\trole: \"custom\",\n\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tcontent: message.content,\n\t\tdisplay: false,\n\t\tdetails: { protectedReconciliationOf: intentEntryId } satisfies ProtectedReconciliationDetails,\n\t\ttimestamp: message.timestamp,\n\t};\n}\n\nfunction completedReconciliationIntent(details: unknown): string | undefined {\n\tif (details === null || typeof details !== \"object\") return undefined;\n\tconst intent = (details as { protectedReconciliationOf?: unknown }).protectedReconciliationOf;\n\treturn typeof intent === \"string\" ? intent : undefined;\n}\n\nfunction protectedDelivery(marker: unknown): ProtectedDelivery | undefined {\n\tif (marker === null || typeof marker !== \"object\") return undefined;\n\tconst delivery = (marker as { delivery?: unknown }).delivery;\n\treturn delivery === \"steer\" || delivery === \"followUp\" ? delivery : undefined;\n}\n\n/** Durable card intents with neither a persisted hidden completion nor a scheduled one. */\nexport function pendingProtectedStreamingCustomMessages(session: AgentSession): PendingRecoveryDelivery[] {\n\tconst branch = session.sessionManager.getBranch();\n\tconst completed = new Set(\n\t\tbranch.flatMap((entry) =>\n\t\t\tentry.type === \"custom_message\" && entry.customType === PROTECTED_RECONCILIATION_CUSTOM_TYPE\n\t\t\t\t? [completedReconciliationIntent(entry.details)].filter((intent): intent is string => intent !== undefined)\n\t\t\t\t: [],\n\t\t),\n\t);\n\tconst scheduled = new Set(\n\t\tprotectedMessages(session).flatMap((entry) => {\n\t\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\t\treturn intent === undefined ? [] : [intent];\n\t\t}),\n\t);\n\tconst pending: PendingRecoveryDelivery[] = [];\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom_message\") continue;\n\t\tconst delivery = protectedDelivery(entry.protectedReconciliation);\n\t\tif (delivery === undefined || completed.has(entry.id) || scheduled.has(entry.id)) continue;\n\t\tpending.push({\n\t\t\tentryId: entry.id,\n\t\t\tcustomType: entry.customType,\n\t\t\tcontent: entry.content,\n\t\t\tdetails: entry.details,\n\t\t\ttimestamp: entry.timestamp,\n\t\t\t...(entry.stageAdmissionKey === undefined ? {} : { stageAdmissionKey: entry.stageAdmissionKey }),\n\t\t\tdelivery,\n\t\t});\n\t}\n\treturn pending;\n}\n\n/** Requeue the hidden model-facing turn of each recovered durable card. */\nexport function recoverProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tpending: readonly PendingRecoveryDelivery[],\n): number {\n\tfor (const entry of pending) {\n\t\tconst parsedTimestamp = Date.parse(entry.timestamp);\n\t\tconst reconciliation: CustomMessage = {\n\t\t\trole: \"custom\",\n\t\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\t\tcontent: entry.content,\n\t\t\tdisplay: false,\n\t\t\tdetails: { protectedReconciliationOf: entry.entryId } satisfies ProtectedReconciliationDetails,\n\t\t\ttimestamp: Number.isFinite(parsedTimestamp) ? parsedTimestamp : Date.now(),\n\t\t};\n\t\tprotectedMessages(session).push({ message: reconciliation, delivery: entry.delivery, phase: \"queued\" });\n\t\tsession._queueAgentMessage(reconciliation, entry.delivery);\n\t}\n\treturn pending.length;\n}\n\n/** Close a recovered card without a model turn, so later resumes never offer it again. */\nexport async function dismissProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tpending: PendingRecoveryDelivery,\n): Promise<void> {\n\tawait session.sessionManager.appendCustomMessageEntry(\n\t\tPROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tpending.content,\n\t\tfalse,\n\t\t{ protectedReconciliationOf: pending.entryId, recovery: \"dropped\" } satisfies ProtectedReconciliationDetails,\n\t\ttrue,\n\t);\n}\n\ninterface ProtectedAdmission {\n\towner: AgentSession;\n\tcards: CustomMessage[];\n\treconciliations: CustomMessage[];\n}\n\nasync function prepareProtectedAdmission(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<ProtectedAdmission> {\n\t// While the initiating workflow tool is still executing, its assistant call\n\t// may be ahead of SessionManager's async event writer. Wait only in that\n\t// protocol-sensitive phase; at ordinary turn boundaries the hidden steer must\n\t// be queued synchronously so agent-core's next native poll observes it.\n\tif (session.agent.state.pendingToolCalls.size > 0) await session._agentEventQueue;\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tconst prepared = [];\n\tfor (const message of messages) {\n\t\tconst { card, intentEntryId } = await appendDurableDisplayCard(owner, message, delivery);\n\t\tprepared.push({ card, reconciliation: createProtectedReconciliation(message, intentEntryId) });\n\t}\n\tconst cards = prepared.map((entry) => entry.card);\n\tconst reconciliations = prepared.map((entry) => entry.reconciliation);\n\tprotectedMessages(owner).push(\n\t\t...reconciliations.map((message) => ({ message, delivery, phase: \"queued\" as const })),\n\t);\n\treturn { owner, cards, reconciliations };\n}\n\nfunction emitProtectedAdmission(admission: ProtectedAdmission): AgentSession {\n\tlet owner = admission.owner;\n\tfor (const card of admission.cards) {\n\t\towner = resolveWorkflowStageDeliveryTarget(owner);\n\t\temitDurableDisplayCard(owner, card);\n\t}\n\treturn resolveWorkflowStageDeliveryTarget(owner);\n}\n\n/** Persist one visible card and register its hidden model-facing turn. */\nexport async function admitProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<CustomMessage> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\temitProtectedAdmission(admission);\n\treturn admission.reconciliations[0]!;\n}\n\n/** Queue one hidden turn before public listeners can transfer its ownership. */\nexport async function queueProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n\tpriority = false,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\tadmission.owner._queueAgentMessage(admission.reconciliations[0]!, priority ? \"interrupt\" : delivery);\n\temitProtectedAdmission(admission);\n}\n\n/** Queue a whole hidden batch before public listeners can transfer ownership. */\nexport async function queueProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\temitProtectedAdmission(admission);\n}\n\n/** Start or queue an idle protected batch before exposing its display cards. */\nexport async function triggerProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\tconst owner = emitProtectedAdmission(admission);\n\tif (owner.isStreaming || owner._isPreparingRun || owner._queuedMessagesPaused) return;\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tremoveQueuedProtectedReference(owner, reconciliation);\n\t}\n\tconst turn = owner._runAgentPrompt(admission.reconciliations);\n\tvoid turn.catch(() => {});\n}\n\n/** Record that agent-core drained and consumed the hidden reconciliation. */\nexport function markProtectedStreamingCustomMessageConsumed(session: AgentSession, message: CustomMessage): boolean {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (!entry) return false;\n\tentry.phase = \"consumed-unpersisted\";\n\treturn true;\n}\n\nexport function markProtectedStreamingCustomMessagePersistenceFailed(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): void {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (entry?.phase === \"consumed-unpersisted\") entry.phase = \"persistence-failed\";\n}\n\nexport function isProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean {\n\treturn protectedMessages(session).some((entry) => entry.message === message);\n}\n\n/**\n * Persist a consumed hidden reconciliation exactly once. Its visible card was\n * already committed at admission, so a transient failure never re-adds a card\n * or re-injects another provider message.\n */\nexport async function persistProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): Promise<boolean> {\n\tconst pending = protectedMessages(session);\n\tconst index = pending.findIndex((entry) => entry.message === message);\n\tif (index === -1) return false;\n\tconst entry = pending[index];\n\tconst admitted = message as StageAdmittedCustomMessage;\n\tif (entry.phase !== \"consumed-unpersisted\" && entry.phase !== \"persistence-failed\") return true;\n\tawait session.sessionManager.appendCustomMessageEntry(\n\t\tmessage.customType,\n\t\tmessage.content,\n\t\tmessage.display,\n\t\tmessage.details,\n\t\tcustomMessageExcludesContext(message),\n\t\tundefined,\n\t\tadmitted.stageAdmissionKey,\n\t);\n\tpending.splice(index, 1);\n\treturn true;\n}\n\n/** Retry only hidden reconciliation persistence; never queue another alias. */\nexport async function retryConsumedProtectedStreamingCustomMessages(session: AgentSession): Promise<void> {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase !== \"persistence-failed\") continue;\n\t\ttry {\n\t\t\tawait persistProtectedStreamingCustomMessage(session, entry.message);\n\t\t} catch {\n\t\t\t// The visible lifecycle card is already durable. Keep this consumed phase\n\t\t\t// for a later event rather than duplicating either the card or model turn.\n\t\t}\n\t}\n}\n\n/** Flush consumed reconciliations before session state can be discarded. */\nexport async function flushConsumedProtectedStreamingCustomMessages(session: AgentSession): Promise<void> {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase === \"queued\") continue;\n\t\t// Do not swallow the final write failure: callers must keep this session\n\t\t// alive rather than discard the only remaining recovery state.\n\t\tawait persistProtectedStreamingCustomMessage(session, entry.message);\n\t}\n}\n\nfunction removeReference<T>(items: T[], message: T): void {\n\tlet index = items.indexOf(message);\n\twhile (index >= 0) {\n\t\titems.splice(index, 1);\n\t\tindex = items.indexOf(message);\n\t}\n}\n\nfunction removeQueuedProtectedReference(session: AgentSession, message: CustomMessage): void {\n\tconst hold = session._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tremoveReference(hold.steering, message);\n\t\tremoveReference(hold.followUp, message);\n\t}\n\tconst queues = session._drainQueuedAgentMessages();\n\tsession._restoreQueuedAgentMessages({\n\t\tsteering: queues.steering.filter((candidate) => candidate !== message),\n\t\tfollowUp: queues.followUp.filter((candidate) => candidate !== message),\n\t});\n}\n\nfunction isPausedHeldProtectedReference(session: AgentSession, message: CustomMessage): boolean {\n\tconst hold = session._activeInterruptQueueHold;\n\treturn (\n\t\tsession._queuedMessagesPaused &&\n\t\thold !== undefined &&\n\t\t(hold.steering.includes(message) || hold.followUp.includes(message))\n\t);\n}\n\n/**\n * Persist only reconciliation input already sealed inside an accepted pause\n * hold. Other queued input can still race an active protocol turn and must keep\n * the historical fail-closed disposal behavior.\n */\nexport async function prepareProtectedStreamingCustomMessagesForDisposal(session: AgentSession): Promise<void> {\n\tconst pending = protectedMessages(session);\n\tconst queued = pending.filter((entry) => entry.phase === \"queued\");\n\tif (queued.some((entry) => !isPausedHeldProtectedReference(session, entry.message))) {\n\t\tthrow new Error(\"Cannot dispose a session with a queued protected reconciliation\");\n\t}\n\tfor (const entry of queued) {\n\t\tconst admitted = entry.message as StageAdmittedCustomMessage;\n\t\tawait session.sessionManager.appendCustomMessageEntry(\n\t\t\tentry.message.customType,\n\t\t\tentry.message.content,\n\t\t\tentry.message.display,\n\t\t\tentry.message.details,\n\t\t\tcustomMessageExcludesContext(entry.message),\n\t\t\tundefined,\n\t\t\tadmitted.stageAdmissionKey,\n\t\t);\n\t\tremoveQueuedProtectedReference(session, entry.message);\n\t\tconst index = pending.indexOf(entry);\n\t\tif (index >= 0) pending.splice(index, 1);\n\t}\n\tawait flushConsumedProtectedStreamingCustomMessages(session);\n}\n\n/** Restore only protected references actually removed from native queues/hold. */\nexport function restoreProtectedStreamingCustomMessages(session: AgentSession, removed: DrainedAgentQueues): void {\n\tconst removedReferences = new Set([...removed.steering, ...removed.followUp]);\n\tfor (const entry of protectedMessages(session)) {\n\t\tif (entry.phase === \"queued\" && removedReferences.has(entry.message)) {\n\t\t\tsession._queueAgentMessage(entry.message, entry.delivery);\n\t\t}\n\t}\n}\n\n/** Move protection only for message references that transfer with native queues. */\nexport function transferProtectedStreamingCustomMessages(\n\tsource: AgentSession,\n\ttarget: AgentSession,\n\ttransferred: DrainedAgentQueues,\n): void {\n\tconst transferredReferences = new Set([...transferred.steering, ...transferred.followUp]);\n\tconst retained: ProtectedStreamingCustomMessage[] = [];\n\tconst moved: ProtectedStreamingCustomMessage[] = [];\n\tfor (const entry of protectedMessages(source)) {\n\t\tif (entry.phase === \"queued\" && transferredReferences.has(entry.message)) moved.push(entry);\n\t\telse retained.push(entry);\n\t}\n\tsource._protectedStreamingCustomMessages = retained;\n\tprotectedMessages(target).unshift(...moved);\n}\n"]}
1
+ {"version":3,"file":"agent-session-persistent-custom-messages.js","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAOxE,MAAM,CAAC,MAAM,oCAAoC,GAAG,2CAA2C,CAAC;AAchG,SAAS,iBAAiB,CAAC,OAAqB;IAC/C,OAAO,CAAC,iCAAiC,KAAK,EAAE,CAAC;IACjD,OAAO,OAAO,CAAC,iCAAiC,CAAC;AAClD,CAAC;AAED,KAAK,UAAU,wBAAwB,CACtC,OAAqB,EACrB,OAAsB,EACtB,QAA2B;IAE3B,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAyD,CAAC;IAC7G,MAAM,QAAQ,GAAG,OAAqC,CAAC;IACvD,6EAA6E;IAC7E,oEAAoE;IACpE,MAAM,OAAO,GACZ,QAAQ,CAAC,iBAAiB,KAAK,SAAS;QACvC,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,OAAO,CAAC,cAAc;aACrB,SAAS,EAAE;aACX,IAAI,CACJ,CAAC,KAAK,EAAE,EAAE,CACT,KAAK,CAAC,IAAI,KAAK,gBAAgB;YAC/B,KAAK,CAAC,iBAAiB,KAAK,QAAQ,CAAC,iBAAiB;YACtD,iBAAiB,CAAC,KAAK,CAAC,uBAAuB,CAAC,KAAK,SAAS,CAC/D,CAAC;IACN,0EAA0E;IAC1E,gCAAgC;IAChC,MAAM,aAAa,GAClB,OAAO,EAAE,EAAE;QACX,CAAC,MAAM,OA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B,WAA+B;IAE/B,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,QAAQ,EAAE,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC1F,MAAM,QAAQ,GAAsC,EAAE,CAAC;IACvD,MAAM,KAAK,GAAsC,EAAE,CAAC;IACpD,KAAK,MAAM,KAAK,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/C,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;YACvF,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IACD,MAAM,CAAC,iCAAiC,GAAG,QAAQ,CAAC;IACpD,iBAAiB,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { DrainedAgentQueues } from \"./agent-session-types.js\";\nimport { customMessageExcludesContext } from \"./agent-session-types.js\";\nimport type { PendingRecoveryDelivery } from \"./extensions/index.js\";\nimport type { CustomMessage, StageAdmittedCustomMessage } from \"./messages.ts\";\n\ntype ProtectedDelivery = \"steer\" | \"followUp\";\ntype ProtectedPhase = \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\nexport const PROTECTED_RECONCILIATION_CUSTOM_TYPE = \"atomic:protected-streaming-reconciliation\";\n\ninterface ProtectedReconciliationDetails {\n\tprotectedReconciliationOf: string;\n\t/** Set when resume recovery declined to replay the card to the model. */\n\trecovery?: \"dropped\";\n}\n\nexport interface ProtectedStreamingCustomMessage {\n\tmessage: CustomMessage;\n\tdelivery: ProtectedDelivery;\n\tphase: ProtectedPhase;\n}\n\nfunction protectedMessages(session: AgentSession): ProtectedStreamingCustomMessage[] {\n\tsession._protectedStreamingCustomMessages ??= [];\n\treturn session._protectedStreamingCustomMessages;\n}\n\nasync function appendDurableDisplayCard(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<{ readonly card: CustomMessage & { excludeFromContext: true }; readonly intentEntryId: string }> {\n\tconst card = { ...message, excludeFromContext: true } satisfies CustomMessage & { excludeFromContext: true };\n\tconst admitted = message as StageAdmittedCustomMessage;\n\t// A retry after a failed flush must complete the already-appended occurrence\n\t// rather than append a second visible card for the same stable key.\n\tconst partial =\n\t\tadmitted.stageAdmissionKey === undefined\n\t\t\t? undefined\n\t\t\t: session.sessionManager\n\t\t\t\t\t.getBranch()\n\t\t\t\t\t.find(\n\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\tentry.type === \"custom_message\" &&\n\t\t\t\t\t\t\tentry.stageAdmissionKey === admitted.stageAdmissionKey &&\n\t\t\t\t\t\t\tprotectedDelivery(entry.protectedReconciliation) !== undefined,\n\t\t\t\t\t);\n\t// The card and recovery marker share one append, so either both survive a\n\t// process exit or neither does.\n\tconst intentEntryId =\n\t\tpartial?.id ??\n\t\t(await session.sessionManager.appendCustomMessageEntry(\n\t\t\tcard.customType,\n\t\t\tcard.content,\n\t\t\tcard.display,\n\t\t\tcard.details,\n\t\t\ttrue,\n\t\t\t{ delivery },\n\t\t\tadmitted.stageAdmissionKey,\n\t\t));\n\tsession._entryIdsByMessage.set(card, intentEntryId);\n\tsession._refreshFinalizedContext();\n\treturn { card, intentEntryId };\n}\n\nfunction emitDurableDisplayCard(session: AgentSession, card: CustomMessage): void {\n\t// The card is already live and file-backed, and its protected reconciliation\n\t// is registered. Public listeners remain fallible, but their errors cannot\n\t// revoke admission or make the producer retry this committed occurrence.\n\ttry {\n\t\tsession._emit({ type: \"message_start\", message: card });\n\t} catch {}\n\ttry {\n\t\tsession._emit({ type: \"message_end\", message: card });\n\t} catch {}\n}\n\nfunction createProtectedReconciliation(message: CustomMessage, intentEntryId: string): CustomMessage {\n\treturn {\n\t\trole: \"custom\",\n\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tcontent: message.content,\n\t\tdisplay: false,\n\t\tdetails: { protectedReconciliationOf: intentEntryId } satisfies ProtectedReconciliationDetails,\n\t\ttimestamp: message.timestamp,\n\t};\n}\n\nfunction completedReconciliationIntent(details: unknown): string | undefined {\n\tif (details === null || typeof details !== \"object\") return undefined;\n\tconst intent = (details as { protectedReconciliationOf?: unknown }).protectedReconciliationOf;\n\treturn typeof intent === \"string\" ? intent : undefined;\n}\n\nfunction protectedDelivery(marker: unknown): ProtectedDelivery | undefined {\n\tif (marker === null || typeof marker !== \"object\") return undefined;\n\tconst delivery = (marker as { delivery?: unknown }).delivery;\n\treturn delivery === \"steer\" || delivery === \"followUp\" ? delivery : undefined;\n}\n\n/** Durable card intents with neither a persisted hidden completion nor a scheduled one. */\nexport function pendingProtectedStreamingCustomMessages(session: AgentSession): PendingRecoveryDelivery[] {\n\tconst branch = session.sessionManager.getBranch();\n\tconst completed = new Set(\n\t\tbranch.flatMap((entry) =>\n\t\t\tentry.type === \"custom_message\" && entry.customType === PROTECTED_RECONCILIATION_CUSTOM_TYPE\n\t\t\t\t? [completedReconciliationIntent(entry.details)].filter((intent): intent is string => intent !== undefined)\n\t\t\t\t: [],\n\t\t),\n\t);\n\tconst scheduled = new Set(\n\t\tprotectedMessages(session).flatMap((entry) => {\n\t\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\t\treturn intent === undefined ? [] : [intent];\n\t\t}),\n\t);\n\tconst pending: PendingRecoveryDelivery[] = [];\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom_message\") continue;\n\t\tconst delivery = protectedDelivery(entry.protectedReconciliation);\n\t\tif (delivery === undefined || completed.has(entry.id) || scheduled.has(entry.id)) continue;\n\t\tpending.push({\n\t\t\tentryId: entry.id,\n\t\t\tcustomType: entry.customType,\n\t\t\tcontent: entry.content,\n\t\t\tdetails: entry.details,\n\t\t\ttimestamp: entry.timestamp,\n\t\t\t...(entry.stageAdmissionKey === undefined ? {} : { stageAdmissionKey: entry.stageAdmissionKey }),\n\t\t\tdelivery,\n\t\t});\n\t}\n\treturn pending;\n}\n\n/** Requeue the hidden model-facing turn of each recovered durable card. */\nexport function recoverProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tpending: readonly PendingRecoveryDelivery[],\n): number {\n\tfor (const entry of pending) {\n\t\tconst parsedTimestamp = Date.parse(entry.timestamp);\n\t\tconst reconciliation: CustomMessage = {\n\t\t\trole: \"custom\",\n\t\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\t\tcontent: entry.content,\n\t\t\tdisplay: false,\n\t\t\tdetails: { protectedReconciliationOf: entry.entryId } satisfies ProtectedReconciliationDetails,\n\t\t\ttimestamp: Number.isFinite(parsedTimestamp) ? parsedTimestamp : Date.now(),\n\t\t};\n\t\tprotectedMessages(session).push({ message: reconciliation, delivery: entry.delivery, phase: \"queued\" });\n\t\tsession._queueAgentMessage(reconciliation, entry.delivery);\n\t}\n\treturn pending.length;\n}\n\n/** Close a recovered card without a model turn, so later resumes never offer it again. */\nexport async function dismissProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tpending: PendingRecoveryDelivery,\n): Promise<void> {\n\tawait session.sessionManager.appendCustomMessageEntry(\n\t\tPROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tpending.content,\n\t\tfalse,\n\t\t{ protectedReconciliationOf: pending.entryId, recovery: \"dropped\" } satisfies ProtectedReconciliationDetails,\n\t\ttrue,\n\t);\n}\n\ninterface ProtectedAdmission {\n\towner: AgentSession;\n\tcards: CustomMessage[];\n\treconciliations: CustomMessage[];\n}\n\nasync function prepareProtectedAdmission(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<ProtectedAdmission> {\n\t// While the initiating workflow tool is still executing, its assistant call\n\t// may be ahead of SessionManager's async event writer. Wait only in that\n\t// protocol-sensitive phase; at ordinary turn boundaries the hidden steer must\n\t// be queued synchronously so agent-core's next native poll observes it.\n\tif (session.agent.state.pendingToolCalls.size > 0) await session._agentEventQueue;\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tconst prepared = [];\n\tfor (const message of messages) {\n\t\tconst { card, intentEntryId } = await appendDurableDisplayCard(owner, message, delivery);\n\t\tprepared.push({ card, reconciliation: createProtectedReconciliation(message, intentEntryId) });\n\t}\n\tconst cards = prepared.map((entry) => entry.card);\n\tconst reconciliations = prepared.map((entry) => entry.reconciliation);\n\tprotectedMessages(owner).push(\n\t\t...reconciliations.map((message) => ({ message, delivery, phase: \"queued\" as const })),\n\t);\n\treturn { owner, cards, reconciliations };\n}\n\nfunction emitProtectedAdmission(admission: ProtectedAdmission): AgentSession {\n\tlet owner = admission.owner;\n\tfor (const card of admission.cards) {\n\t\towner = resolveWorkflowStageDeliveryTarget(owner);\n\t\temitDurableDisplayCard(owner, card);\n\t}\n\treturn resolveWorkflowStageDeliveryTarget(owner);\n}\n\n/** Persist one visible card and register its hidden model-facing turn. */\nexport async function admitProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<CustomMessage> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\temitProtectedAdmission(admission);\n\treturn admission.reconciliations[0]!;\n}\n\n/** Queue one hidden turn before public listeners can transfer its ownership. */\nexport async function queueProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n\tpriority = false,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\tadmission.owner._queueAgentMessage(admission.reconciliations[0]!, priority ? \"interrupt\" : delivery);\n\temitProtectedAdmission(admission);\n}\n\n/** Queue a whole hidden batch before public listeners can transfer ownership. */\nexport async function queueProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\temitProtectedAdmission(admission);\n}\n\n/** Start or queue an idle protected batch before exposing its display cards. */\nexport async function triggerProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\tconst owner = emitProtectedAdmission(admission);\n\tif (owner.isStreaming || owner._isPreparingRun || owner._queuedMessagesPaused) return;\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tremoveQueuedProtectedReference(owner, reconciliation);\n\t}\n\tconst turn = owner._runAgentPrompt(admission.reconciliations);\n\tvoid turn.catch(() => {});\n}\n\n/** Record that agent-core drained and consumed the hidden reconciliation. */\nexport function markProtectedStreamingCustomMessageConsumed(session: AgentSession, message: CustomMessage): boolean {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (!entry) return false;\n\tentry.phase = \"consumed-unpersisted\";\n\treturn true;\n}\n\nexport function markProtectedStreamingCustomMessagePersistenceFailed(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): void {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (entry?.phase === \"consumed-unpersisted\") entry.phase = \"persistence-failed\";\n}\n\n/**\n * Whether a durable card of this custom type is admitted but its hidden turn is still queued, so the model has not\n * read it yet. Clearing the queue restores protected turns, so a queued entry ends only when it is consumed.\n */\nexport function hasUnreadProtectedCustomMessage(session: AgentSession, customType: string): boolean {\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\treturn protectedMessages(owner).some((entry) => {\n\t\tif (entry.phase !== \"queued\") return false;\n\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\tif (intent === undefined) return false;\n\t\tconst card = owner.sessionManager.getEntry(intent);\n\t\treturn card?.type === \"custom_message\" && card.customType === customType;\n\t});\n}\n\nexport function isProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean {\n\treturn protectedMessages(session).some((entry) => entry.message === message);\n}\n\n/**\n * Persist a consumed hidden reconciliation exactly once. Its visible card was\n * already committed at admission, so a transient failure never re-adds a card\n * or re-injects another provider message.\n */\nexport async function persistProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): Promise<boolean> {\n\tconst pending = protectedMessages(session);\n\tconst index = pending.findIndex((entry) => entry.message === message);\n\tif (index === -1) return false;\n\tconst entry = pending[index];\n\tconst admitted = message as StageAdmittedCustomMessage;\n\tif (entry.phase !== \"consumed-unpersisted\" && entry.phase !== \"persistence-failed\") return true;\n\tawait session.sessionManager.appendCustomMessageEntry(\n\t\tmessage.customType,\n\t\tmessage.content,\n\t\tmessage.display,\n\t\tmessage.details,\n\t\tcustomMessageExcludesContext(message),\n\t\tundefined,\n\t\tadmitted.stageAdmissionKey,\n\t);\n\tpending.splice(index, 1);\n\treturn true;\n}\n\n/** Retry only hidden reconciliation persistence; never queue another alias. */\nexport async function retryConsumedProtectedStreamingCustomMessages(session: AgentSession): Promise<void> {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase !== \"persistence-failed\") continue;\n\t\ttry {\n\t\t\tawait persistProtectedStreamingCustomMessage(session, entry.message);\n\t\t} catch {\n\t\t\t// The visible lifecycle card is already durable. Keep this consumed phase\n\t\t\t// for a later event rather than duplicating either the card or model turn.\n\t\t}\n\t}\n}\n\n/** Flush consumed reconciliations before session state can be discarded. */\nexport async function flushConsumedProtectedStreamingCustomMessages(session: AgentSession): Promise<void> {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase === \"queued\") continue;\n\t\t// Do not swallow the final write failure: callers must keep this session\n\t\t// alive rather than discard the only remaining recovery state.\n\t\tawait persistProtectedStreamingCustomMessage(session, entry.message);\n\t}\n}\n\nfunction removeReference<T>(items: T[], message: T): void {\n\tlet index = items.indexOf(message);\n\twhile (index >= 0) {\n\t\titems.splice(index, 1);\n\t\tindex = items.indexOf(message);\n\t}\n}\n\nfunction removeQueuedProtectedReference(session: AgentSession, message: CustomMessage): void {\n\tconst hold = session._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tremoveReference(hold.steering, message);\n\t\tremoveReference(hold.followUp, message);\n\t}\n\tconst queues = session._drainQueuedAgentMessages();\n\tsession._restoreQueuedAgentMessages({\n\t\tsteering: queues.steering.filter((candidate) => candidate !== message),\n\t\tfollowUp: queues.followUp.filter((candidate) => candidate !== message),\n\t});\n}\n\nfunction isPausedHeldProtectedReference(session: AgentSession, message: CustomMessage): boolean {\n\tconst hold = session._activeInterruptQueueHold;\n\treturn (\n\t\tsession._queuedMessagesPaused &&\n\t\thold !== undefined &&\n\t\t(hold.steering.includes(message) || hold.followUp.includes(message))\n\t);\n}\n\n/**\n * Persist only reconciliation input already sealed inside an accepted pause\n * hold. Other queued input can still race an active protocol turn and must keep\n * the historical fail-closed disposal behavior.\n */\nexport async function prepareProtectedStreamingCustomMessagesForDisposal(session: AgentSession): Promise<void> {\n\tconst pending = protectedMessages(session);\n\tconst queued = pending.filter((entry) => entry.phase === \"queued\");\n\tif (queued.some((entry) => !isPausedHeldProtectedReference(session, entry.message))) {\n\t\tthrow new Error(\"Cannot dispose a session with a queued protected reconciliation\");\n\t}\n\tfor (const entry of queued) {\n\t\tconst admitted = entry.message as StageAdmittedCustomMessage;\n\t\tawait session.sessionManager.appendCustomMessageEntry(\n\t\t\tentry.message.customType,\n\t\t\tentry.message.content,\n\t\t\tentry.message.display,\n\t\t\tentry.message.details,\n\t\t\tcustomMessageExcludesContext(entry.message),\n\t\t\tundefined,\n\t\t\tadmitted.stageAdmissionKey,\n\t\t);\n\t\tremoveQueuedProtectedReference(session, entry.message);\n\t\tconst index = pending.indexOf(entry);\n\t\tif (index >= 0) pending.splice(index, 1);\n\t}\n\tawait flushConsumedProtectedStreamingCustomMessages(session);\n}\n\n/** Restore only protected references actually removed from native queues/hold. */\nexport function restoreProtectedStreamingCustomMessages(session: AgentSession, removed: DrainedAgentQueues): void {\n\tconst removedReferences = new Set([...removed.steering, ...removed.followUp]);\n\tfor (const entry of protectedMessages(session)) {\n\t\tif (entry.phase === \"queued\" && removedReferences.has(entry.message)) {\n\t\t\tsession._queueAgentMessage(entry.message, entry.delivery);\n\t\t}\n\t}\n}\n\n/** Move protection only for message references that transfer with native queues. */\nexport function transferProtectedStreamingCustomMessages(\n\tsource: AgentSession,\n\ttarget: AgentSession,\n\ttransferred: DrainedAgentQueues,\n): void {\n\tconst transferredReferences = new Set([...transferred.steering, ...transferred.followUp]);\n\tconst retained: ProtectedStreamingCustomMessage[] = [];\n\tconst moved: ProtectedStreamingCustomMessage[] = [];\n\tfor (const entry of protectedMessages(source)) {\n\t\tif (entry.phase === \"queued\" && transferredReferences.has(entry.message)) moved.push(entry);\n\t\telse retained.push(entry);\n\t}\n\tsource._protectedStreamingCustomMessages = retained;\n\tprotectedMessages(target).unshift(...moved);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-tasks.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-tasks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAG9F,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAYzD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAOzE,oGAAoG;AACpG,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE,iBAAiB,CAAC,GAAG,OAAO,CAE9F;AAUD,wBAAgB,uBAAuB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AY,GAAG,OAAO,CAAC,IAAI,CAAC,CAElE;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAEpD;AAED,eAAO,MAAM,uBAAuB;;;;;;CAMnC,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { hasUnreadProtectedCustomMessage } from "./agent-session-persistent-custom-messages.js";
2
3
  import { getExtensionRuntimeEventBus } from "./extensions/loader-core.js";
3
4
  import { sessionGenerationClosing } from "./session-lifecycle-work.js";
4
5
  import { AgentTaskHost } from "./tasks/agent-adapter.js";
@@ -6,6 +7,7 @@ import { childTaskCompletionRoute } from "./tasks/child-command-owner.js";
6
7
  import { COMMAND_DETAIL_TAIL_BYTES, taskOutputText } from "./tasks/command-output.js";
7
8
  import { formatTaskCompletion, TASK_COMPLETION_MESSAGE_TYPE, TaskCompletionOutbox, taskCompletionNotice, } from "./tasks/completion.js";
8
9
  import { flushTaskCompletionMessages } from "./tasks/completion-ordering.js";
10
+ import { TASK_HEARTBEAT_MESSAGE_TYPE } from "./tasks/heartbeat.js";
9
11
  import { bindOwnerTaskStore, OwnerTaskStore } from "./tasks/owner-store.js";
10
12
  import { taskOwnTranscriptEntries, taskTranscriptSource } from "./tasks/supervisor.js";
11
13
  import { WorkflowStageAdmissionBoundary } from "./workflow-stage-admission.js";
@@ -119,8 +121,26 @@ export function getAgentTaskHost() {
119
121
  }
120
122
  });
121
123
  this._taskCompletionOutbox = outbox;
124
+ const heartbeat = {
125
+ defaultIntervalMs: () => this.settingsManager.getTaskHeartbeatMs(),
126
+ hasUnreadHeartbeat: () => hasUnreadProtectedCustomMessage(this, TASK_HEARTBEAT_MESSAGE_TYPE),
127
+ deliver: async (message) => {
128
+ if (this._disposed || !admission.isOpen())
129
+ throw new Error("Task owner is closed");
130
+ // The workflow heartbeat delivery: a visible card plus a steer that waits for the next safe boundary,
131
+ // never interrupting a response in progress.
132
+ const deliver = () => this.sendCustomMessage(message, { triggerTurn: true, deliverAs: "steer", persistWhenStreaming: true });
133
+ if (stageAdmission)
134
+ await deliver();
135
+ else
136
+ await admission.admit(undefined, deliver, () => {
137
+ throw new Error("Task owner is closed");
138
+ }).completion;
139
+ },
140
+ };
122
141
  const binding = {
123
142
  resourceAdmission: this._resourceAdmission,
143
+ heartbeat,
124
144
  authorizeLaunch: () => {
125
145
  if (this._disposed || sessionGenerationClosing.has(this) || !admission.isOpen())
126
146
  throw new Error("Task owner is closed");
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-tasks.js","sourceRoot":"","sources":["../../src/core/agent-session-tasks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAiC,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AACzG,OAAO,EAAE,yBAAyB,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AACtF,OAAO,EACN,oBAAoB,EACpB,4BAA4B,EAC5B,oBAAoB,EACpB,oBAAoB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEvF,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAE/E,6EAA6E;AAC7E,6EAA6E;AAC7E,MAAM,sBAAsB,GAAG,IAAI,OAAO,EAAkB,CAAC;AAE7D,oGAAoG;AACpG,MAAM,UAAU,sBAAsB,CAAC,OAA8C;IACpF,OAAO,CAAC,OAAO,CAAC,eAAe,EAA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AAED,MAAM,UAAU,WAAW;IAC1B,IAAI,CAAC,cAAc,EAAE,WAAW,EAAE,CAAC;AACpC,CAAC;AAED,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,gBAAgB;IAChB,oBAAoB;IACpB,iBAAiB;IACjB,UAAU;IACV,WAAW;CACX,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { getExtensionRuntimeEventBus } from \"./extensions/loader-core.js\";\nimport { sessionGenerationClosing } from \"./session-lifecycle-work.ts\";\nimport { AgentTaskHost } from \"./tasks/agent-adapter.js\";\nimport { type ChildTaskCompletionRoute, childTaskCompletionRoute } from \"./tasks/child-command-owner.js\";\nimport { COMMAND_DETAIL_TAIL_BYTES, taskOutputText } from \"./tasks/command-output.js\";\nimport {\n\tformatTaskCompletion,\n\tTASK_COMPLETION_MESSAGE_TYPE,\n\tTaskCompletionOutbox,\n\ttaskCompletionNotice,\n} from \"./tasks/completion.js\";\nimport { flushTaskCompletionMessages } from \"./tasks/completion-ordering.js\";\nimport { bindOwnerTaskStore, OwnerTaskStore } from \"./tasks/owner-store.js\";\nimport { taskOwnTranscriptEntries, taskTranscriptSource } from \"./tasks/supervisor.js\";\nimport type { SupervisedCommandOwner } from \"./tools/bash-pty-native.js\";\nimport { WorkflowStageAdmissionBoundary } from \"./workflow-stage-admission.ts\";\n\n// Native owners identify live generations, never borrowed persisted storage.\n// Explicit workflow-stage owners remain borrowed across session replacement.\nconst replacementOwnerScopes = new WeakMap<object, string>();\n\n/** An admitted in-process subagent child; top-level sessions may carry a policy without `depth`. */\nexport function isSubagentChildSession(session: Pick<AgentSession, \"_subagentPolicy\">): boolean {\n\treturn (session._subagentPolicy?.depth ?? 0) >= 1;\n}\n\n/**\n * A child launched from a workflow stage inherits the stage's admission boundary for\n * message delivery, but must never bind or rebind the stage's own task owner.\n */\nfunction stageTaskAdmission(session: AgentSession) {\n\treturn isSubagentChildSession(session) ? undefined : session._workflowStageAdmission;\n}\n\nexport function replaceSessionTaskOwner(session: AgentSession): void {\n\tif (stageTaskAdmission(session)) return;\n\treplacementOwnerScopes.set(session, randomUUID());\n\tsession._agentTaskHost = undefined;\n\tsession._taskAdmission = undefined;\n\tsession._taskCompletionOutbox = undefined;\n}\n\nexport function getAgentTaskHost(this: AgentSession): AgentTaskHost {\n\tif (this._disposed || sessionGenerationClosing.has(this)) throw new Error(\"Task owner is closed\");\n\tif (this._agentTaskHost) return this._agentTaskHost;\n\tconst stageAdmission = stageTaskAdmission(this);\n\tconst admission = stageAdmission ?? WorkflowStageAdmissionBoundary.restore(this.sessionManager.getEntries());\n\tthis._taskAdmission = admission;\n\tconst outbox = new TaskCompletionOutbox(\n\t\tthis.sessionManager,\n\t\t() => !this._disposed && admission.isOpen(),\n\t\tasync (envelope, restored) => {\n\t\t\t// Settlement can precede the UI projection's next drain. Read the owner\n\t\t\t// snapshot, not the display store, when attaching completion context.\n\t\t\tconst host = this._agentTaskHost;\n\t\t\tconst watched = host?.watchOwnerTasks();\n\t\t\tconst task = watched?.ok\n\t\t\t\t? watched.value.snapshot.tasks.find(\n\t\t\t\t\t\t(item) => item.ref.taskId === envelope.taskId && item.ref.ownerId === envelope.ownerId,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\tif (watched?.ok) watched.value.dispose();\n\t\t\t// Foreground shell results already return through their tool call. Do not\n\t\t\t// create a second model turn or background card for that same execution.\n\t\t\tif (task?.kind === \"command\" && !task.wasBackground) return;\n\t\t\tconst lease = task ? host?.resolveTask(envelope.taskId) : undefined;\n\t\t\tconst source = lease?.ok ? taskTranscriptSource(lease.value) : undefined;\n\t\t\tconst ownEntries = lease?.ok ? taskOwnTranscriptEntries(lease.value) : undefined;\n\t\t\tconst response = ownEntries\n\t\t\t\t? ownEntries\n\t\t\t\t\t\t.slice()\n\t\t\t\t\t\t.reverse()\n\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t\t\t\t\tentry.message.role === \"assistant\" &&\n\t\t\t\t\t\t\t\tentry.message.content.some((block) => block.type === \"text\" && block.text.trim()),\n\t\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\tlet output =\n\t\t\t\tresponse?.type === \"message\" && response.message.role === \"assistant\"\n\t\t\t\t\t? response.message.content\n\t\t\t\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t\t\t\t.map((block) => block.text)\n\t\t\t\t\t\t\t.join(\"\\n\")\n\t\t\t\t\t: undefined;\n\t\t\tif (task?.kind === \"command\" && lease?.ok && host) {\n\t\t\t\ttry {\n\t\t\t\t\tconst bytes = BigInt(task.output.byteCount);\n\t\t\t\t\tconst start = bytes > BigInt(COMMAND_DETAIL_TAIL_BYTES) ? bytes - BigInt(COMMAND_DETAIL_TAIL_BYTES) : 0n;\n\t\t\t\t\tconst page = await host.ownerBinding.supervisor.readTaskOutput(lease.value, {\n\t\t\t\t\t\tstart: String(start),\n\t\t\t\t\t\tmaximumBytes: COMMAND_DETAIL_TAIL_BYTES,\n\t\t\t\t\t});\n\t\t\t\t\toutput = page.ok\n\t\t\t\t\t\t? `${start > 0n ? \"[Earlier output omitted]\\n\" : \"\"}${taskOutputText(page.value)}`\n\t\t\t\t\t\t: \"Output unavailable\";\n\t\t\t\t} catch {\n\t\t\t\t\t// Missing retained output must not suppress a terminal notification.\n\t\t\t\t\toutput = \"Output unavailable\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst message = {\n\t\t\t\tcustomType: TASK_COMPLETION_MESSAGE_TYPE,\n\t\t\t\tcontent: formatTaskCompletion(envelope, task, output),\n\t\t\t\tdetails: { ...envelope, notification: taskCompletionNotice(envelope, task, output) },\n\t\t\t\tdisplay: true as const,\n\t\t\t};\n\t\t\tconst childRoute =\n\t\t\t\thost && task?.kind === \"command\" ? childTaskCompletionRoute(host, envelope.taskId) : undefined;\n\t\t\tif (childRoute) {\n\t\t\t\ttry {\n\t\t\t\t\tawait childRoute.deliver(message);\n\t\t\t\t\treturn;\n\t\t\t\t} catch {\n\t\t\t\t\t// The launching child ended before delivery; the owning parent receives the notice.\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst completionSource = source?.ok ? source.value.session.completionSource : undefined;\n\t\t\tif (completionSource) {\n\t\t\t\tawait flushTaskCompletionMessages(\n\t\t\t\t\tgetExtensionRuntimeEventBus(this._resourceLoader.getExtensions().runtime),\n\t\t\t\t\tcompletionSource,\n\t\t\t\t\tenvelope.completionId,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst deliver = () =>\n\t\t\t\tthis.sendCustomMessage(\n\t\t\t\t\tmessage,\n\t\t\t\t\trestored\n\t\t\t\t\t\t? { triggerTurn: false, stageAdmissionKey: envelope.completionId }\n\t\t\t\t\t\t: { triggerTurn: true, persistWhenStreaming: true, stageAdmissionKey: envelope.completionId },\n\t\t\t\t);\n\t\t\tif (stageAdmission) await deliver();\n\t\t\telse {\n\t\t\t\tawait admission.admit(envelope.completionId, deliver, () => {\n\t\t\t\t\tthrow new Error(\"Task owner is closed\");\n\t\t\t\t}).completion;\n\t\t\t}\n\t\t},\n\t);\n\tthis._taskCompletionOutbox = outbox;\n\tconst binding = {\n\t\tresourceAdmission: this._resourceAdmission,\n\t\tauthorizeLaunch: () => {\n\t\t\tif (this._disposed || sessionGenerationClosing.has(this) || !admission.isOpen())\n\t\t\t\tthrow new Error(\"Task owner is closed\");\n\t\t\tif (isSubagentChildSession(this)) throw new Error(\"Subagent delegation is not available inside a subagent\");\n\t\t},\n\t\tonTaskSettled: (\n\t\t\t...[ref, receipt]: Parameters<NonNullable<import(\"./tasks/supervisor.js\").TrustedTaskHost[\"onTaskSettled\"]>>\n\t\t) => {\n\t\t\t// Save the task's kind with the intent: a notice replayed after a restart has no task record to read it from.\n\t\t\tconst watched = this._agentTaskHost?.watchOwnerTasks();\n\t\t\tconst kind = watched?.ok\n\t\t\t\t? watched.value.snapshot.tasks.find((task) => task.ref.taskId === receipt.taskId)?.kind\n\t\t\t\t: undefined;\n\t\t\tif (watched?.ok) watched.value.dispose();\n\t\t\toutbox.record(ref.ownerId, receipt, kind);\n\t\t\tvoid outbox.flush();\n\t\t},\n\t};\n\tif (!stageAdmission && !replacementOwnerScopes.has(this)) replacementOwnerScopes.set(this, randomUUID());\n\tthis._agentTaskHost = stageAdmission\n\t\t? stageAdmission.bindAgentTaskHost(binding)\n\t\t: new AgentTaskHost({\n\t\t\t\t...binding,\n\t\t\t\tscope: {\n\t\t\t\t\tkind: \"session\",\n\t\t\t\t\tsessionId: replacementOwnerScopes.get(this)!,\n\t\t\t\t},\n\t\t\t});\n\tconst { supervisor, owner } = this._agentTaskHost.ownerBinding;\n\tconst store = new OwnerTaskStore(supervisor, owner);\n\tconst connected = store.connect();\n\tif (!connected.ok) throw new Error(connected.error.message);\n\tbindOwnerTaskStore(this, store);\n\treturn this._agentTaskHost;\n}\n\n/**\n * Shell task owner for this session. A subagent child runs shells in its parent's owner,\n * so they appear in the parent's `/tasks` and outlive the child.\n */\nexport function _getCommandTaskOwner(this: AgentSession): SupervisedCommandOwner | undefined {\n\tif (!isSubagentChildSession(this)) return this.getAgentTaskHost().ownerBinding;\n\tif (!this._parentCommandTaskOwner || this._disposed) return undefined;\n\tconst route: ChildTaskCompletionRoute = {\n\t\tisOpen: () => !this._disposed && this._subagentPolicy?.messageAdmission?.isOpen() === true,\n\t\tdeliver: async (message) => {\n\t\t\tconst admission = this._subagentPolicy?.messageAdmission;\n\t\t\tif (!admission) throw new Error(\"Subagent execution cannot accept messages\");\n\t\t\tawait admission.run(() => this.sendCustomMessage(message, { triggerTurn: true, persistWhenStreaming: true }));\n\t\t},\n\t};\n\treturn this._parentCommandTaskOwner.bind(this.sessionManager.getSessionId(), route, this._childTaskWaits);\n}\n\nexport async function closeSessionTasks(this: AgentSession): Promise<void> {\n\t// Replacement stage sessions share generation lifetime; disposal is not stage closure.\n\tif (stageTaskAdmission(this)) return;\n\tthis._taskAdmission?.seal();\n\tconst closed = await this._agentTaskHost?.close(\"session-close\");\n\tif (closed && !closed.ok) throw new Error(`${closed.error.code}: ${closed.error.message}`);\n}\n\n/** Workflow controller only: main-chat message pause does not stop owned tasks. */\nexport async function pauseTasks(this: AgentSession): Promise<void> {\n\tawait this.getAgentTaskHost().pauseTasks();\n}\n\nexport function resumeTasks(this: AgentSession): void {\n\tthis._agentTaskHost?.resumeTasks();\n}\n\nexport const agentSessionTaskMethods = {\n\tgetAgentTaskHost,\n\t_getCommandTaskOwner,\n\tcloseSessionTasks,\n\tpauseTasks,\n\tresumeTasks,\n};\n"]}
1
+ {"version":3,"file":"agent-session-tasks.js","sourceRoot":"","sources":["../../src/core/agent-session-tasks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC;AAChG,OAAO,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAiC,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AACzG,OAAO,EAAE,yBAAyB,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AACtF,OAAO,EACN,oBAAoB,EACpB,4BAA4B,EAC5B,oBAAoB,EACpB,oBAAoB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EAAE,2BAA2B,EAA8B,MAAM,sBAAsB,CAAC;AAC/F,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC5E,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEvF,OAAO,EAAE,8BAA8B,EAAE,MAAM,+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gentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { hasUnreadProtectedCustomMessage } from \"./agent-session-persistent-custom-messages.ts\";\nimport { getExtensionRuntimeEventBus } from \"./extensions/loader-core.js\";\nimport { sessionGenerationClosing } from \"./session-lifecycle-work.ts\";\nimport { AgentTaskHost } from \"./tasks/agent-adapter.js\";\nimport { type ChildTaskCompletionRoute, childTaskCompletionRoute } from \"./tasks/child-command-owner.js\";\nimport { COMMAND_DETAIL_TAIL_BYTES, taskOutputText } from \"./tasks/command-output.js\";\nimport {\n\tformatTaskCompletion,\n\tTASK_COMPLETION_MESSAGE_TYPE,\n\tTaskCompletionOutbox,\n\ttaskCompletionNotice,\n} from \"./tasks/completion.js\";\nimport { flushTaskCompletionMessages } from \"./tasks/completion-ordering.js\";\nimport { TASK_HEARTBEAT_MESSAGE_TYPE, type TaskHeartbeatDelivery } from \"./tasks/heartbeat.js\";\nimport { bindOwnerTaskStore, OwnerTaskStore } from \"./tasks/owner-store.js\";\nimport { taskOwnTranscriptEntries, taskTranscriptSource } from \"./tasks/supervisor.js\";\nimport type { SupervisedCommandOwner } from \"./tools/bash-pty-native.js\";\nimport { WorkflowStageAdmissionBoundary } from \"./workflow-stage-admission.ts\";\n\n// Native owners identify live generations, never borrowed persisted storage.\n// Explicit workflow-stage owners remain borrowed across session replacement.\nconst replacementOwnerScopes = new WeakMap<object, string>();\n\n/** An admitted in-process subagent child; top-level sessions may carry a policy without `depth`. */\nexport function isSubagentChildSession(session: Pick<AgentSession, \"_subagentPolicy\">): boolean {\n\treturn (session._subagentPolicy?.depth ?? 0) >= 1;\n}\n\n/**\n * A child launched from a workflow stage inherits the stage's admission boundary for\n * message delivery, but must never bind or rebind the stage's own task owner.\n */\nfunction stageTaskAdmission(session: AgentSession) {\n\treturn isSubagentChildSession(session) ? undefined : session._workflowStageAdmission;\n}\n\nexport function replaceSessionTaskOwner(session: AgentSession): void {\n\tif (stageTaskAdmission(session)) return;\n\treplacementOwnerScopes.set(session, randomUUID());\n\tsession._agentTaskHost = undefined;\n\tsession._taskAdmission = undefined;\n\tsession._taskCompletionOutbox = undefined;\n}\n\nexport function getAgentTaskHost(this: AgentSession): AgentTaskHost {\n\tif (this._disposed || sessionGenerationClosing.has(this)) throw new Error(\"Task owner is closed\");\n\tif (this._agentTaskHost) return this._agentTaskHost;\n\tconst stageAdmission = stageTaskAdmission(this);\n\tconst admission = stageAdmission ?? WorkflowStageAdmissionBoundary.restore(this.sessionManager.getEntries());\n\tthis._taskAdmission = admission;\n\tconst outbox = new TaskCompletionOutbox(\n\t\tthis.sessionManager,\n\t\t() => !this._disposed && admission.isOpen(),\n\t\tasync (envelope, restored) => {\n\t\t\t// Settlement can precede the UI projection's next drain. Read the owner\n\t\t\t// snapshot, not the display store, when attaching completion context.\n\t\t\tconst host = this._agentTaskHost;\n\t\t\tconst watched = host?.watchOwnerTasks();\n\t\t\tconst task = watched?.ok\n\t\t\t\t? watched.value.snapshot.tasks.find(\n\t\t\t\t\t\t(item) => item.ref.taskId === envelope.taskId && item.ref.ownerId === envelope.ownerId,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\tif (watched?.ok) watched.value.dispose();\n\t\t\t// Foreground shell results already return through their tool call. Do not\n\t\t\t// create a second model turn or background card for that same execution.\n\t\t\tif (task?.kind === \"command\" && !task.wasBackground) return;\n\t\t\tconst lease = task ? host?.resolveTask(envelope.taskId) : undefined;\n\t\t\tconst source = lease?.ok ? taskTranscriptSource(lease.value) : undefined;\n\t\t\tconst ownEntries = lease?.ok ? taskOwnTranscriptEntries(lease.value) : undefined;\n\t\t\tconst response = ownEntries\n\t\t\t\t? ownEntries\n\t\t\t\t\t\t.slice()\n\t\t\t\t\t\t.reverse()\n\t\t\t\t\t\t.find(\n\t\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t\t\t\t\tentry.message.role === \"assistant\" &&\n\t\t\t\t\t\t\t\tentry.message.content.some((block) => block.type === \"text\" && block.text.trim()),\n\t\t\t\t\t\t)\n\t\t\t\t: undefined;\n\t\t\tlet output =\n\t\t\t\tresponse?.type === \"message\" && response.message.role === \"assistant\"\n\t\t\t\t\t? response.message.content\n\t\t\t\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t\t\t\t.map((block) => block.text)\n\t\t\t\t\t\t\t.join(\"\\n\")\n\t\t\t\t\t: undefined;\n\t\t\tif (task?.kind === \"command\" && lease?.ok && host) {\n\t\t\t\ttry {\n\t\t\t\t\tconst bytes = BigInt(task.output.byteCount);\n\t\t\t\t\tconst start = bytes > BigInt(COMMAND_DETAIL_TAIL_BYTES) ? bytes - BigInt(COMMAND_DETAIL_TAIL_BYTES) : 0n;\n\t\t\t\t\tconst page = await host.ownerBinding.supervisor.readTaskOutput(lease.value, {\n\t\t\t\t\t\tstart: String(start),\n\t\t\t\t\t\tmaximumBytes: COMMAND_DETAIL_TAIL_BYTES,\n\t\t\t\t\t});\n\t\t\t\t\toutput = page.ok\n\t\t\t\t\t\t? `${start > 0n ? \"[Earlier output omitted]\\n\" : \"\"}${taskOutputText(page.value)}`\n\t\t\t\t\t\t: \"Output unavailable\";\n\t\t\t\t} catch {\n\t\t\t\t\t// Missing retained output must not suppress a terminal notification.\n\t\t\t\t\toutput = \"Output unavailable\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst message = {\n\t\t\t\tcustomType: TASK_COMPLETION_MESSAGE_TYPE,\n\t\t\t\tcontent: formatTaskCompletion(envelope, task, output),\n\t\t\t\tdetails: { ...envelope, notification: taskCompletionNotice(envelope, task, output) },\n\t\t\t\tdisplay: true as const,\n\t\t\t};\n\t\t\tconst childRoute =\n\t\t\t\thost && task?.kind === \"command\" ? childTaskCompletionRoute(host, envelope.taskId) : undefined;\n\t\t\tif (childRoute) {\n\t\t\t\ttry {\n\t\t\t\t\tawait childRoute.deliver(message);\n\t\t\t\t\treturn;\n\t\t\t\t} catch {\n\t\t\t\t\t// The launching child ended before delivery; the owning parent receives the notice.\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst completionSource = source?.ok ? source.value.session.completionSource : undefined;\n\t\t\tif (completionSource) {\n\t\t\t\tawait flushTaskCompletionMessages(\n\t\t\t\t\tgetExtensionRuntimeEventBus(this._resourceLoader.getExtensions().runtime),\n\t\t\t\t\tcompletionSource,\n\t\t\t\t\tenvelope.completionId,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst deliver = () =>\n\t\t\t\tthis.sendCustomMessage(\n\t\t\t\t\tmessage,\n\t\t\t\t\trestored\n\t\t\t\t\t\t? { triggerTurn: false, stageAdmissionKey: envelope.completionId }\n\t\t\t\t\t\t: { triggerTurn: true, persistWhenStreaming: true, stageAdmissionKey: envelope.completionId },\n\t\t\t\t);\n\t\t\tif (stageAdmission) await deliver();\n\t\t\telse {\n\t\t\t\tawait admission.admit(envelope.completionId, deliver, () => {\n\t\t\t\t\tthrow new Error(\"Task owner is closed\");\n\t\t\t\t}).completion;\n\t\t\t}\n\t\t},\n\t);\n\tthis._taskCompletionOutbox = outbox;\n\tconst heartbeat: TaskHeartbeatDelivery = {\n\t\tdefaultIntervalMs: () => this.settingsManager.getTaskHeartbeatMs(),\n\t\thasUnreadHeartbeat: () => hasUnreadProtectedCustomMessage(this, TASK_HEARTBEAT_MESSAGE_TYPE),\n\t\tdeliver: async (message) => {\n\t\t\tif (this._disposed || !admission.isOpen()) throw new Error(\"Task owner is closed\");\n\t\t\t// The workflow heartbeat delivery: a visible card plus a steer that waits for the next safe boundary,\n\t\t\t// never interrupting a response in progress.\n\t\t\tconst deliver = () =>\n\t\t\t\tthis.sendCustomMessage(message, { triggerTurn: true, deliverAs: \"steer\", persistWhenStreaming: true });\n\t\t\tif (stageAdmission) await deliver();\n\t\t\telse\n\t\t\t\tawait admission.admit(undefined, deliver, () => {\n\t\t\t\t\tthrow new Error(\"Task owner is closed\");\n\t\t\t\t}).completion;\n\t\t},\n\t};\n\tconst binding = {\n\t\tresourceAdmission: this._resourceAdmission,\n\t\theartbeat,\n\t\tauthorizeLaunch: () => {\n\t\t\tif (this._disposed || sessionGenerationClosing.has(this) || !admission.isOpen())\n\t\t\t\tthrow new Error(\"Task owner is closed\");\n\t\t\tif (isSubagentChildSession(this)) throw new Error(\"Subagent delegation is not available inside a subagent\");\n\t\t},\n\t\tonTaskSettled: (\n\t\t\t...[ref, receipt]: Parameters<NonNullable<import(\"./tasks/supervisor.js\").TrustedTaskHost[\"onTaskSettled\"]>>\n\t\t) => {\n\t\t\t// Save the task's kind with the intent: a notice replayed after a restart has no task record to read it from.\n\t\t\tconst watched = this._agentTaskHost?.watchOwnerTasks();\n\t\t\tconst kind = watched?.ok\n\t\t\t\t? watched.value.snapshot.tasks.find((task) => task.ref.taskId === receipt.taskId)?.kind\n\t\t\t\t: undefined;\n\t\t\tif (watched?.ok) watched.value.dispose();\n\t\t\toutbox.record(ref.ownerId, receipt, kind);\n\t\t\tvoid outbox.flush();\n\t\t},\n\t};\n\tif (!stageAdmission && !replacementOwnerScopes.has(this)) replacementOwnerScopes.set(this, randomUUID());\n\tthis._agentTaskHost = stageAdmission\n\t\t? stageAdmission.bindAgentTaskHost(binding)\n\t\t: new AgentTaskHost({\n\t\t\t\t...binding,\n\t\t\t\tscope: {\n\t\t\t\t\tkind: \"session\",\n\t\t\t\t\tsessionId: replacementOwnerScopes.get(this)!,\n\t\t\t\t},\n\t\t\t});\n\tconst { supervisor, owner } = this._agentTaskHost.ownerBinding;\n\tconst store = new OwnerTaskStore(supervisor, owner);\n\tconst connected = store.connect();\n\tif (!connected.ok) throw new Error(connected.error.message);\n\tbindOwnerTaskStore(this, store);\n\treturn this._agentTaskHost;\n}\n\n/**\n * Shell task owner for this session. A subagent child runs shells in its parent's owner,\n * so they appear in the parent's `/tasks` and outlive the child.\n */\nexport function _getCommandTaskOwner(this: AgentSession): SupervisedCommandOwner | undefined {\n\tif (!isSubagentChildSession(this)) return this.getAgentTaskHost().ownerBinding;\n\tif (!this._parentCommandTaskOwner || this._disposed) return undefined;\n\tconst route: ChildTaskCompletionRoute = {\n\t\tisOpen: () => !this._disposed && this._subagentPolicy?.messageAdmission?.isOpen() === true,\n\t\tdeliver: async (message) => {\n\t\t\tconst admission = this._subagentPolicy?.messageAdmission;\n\t\t\tif (!admission) throw new Error(\"Subagent execution cannot accept messages\");\n\t\t\tawait admission.run(() => this.sendCustomMessage(message, { triggerTurn: true, persistWhenStreaming: true }));\n\t\t},\n\t};\n\treturn this._parentCommandTaskOwner.bind(this.sessionManager.getSessionId(), route, this._childTaskWaits);\n}\n\nexport async function closeSessionTasks(this: AgentSession): Promise<void> {\n\t// Replacement stage sessions share generation lifetime; disposal is not stage closure.\n\tif (stageTaskAdmission(this)) return;\n\tthis._taskAdmission?.seal();\n\tconst closed = await this._agentTaskHost?.close(\"session-close\");\n\tif (closed && !closed.ok) throw new Error(`${closed.error.code}: ${closed.error.message}`);\n}\n\n/** Workflow controller only: main-chat message pause does not stop owned tasks. */\nexport async function pauseTasks(this: AgentSession): Promise<void> {\n\tawait this.getAgentTaskHost().pauseTasks();\n}\n\nexport function resumeTasks(this: AgentSession): void {\n\tthis._agentTaskHost?.resumeTasks();\n}\n\nexport const agentSessionTaskMethods = {\n\tgetAgentTaskHost,\n\t_getCommandTaskOwner,\n\tcloseSessionTasks,\n\tpauseTasks,\n\tresumeTasks,\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"child-session-options.d.ts","sourceRoot":"","sources":["../../src/core/child-session-options.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAKhE,2FAA2F;AAC3F,MAAM,MAAM,2BAA2B,GAAG,CAAC,OAAO,EAAE,yBAAyB,KAAK,yBAAyB,CAAC;AAO5G,wBAAgB,0BAA0B,CACzC,MAAM,EAAE,yBAAyB,EACjC,KAAK,EAAE,yBAAyB,EAChC,kBAAkB,GAAE,SAAS,MAAM,EAAO,GACxC,yBAAyB,CAuD3B"}
1
+ {"version":3,"file":"child-session-options.d.ts","sourceRoot":"","sources":["../../src/core/child-session-options.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAKhE,2FAA2F;AAC3F,MAAM,MAAM,2BAA2B,GAAG,CAAC,OAAO,EAAE,yBAAyB,KAAK,yBAAyB,CAAC;AAO5G,wBAAgB,0BAA0B,CACzC,MAAM,EAAE,yBAAyB,EACjC,KAAK,EAAE,yBAAyB,EAChC,kBAAkB,GAAE,SAAS,MAAM,EAAO,GACxC,yBAAyB,CAyD3B"}
@@ -40,7 +40,9 @@ export function inheritChildSessionOptions(parent, child, availableToolNames = [
40
40
  return {
41
41
  ...parent,
42
42
  ...definedOptions(child),
43
- resourceAdmission: parent.resourceAdmission ?? child.resourceAdmission,
43
+ // The parent's admission, or the child's own, is the child's only one: a parent that holds none makes the child
44
+ // hold none, so a `withResourceAdmission` scope the parent's turn happened to start in never gates its child.
45
+ resourceAdmission: parent.resourceAdmission ?? child.resourceAdmission ?? null,
44
46
  resourceAdmissionSignal: child.resourceAdmissionSignal,
45
47
  resourceAdmissionDelegated: parent.resourceAdmission ? true : child.resourceAdmissionDelegated,
46
48
  cwd: resolve(parent.cwd, child.cwd ?? child.sessionManager?.getCwd() ?? "."),
@@ -1 +1 @@
1
- {"version":3,"file":"child-session-options.js","sourceRoot":"","sources":["../../src/core/child-session-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC3F,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAKrE,2FAA2F;AAC3F,SAAS,cAAc,CAAmB,OAAsB;IAC/D,OAAO,MAAM,CAAC,WAAW,CAAC,MAA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,CAAC,KAAK,EAAE,MAAM,CAAC;YAC1E,CAAC,CAAC,CAAC,UAAU,IAAI,SAAS,CAAC;KAC7B,CAAC;AACH,CAAC","sourcesContent":["import { resolve } from \"node:path\";\nimport type { CreateAgentSessionOptions } from \"./sdk-types.ts\";\nimport { applyToolModifiers, getToolListError, isToolModifier } from \"./settings-merge.js\";\nimport { createToolNameMatcher, isMcpToolName } from \"./tool-selection.ts\";\nimport { allToolNames, getDefaultToolNames } from \"./tools/index.js\";\n\n/** Internal owner-bound adapter seam. Does not admit work or transfer parent authority. */\nexport type ChildSessionOptionsResolver = (options: CreateAgentSessionOptions) => CreateAgentSessionOptions;\n\n/** Optional undefined values retain inheritance; null and other explicit values do not. */\nfunction definedOptions<T extends object>(options: T | undefined): Partial<T> {\n\treturn Object.fromEntries(Object.entries(options ?? {}).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\nexport function inheritChildSessionOptions(\n\tparent: CreateAgentSessionOptions,\n\tchild: CreateAgentSessionOptions,\n\tavailableToolNames: readonly string[] = [],\n): CreateAgentSessionOptions {\n\tconst builtins = { ...parent.builtins, ...definedOptions(child.builtins) };\n\tfor (const name of [\"workflows\", \"subagents\", \"mcp\", \"web-access\", \"intercom\"] as const) {\n\t\tif (parent.builtins?.[name] === false) builtins[name] = false;\n\t}\n\tconst ceiling = parent.noTools === \"all\" ? [] : parent.tools;\n\tconst parentAllows = createToolNameMatcher(ceiling ?? []);\n\tconst parentNamesMcp = createToolNameMatcher((ceiling ?? []).filter((entry) => entry.startsWith(\"mcp__\")));\n\tconst toolListError = child.tools ? getToolListError(child.tools) : undefined;\n\tif (toolListError) throw new Error(`Invalid tools option: ${toolListError}`);\n\tconst codingToolNames = new Set<string>(allToolNames);\n\tconst inheritedCustomToolNames = [...new Set([...availableToolNames, ...(ceiling ?? [])])].filter(\n\t\t(name) => !name.includes(\"*\") && !codingToolNames.has(name) && parentAllows(name),\n\t);\n\tconst childToolNames = child.tools?.some(isToolModifier)\n\t\t? applyToolModifiers(\n\t\t\t\t[\n\t\t\t\t\t...((child.noTools ?? parent.noTools)\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: ((child.settingsManager ?? parent.settingsManager)?.getDefaultTools() ?? getDefaultToolNames())),\n\t\t\t\t\t...inheritedCustomToolNames,\n\t\t\t\t],\n\t\t\t\tchild.tools,\n\t\t\t)\n\t\t: child.tools;\n\tconst childAllows = childToolNames === undefined ? undefined : createToolNameMatcher(childToolNames);\n\tconst tools =\n\t\tceiling === undefined\n\t\t\t? child.tools\n\t\t\t: [...new Set([...availableToolNames, ...ceiling, ...(childToolNames ?? [])])].filter(\n\t\t\t\t\t(name) =>\n\t\t\t\t\t\t!name.includes(\"*\") &&\n\t\t\t\t\t\tparentAllows(name) &&\n\t\t\t\t\t\t(!childAllows || childAllows(name)) &&\n\t\t\t\t\t\t(!isMcpToolName(name) || ceiling.includes(name) || parentNamesMcp(name)),\n\t\t\t\t);\n\tconst parentGate = parent.isFallbackModelAllowed;\n\tconst childGate = child.isFallbackModelAllowed;\n\treturn {\n\t\t...parent,\n\t\t...definedOptions(child),\n\t\tresourceAdmission: parent.resourceAdmission ?? child.resourceAdmission,\n\t\tresourceAdmissionSignal: child.resourceAdmissionSignal,\n\t\tresourceAdmissionDelegated: parent.resourceAdmission ? true : child.resourceAdmissionDelegated,\n\t\tcwd: resolve(parent.cwd!, child.cwd ?? child.sessionManager?.getCwd() ?? \".\"),\n\t\tbuiltins,\n\t\ttools,\n\t\texcludedTools: [...(parent.excludedTools ?? []), ...(child.excludedTools ?? [])],\n\t\tnoTools: parent.noTools === \"all\" ? \"all\" : (child.noTools ?? parent.noTools),\n\t\textensionBindings: { ...parent.extensionBindings, ...definedOptions(child.extensionBindings) },\n\t\tisFallbackModelAllowed:\n\t\t\tparentGate && childGate\n\t\t\t\t? (model, effort) => parentGate(model, effort) && childGate(model, effort)\n\t\t\t\t: (parentGate ?? childGate),\n\t};\n}\n"]}
1
+ {"version":3,"file":"child-session-options.js","sourceRoot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AC,aAAa,IAAI,EAAE,CAAC,CAAC;QAChF,OAAO,EAAE,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC;QAC7E,iBAAiB,EAAE,EAAE,GAAG,MAAM,CAAC,iBAAiB,EAAE,GAAG,cAAc,CAAC,KAAK,CAAC,iBAAiB,CAAC,EAAE;QAC9F,sBAAsB,EACrB,UAAU,IAAI,SAAS;YACtB,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC;YAC1E,CAAC,CAAC,CAAC,UAAU,IAAI,SAAS,CAAC;KAC7B,CAAC;AACH,CAAC","sourcesContent":["import { resolve } from \"node:path\";\nimport type { CreateAgentSessionOptions } from \"./sdk-types.ts\";\nimport { applyToolModifiers, getToolListError, isToolModifier } from \"./settings-merge.js\";\nimport { createToolNameMatcher, isMcpToolName } from \"./tool-selection.ts\";\nimport { allToolNames, getDefaultToolNames } from \"./tools/index.js\";\n\n/** Internal owner-bound adapter seam. Does not admit work or transfer parent authority. */\nexport type ChildSessionOptionsResolver = (options: CreateAgentSessionOptions) => CreateAgentSessionOptions;\n\n/** Optional undefined values retain inheritance; null and other explicit values do not. */\nfunction definedOptions<T extends object>(options: T | undefined): Partial<T> {\n\treturn Object.fromEntries(Object.entries(options ?? {}).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\nexport function inheritChildSessionOptions(\n\tparent: CreateAgentSessionOptions,\n\tchild: CreateAgentSessionOptions,\n\tavailableToolNames: readonly string[] = [],\n): CreateAgentSessionOptions {\n\tconst builtins = { ...parent.builtins, ...definedOptions(child.builtins) };\n\tfor (const name of [\"workflows\", \"subagents\", \"mcp\", \"web-access\", \"intercom\"] as const) {\n\t\tif (parent.builtins?.[name] === false) builtins[name] = false;\n\t}\n\tconst ceiling = parent.noTools === \"all\" ? [] : parent.tools;\n\tconst parentAllows = createToolNameMatcher(ceiling ?? []);\n\tconst parentNamesMcp = createToolNameMatcher((ceiling ?? []).filter((entry) => entry.startsWith(\"mcp__\")));\n\tconst toolListError = child.tools ? getToolListError(child.tools) : undefined;\n\tif (toolListError) throw new Error(`Invalid tools option: ${toolListError}`);\n\tconst codingToolNames = new Set<string>(allToolNames);\n\tconst inheritedCustomToolNames = [...new Set([...availableToolNames, ...(ceiling ?? [])])].filter(\n\t\t(name) => !name.includes(\"*\") && !codingToolNames.has(name) && parentAllows(name),\n\t);\n\tconst childToolNames = child.tools?.some(isToolModifier)\n\t\t? applyToolModifiers(\n\t\t\t\t[\n\t\t\t\t\t...((child.noTools ?? parent.noTools)\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: ((child.settingsManager ?? parent.settingsManager)?.getDefaultTools() ?? getDefaultToolNames())),\n\t\t\t\t\t...inheritedCustomToolNames,\n\t\t\t\t],\n\t\t\t\tchild.tools,\n\t\t\t)\n\t\t: child.tools;\n\tconst childAllows = childToolNames === undefined ? undefined : createToolNameMatcher(childToolNames);\n\tconst tools =\n\t\tceiling === undefined\n\t\t\t? child.tools\n\t\t\t: [...new Set([...availableToolNames, ...ceiling, ...(childToolNames ?? [])])].filter(\n\t\t\t\t\t(name) =>\n\t\t\t\t\t\t!name.includes(\"*\") &&\n\t\t\t\t\t\tparentAllows(name) &&\n\t\t\t\t\t\t(!childAllows || childAllows(name)) &&\n\t\t\t\t\t\t(!isMcpToolName(name) || ceiling.includes(name) || parentNamesMcp(name)),\n\t\t\t\t);\n\tconst parentGate = parent.isFallbackModelAllowed;\n\tconst childGate = child.isFallbackModelAllowed;\n\treturn {\n\t\t...parent,\n\t\t...definedOptions(child),\n\t\t// The parent's admission, or the child's own, is the child's only one: a parent that holds none makes the child\n\t\t// hold none, so a `withResourceAdmission` scope the parent's turn happened to start in never gates its child.\n\t\tresourceAdmission: parent.resourceAdmission ?? child.resourceAdmission ?? null,\n\t\tresourceAdmissionSignal: child.resourceAdmissionSignal,\n\t\tresourceAdmissionDelegated: parent.resourceAdmission ? true : child.resourceAdmissionDelegated,\n\t\tcwd: resolve(parent.cwd!, child.cwd ?? child.sessionManager?.getCwd() ?? \".\"),\n\t\tbuiltins,\n\t\ttools,\n\t\texcludedTools: [...(parent.excludedTools ?? []), ...(child.excludedTools ?? [])],\n\t\tnoTools: parent.noTools === \"all\" ? \"all\" : (child.noTools ?? parent.noTools),\n\t\textensionBindings: { ...parent.extensionBindings, ...definedOptions(child.extensionBindings) },\n\t\tisFallbackModelAllowed:\n\t\t\tparentGate && childGate\n\t\t\t\t? (model, effort) => parentGate(model, effort) && childGate(model, effort)\n\t\t\t\t: (parentGate ?? childGate),\n\t};\n}\n"]}
@@ -100,7 +100,12 @@ export interface CreateAgentSessionOptions {
100
100
  * parent's child-session options, so child background shells appear in the parent's `/tasks`.
101
101
  */
102
102
  parentCommandTaskOwner?: import("./tasks/child-command-owner.js").ChildCommandTaskOwner;
103
- resourceAdmission?: ResourceAdmission;
103
+ /**
104
+ * Capacity policy for this session and its managed commands. Omitted, the session draws its own permit from the
105
+ * enclosing `withResourceAdmission` scope, if any. `null` means it holds none, even inside such a scope. Child
106
+ * options from `getChildSessionOptions()` carry the parent's admission, or `null` when the parent holds none.
107
+ */
108
+ resourceAdmission?: ResourceAdmission | null;
104
109
  resourceAdmissionSignal?: AbortSignal;
105
110
  resourceAdmissionDelegated?: boolean;
106
111
  /** Transform the fully constructed base system prompt at session construction. */
@@ -1 +1 @@
1
- {"version":3,"file":"sdk-types.d.ts","sourceRoot":"","sources":["../../src/core/sdk-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAA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IACnD,gFAAgF;IAChF,uBAAuB,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,YAAY,EAAE,CAAC;CACvE;AAED,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,IAAI,EAAE,oBAAoB,CAAC;IACpC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,MAAM,cAAc,GAAG,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG;IACpD,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE,uBAAuB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACnE,CAAC;AAEF,MAAM,WAAW,iBAAiB;IACjC,OAAO,CACN,IAAI,EAAE,SAAS,GAAG,SAAS,EAC3B,MAAM,CAAC,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,wBAAwB,GAChC,OAAO,CAAC,cAAc,CAAC,CAAC;CAC3B;AAED,qCAAqC;AACrC,MAAM,WAAW,wBAAwB;IACxC,0BAA0B;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,mEAAmE;IACnE,gBAAgB,EAAE,oBAAoB,CAAC;IACvC,sEAAsE;IACtE,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,gFAAgF;IAChF,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;CAC1C"}
@@ -1 +1 @@
1
- {"version":3,"file":"sdk-types.js","sourceRoot":"","sources":["../../src/core/sdk-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { AgentSession } from \"./agent-session.js\";\nimport type { ExtensionBindings } from \"./agent-session-types.js\";\nimport type {\n\tLoadExtensionsResult,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tSubagentChildPolicy,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nimport type { ModelFallbackReason } from \"./model-resolver-types.ts\";\nimport type { ModelRuntime } from \"./model-runtime.js\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { RunJournalOption, StorageSelection } from \"./storage/provider.js\";\nimport type { SessionStore } from \"./storage/session/types.js\";\n\nexport type AtomicBuiltin = \"workflows\" | \"subagents\" | \"mcp\" | \"web-access\" | \"intercom\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Shipped packages are enabled unless explicitly false. Independent of tool selection. */\n\tbuiltins?: Partial<Record<AtomicBuiltin, boolean>>;\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.atomic/agent */\n\tagentDir?: string;\n\t/**\n\t * Workflow journal for this session's `workflow` tool: a file path, a caller-owned database, process-local\n\t * memory, a storage adapter, or a supplied journal. Overrides process-level selections (`ATOMIC_WORKFLOWS_JOURNAL`,\n\t * `ATOMIC_WORKFLOW_JOURNAL_PATH`, `ATOMIC_STORAGE`), the session's `workflows.journal` settings, and the default\n\t * journal file. The caller closes a database or journal it supplies.\n\t */\n\tjournal?: RunJournalOption;\n\n\t/** Canonical model/auth runtime. Defaults to agentDir/auth.json and models.json. */\n\tmodelRuntime?: ModelRuntime;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<Api>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Ordered fallback models as provider/model strings with optional :thinkingLevel suffix.\n\t * Used by main-chat turns and borrowed, planner-only, for compaction range planning when\n\t * the current model cannot produce a usable plan — so a configured candidate may receive\n\t * the compaction transcript. Borrowing never changes the session model or thinking level.\n\t * Default: settings.fallbackModels\n\t */\n\tfallbackModels?: string[];\n\t/** Hard eligibility gate applied before fallback inference, including compaction borrowing. */\n\tisFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Tool suppression mode.\n\t *\n\t * - \"all\": no active tools, even with an explicit allowlist\n\t * - \"builtin\": suppress coding-tool defaults only when tools is omitted;\n\t * extension/custom tools remain enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names or patterns where `*` matches any characters.\n\t *\n\t * When omitted, Atomic uses the resolved `defaultTools` setting for the initial\n\t * built-in selection when configured. Otherwise it enables the default\n\t * built-in tools (read, bash, edit, write, find, search, ask_user_question,\n\t * todo). Extension/custom tools remain enabled unless `noTools` changes\n\t * that default. MCP tools stay registered for codemode and tool search unless\n\t * an entry starts with `mcp__`; only matching tools are declared directly.\n\t * `excludedTools` applies afterwards. `noTools: \"all\"` overrides this selection.\n\t * Intercom follows the same selection and suppression rules as other extension tools.\n\t * A list of only `+name`/`-name` entries changes the resolved defaults instead\n\t * of allowlisting tools, and is reapplied on reload. Modifiers take exact names;\n\t * mixing them with plain names or patterns throws. Total suppression still wins.\n\t */\n\ttools?: string[];\n\t/**\n\t * Optional blocklist of tool names or patterns, including MCP tools.\n\t *\n\t * Matching built-in, extension, and SDK custom tools are omitted from the\n\t * final session tool registry and active tool set. Unknown names are ignored.\n\t */\n\texcludedTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\t/** Session storage. Defaults to the resolved settings or the shared local SQLite database. */\n\tsessionStore?: SessionStore | StorageSelection;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Host bindings installed before extension startup. Rebinding does not replay startup. */\n\textensionBindings?: ExtensionBindings;\n\t/** Session-scoped orchestration policy exposed to extension/tool handlers. */\n\torchestrationContext?: OrchestrationContext;\n\t/** Typed capability policy for an in-process subagent child. */\n\tsubagentPolicy?: SubagentChildPolicy;\n\t/**\n\t * Internal: parent-issued shell task owner for an in-process subagent child. Supplied by the\n\t * parent's child-session options, so child background shells appear in the parent's `/tasks`.\n\t */\n\tparentCommandTaskOwner?: import(\"./tasks/child-command-owner.js\").ChildCommandTaskOwner;\n\tresourceAdmission?: ResourceAdmission;\n\tresourceAdmissionSignal?: AbortSignal;\n\tresourceAdmissionDelegated?: boolean;\n\t/** Transform the fully constructed base system prompt at session construction. */\n\tsystemPromptTransform?: (prompt: string) => string;\n\t/** Filter inherited session messages before they enter the new AgentSession. */\n\tinitialContextTransform?: (messages: AgentMessage[]) => AgentMessage[];\n}\n\nexport interface ResourceAdmissionRequest {\n\treadonly delegated?: boolean;\n}\n\nexport interface ResourceProcessIdentity {\n\treadonly kind: \"unix-process-group\";\n\treadonly id: number;\n}\n\nexport type ResourcePermit = (() => Promise<void>) & {\n\tbindProcess?: (identity: ResourceProcessIdentity) => Promise<void>;\n};\n\nexport interface ResourceAdmission {\n\tacquire(\n\t\tkind: \"session\" | \"process\",\n\t\tsignal?: AbortSignal,\n\t\trequest?: ResourceAdmissionRequest,\n\t): Promise<ResourcePermit>;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning when a restored or configured model cannot be selected. */\n\tmodelFallbackMessage?: string;\n\t/** Semantic reason for modelFallbackMessage; suitable for mode control flow. */\n\tmodelFallbackReason?: ModelFallbackReason;\n}\n"]}
1
+ {"version":3,"file":"sdk-types.js","sourceRoot":"","sources":["../../src/core/sdk-types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { AgentSession } from \"./agent-session.js\";\nimport type { ExtensionBindings } from \"./agent-session-types.js\";\nimport type {\n\tLoadExtensionsResult,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tSubagentChildPolicy,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nimport type { ModelFallbackReason } from \"./model-resolver-types.ts\";\nimport type { ModelRuntime } from \"./model-runtime.js\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { RunJournalOption, StorageSelection } from \"./storage/provider.js\";\nimport type { SessionStore } from \"./storage/session/types.js\";\n\nexport type AtomicBuiltin = \"workflows\" | \"subagents\" | \"mcp\" | \"web-access\" | \"intercom\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Shipped packages are enabled unless explicitly false. Independent of tool selection. */\n\tbuiltins?: Partial<Record<AtomicBuiltin, boolean>>;\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.atomic/agent */\n\tagentDir?: string;\n\t/**\n\t * Workflow journal for this session's `workflow` tool: a file path, a caller-owned database, process-local\n\t * memory, a storage adapter, or a supplied journal. Overrides process-level selections (`ATOMIC_WORKFLOWS_JOURNAL`,\n\t * `ATOMIC_WORKFLOW_JOURNAL_PATH`, `ATOMIC_STORAGE`), the session's `workflows.journal` settings, and the default\n\t * journal file. The caller closes a database or journal it supplies.\n\t */\n\tjournal?: RunJournalOption;\n\n\t/** Canonical model/auth runtime. Defaults to agentDir/auth.json and models.json. */\n\tmodelRuntime?: ModelRuntime;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<Api>;\n\t/** Thinking level. Default: from settings, else 'medium' (clamped to model capabilities) */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Ordered fallback models as provider/model strings with optional :thinkingLevel suffix.\n\t * Used by main-chat turns and borrowed, planner-only, for compaction range planning when\n\t * the current model cannot produce a usable plan — so a configured candidate may receive\n\t * the compaction transcript. Borrowing never changes the session model or thinking level.\n\t * Default: settings.fallbackModels\n\t */\n\tfallbackModels?: string[];\n\t/** Hard eligibility gate applied before fallback inference, including compaction borrowing. */\n\tisFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Tool suppression mode.\n\t *\n\t * - \"all\": no active tools, even with an explicit allowlist\n\t * - \"builtin\": suppress coding-tool defaults only when tools is omitted;\n\t * extension/custom tools remain enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names or patterns where `*` matches any characters.\n\t *\n\t * When omitted, Atomic uses the resolved `defaultTools` setting for the initial\n\t * built-in selection when configured. Otherwise it enables the default\n\t * built-in tools (read, bash, edit, write, find, search, ask_user_question,\n\t * todo). Extension/custom tools remain enabled unless `noTools` changes\n\t * that default. MCP tools stay registered for codemode and tool search unless\n\t * an entry starts with `mcp__`; only matching tools are declared directly.\n\t * `excludedTools` applies afterwards. `noTools: \"all\"` overrides this selection.\n\t * Intercom follows the same selection and suppression rules as other extension tools.\n\t * A list of only `+name`/`-name` entries changes the resolved defaults instead\n\t * of allowlisting tools, and is reapplied on reload. Modifiers take exact names;\n\t * mixing them with plain names or patterns throws. Total suppression still wins.\n\t */\n\ttools?: string[];\n\t/**\n\t * Optional blocklist of tool names or patterns, including MCP tools.\n\t *\n\t * Matching built-in, extension, and SDK custom tools are omitted from the\n\t * final session tool registry and active tool set. Unknown names are ignored.\n\t */\n\texcludedTools?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd) */\n\tsessionManager?: SessionManager;\n\t/** Session storage. Defaults to the resolved settings or the shared local SQLite database. */\n\tsessionStore?: SessionStore | StorageSelection;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n\t/** Host bindings installed before extension startup. Rebinding does not replay startup. */\n\textensionBindings?: ExtensionBindings;\n\t/** Session-scoped orchestration policy exposed to extension/tool handlers. */\n\torchestrationContext?: OrchestrationContext;\n\t/** Typed capability policy for an in-process subagent child. */\n\tsubagentPolicy?: SubagentChildPolicy;\n\t/**\n\t * Internal: parent-issued shell task owner for an in-process subagent child. Supplied by the\n\t * parent's child-session options, so child background shells appear in the parent's `/tasks`.\n\t */\n\tparentCommandTaskOwner?: import(\"./tasks/child-command-owner.js\").ChildCommandTaskOwner;\n\t/**\n\t * Capacity policy for this session and its managed commands. Omitted, the session draws its own permit from the\n\t * enclosing `withResourceAdmission` scope, if any. `null` means it holds none, even inside such a scope. Child\n\t * options from `getChildSessionOptions()` carry the parent's admission, or `null` when the parent holds none.\n\t */\n\tresourceAdmission?: ResourceAdmission | null;\n\tresourceAdmissionSignal?: AbortSignal;\n\tresourceAdmissionDelegated?: boolean;\n\t/** Transform the fully constructed base system prompt at session construction. */\n\tsystemPromptTransform?: (prompt: string) => string;\n\t/** Filter inherited session messages before they enter the new AgentSession. */\n\tinitialContextTransform?: (messages: AgentMessage[]) => AgentMessage[];\n}\n\nexport interface ResourceAdmissionRequest {\n\treadonly delegated?: boolean;\n}\n\nexport interface ResourceProcessIdentity {\n\treadonly kind: \"unix-process-group\";\n\treadonly id: number;\n}\n\nexport type ResourcePermit = (() => Promise<void>) & {\n\tbindProcess?: (identity: ResourceProcessIdentity) => Promise<void>;\n};\n\nexport interface ResourceAdmission {\n\tacquire(\n\t\tkind: \"session\" | \"process\",\n\t\tsignal?: AbortSignal,\n\t\trequest?: ResourceAdmissionRequest,\n\t): Promise<ResourcePermit>;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning when a restored or configured model cannot be selected. */\n\tmodelFallbackMessage?: string;\n\t/** Semantic reason for modelFallbackMessage; suitable for mode control flow. */\n\tmodelFallbackReason?: ModelFallbackReason;\n}\n"]}
package/dist/core/sdk.js CHANGED
@@ -120,7 +120,9 @@ function createScopedSession(options, deferStart, persistInitialState = true) {
120
120
  };
121
121
  if (options.sessionManager)
122
122
  ownedSessionManagerStores.delete(options.sessionManager);
123
- const admission = options.resourceAdmission ?? currentResourceAdmission();
123
+ const admission = options.resourceAdmission === null
124
+ ? undefined
125
+ : (options.resourceAdmission ?? currentResourceAdmission());
124
126
  try {
125
127
  acquisition.release = await admission?.acquire("session", options.resourceAdmissionSignal, options.resourceAdmissionDelegated ? { delegated: true } : undefined);
126
128
  return await constructAgentSession({
@@ -609,7 +611,7 @@ async function constructAgentSession(options, deferStart, persistInitialState, a
609
611
  orchestrationContext: options.orchestrationContext,
610
612
  subagentPolicy,
611
613
  parentCommandTaskOwner: options.parentCommandTaskOwner,
612
- resourceAdmission: options.resourceAdmission,
614
+ resourceAdmission: options.resourceAdmission ?? undefined,
613
615
  systemPromptTransform: options.systemPromptTransform,
614
616
  contextProjectionTransform: options.initialContextTransform,
615
617
  });