@sorbetai/durable 0.1.0-alpha.16 → 0.1.0-alpha.17

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.
@@ -1,4 +1,4 @@
1
- import { _ as WaitTargetSource } from "./contracts-L7iISO7a.js";
1
+ import { _ as WaitTargetSource } from "./contracts-ui4Wvp-X.js";
2
2
  import * as s from "@earendil-works/pi-schema";
3
3
  import * as _sorbetai_runtime18 from "@sorbetai/runtime";
4
4
  import { ContextualTool, JournalCursor, JournalSubscription, JsonValue, RunCancellationReceipt, RunInspection, RunTerminalOutcome, RunView, SessionInspection, SessionInspectionOptions, SorbetRun, ToolInvocationContext, UnitReader, UnitRuntime, UnitTx } from "@sorbetai/runtime";
@@ -77,6 +77,11 @@ interface ChildAgentSnapshot {
77
77
  /** Short description of the initial assignment. */
78
78
  readonly description?: string;
79
79
  readonly state: ChildAgentState;
80
+ /** Run of the parent that admitted this child. */
81
+ readonly parentRunId: string;
82
+ /** Parent Tool call that admitted this child; anchors the child in task projections. */
83
+ readonly spawnToolCallId: string;
84
+ readonly createdAt: string;
80
85
  readonly modelUsage: ChildModelUsageSnapshot;
81
86
  readonly runId?: string;
82
87
  readonly outcome?: RunTerminalOutcome;
package/dist/children.js CHANGED
@@ -1114,10 +1114,7 @@ var ChildObservationCoordinator = class {
1114
1114
  if (record.closed) {
1115
1115
  const closedUsage = record.closedUsage ?? await this.#closedUsage(record);
1116
1116
  return {
1117
- agentId: record.agentId,
1118
- childSessionId: record.childSessionId,
1119
- ...record.name === void 0 ? {} : { name: record.name },
1120
- ...record.description === void 0 ? {} : { description: record.description },
1117
+ ...snapshotIdentity(record),
1121
1118
  state: "closed",
1122
1119
  modelUsage: closedUsage.modelUsage
1123
1120
  };
@@ -1125,10 +1122,7 @@ var ChildObservationCoordinator = class {
1125
1122
  const inspection = await this.#options.host.inspectChild(record);
1126
1123
  const runIndex = inspection.runs.length - 1;
1127
1124
  if (runIndex === -1) return {
1128
- agentId: record.agentId,
1129
- childSessionId: record.childSessionId,
1130
- ...record.name === void 0 ? {} : { name: record.name },
1131
- ...record.description === void 0 ? {} : { description: record.description },
1125
+ ...snapshotIdentity(record),
1132
1126
  state: "starting",
1133
1127
  modelUsage: projectModelUsage(inspection.runs)
1134
1128
  };
@@ -1140,10 +1134,7 @@ var ChildObservationCoordinator = class {
1140
1134
  const modelUsage = projectModelUsage(inspection.runs);
1141
1135
  const outcome = run.lifecycle.outcome;
1142
1136
  if (outcome === void 0) return {
1143
- agentId: record.agentId,
1144
- childSessionId: record.childSessionId,
1145
- ...record.name === void 0 ? {} : { name: record.name },
1146
- ...record.description === void 0 ? {} : { description: record.description },
1137
+ ...snapshotIdentity(record),
1147
1138
  state: "running",
1148
1139
  modelUsage,
1149
1140
  runId: run.lifecycle.runId
@@ -1151,10 +1142,7 @@ var ChildObservationCoordinator = class {
1151
1142
  const state = outcome.kind === "completed" ? "completed" : outcome.kind;
1152
1143
  const response = outcome.kind === "completed" ? completedText(inspection, outcome.responseMessageId) : void 0;
1153
1144
  return {
1154
- agentId: record.agentId,
1155
- childSessionId: record.childSessionId,
1156
- ...record.name === void 0 ? {} : { name: record.name },
1157
- ...record.description === void 0 ? {} : { description: record.description },
1145
+ ...snapshotIdentity(record),
1158
1146
  state,
1159
1147
  modelUsage,
1160
1148
  runId: run.lifecycle.runId,
@@ -1171,6 +1159,17 @@ var ChildObservationCoordinator = class {
1171
1159
  };
1172
1160
  }
1173
1161
  };
1162
+ function snapshotIdentity(record) {
1163
+ return {
1164
+ agentId: record.agentId,
1165
+ childSessionId: record.childSessionId,
1166
+ ...record.name === void 0 ? {} : { name: record.name },
1167
+ ...record.description === void 0 ? {} : { description: record.description },
1168
+ parentRunId: record.parentRunId,
1169
+ spawnToolCallId: record.spawnToolCallId,
1170
+ createdAt: record.createdAt
1171
+ };
1172
+ }
1174
1173
  function sumModelUsage(usages) {
1175
1174
  let committedResponses = 0;
1176
1175
  let activeRequests = 0;
@@ -1 +1 @@
1
- {"version":3,"file":"children.js","names":["#tracked","catalog: ChildAgentCatalog","observation: ChildAgentObservationPort | undefined","pending: Promise<void> | undefined","deliveries: ChildDeliveryBacklog[]","NonEmptyString","subagentIdentity: NamedStateOwner","code: ChildAgentFailureCode","identity: ChildOperationIdentity","outcome: Exit.Exit<A, E>","toError","#runtime","#control","#waitForEffect","failures: Error[]","Identity","#inputs","parentSessionId: string","observeAfter: number","fact","input","#options","#completionState","#findRun","#placedRun","#placedRuns","#snapshotRun","#closedUsage","state: ChildAgentSnapshot['state']","NeverAbortSignal","options: Options","#send","#assertSender","#admit","providerId: string","modelId: string","#options","#admitChild","#parent","#modelIdentity","#selectModel","child","child: ChildTaskInput & { initialSubmissionId: string }","admission: ChildAdmission | undefined","#stopChild","#telemetry","#catalog","#observationPort","#runtime","#control","#observation","#delivery","#lifecycle","#runOperation","#shutdown","#closing","#owned","openReader: (parentSessionId: string) => Promise<UnitReader>","state: OwnedProjection","#readCold","cursor: JournalCursor | undefined","NON_EMPTY_STRING_MIN_LENGTH","SAFE_ID_PATTERN","NonEmptyString","SafeId","details: AgentToolDetails","toError","details: TeamToolDetails","toError"],"sources":["../src/children/telemetry-port.ts","../src/children/telemetry.ts","../src/children/contracts.ts","../src/children/control/state.ts","../src/children/control/service.ts","../src/children/control/client.ts","../src/children/usage.ts","../src/children/record.ts","../src/children/close.ts","../src/children/projection.ts","../src/children/completion.ts","../src/children/observation.ts","../src/children/delivery.ts","../src/children/models.ts","../src/children/lifecycle.ts","../src/children/manager.ts","../src/children/catalog.ts","../src/children/tools.ts","../src/children/team-tools.ts"],"sourcesContent":["import { isPromise } from 'es-toolkit';\n\nexport interface ChildDeliveryBacklog {\n readonly direction: 'to_child' | 'to_parent';\n readonly pending: number;\n readonly dispatching: number;\n readonly awaitingInclusion: number;\n /** Wall-clock bound; absent when no pending delivery has a recorded enqueue time. */\n readonly oldestPendingEnqueuedAt?: string;\n readonly unknownPendingAge: number;\n}\n\n/** The callback name is retained for compatibility; its data derives from committed Unit facts. */\nexport interface ChildLedgerObservation {\n readonly parentSessionId: string;\n /** Children with a nonterminal Run, including interrupted or parked Runs; not a resource-usage gauge. */\n readonly activeChildren: number;\n readonly deliveries: readonly ChildDeliveryBacklog[];\n}\n\nexport interface ChildDeliveryObservation {\n readonly parentSessionId: string;\n readonly agentId: string;\n readonly childSessionId?: string;\n readonly deliveryId: string;\n readonly orderingKey: number;\n readonly sourceSessionId: string;\n readonly sourceRunId: string;\n readonly direction: 'to_child' | 'to_parent';\n readonly state: 'pending' | 'dispatching' | 'complete' | 'cancelled';\n readonly transition:\n 'enqueued' | 'dispatched' | 'accepted' | 'included' | 'completed' | 'cancelled';\n /** Persisted wall times, never reconstructed as a continuous monotonic span. */\n readonly enqueuedAt?: string;\n readonly dispatchedAt?: string;\n readonly acceptedAt?: string;\n readonly acceptedRunId?: string;\n readonly acceptedSessionId?: string;\n readonly acceptedFactId?: string;\n readonly acceptedCursor?: string;\n readonly includedAt?: string;\n readonly includedModelRequestId?: string;\n readonly includedFactId?: string;\n readonly includedCursor?: string;\n readonly includedSessionId?: string;\n}\n\nexport interface ChildDeliveryPage {\n readonly parentSessionId: string;\n readonly deliveries: readonly Omit<ChildDeliveryObservation, 'transition'>[];\n readonly nextOrderingKey?: number;\n}\n\nexport interface ChildSpawnObservation {\n readonly parentSessionId: string;\n readonly parentRunId: string;\n readonly childSessionId: string;\n readonly agentId: string;\n readonly toolCallId: string;\n readonly effectAttemptId: string;\n}\n\n/** Borrowed passive metadata callbacks. Durable transitions report only after an atomic\n * Unit commit; reopening a Unit does not replay historical transition counters. Throws and\n * accidental rejected promises cannot alter child admission, delivery, or cleanup. */\nexport interface ChildAgentObservationPort {\n childLedgerProjected?(data: ChildLedgerObservation): void;\n childDeliveryCommitted?(data: ChildDeliveryObservation): void;\n childSpawnCommitted?(data: ChildSpawnObservation): void;\n childLedgerDetached?(data: { readonly parentSessionId: string }): void;\n}\n\nexport function observeChildAgents(report: () => void): void {\n try {\n const pending = report();\n if (isPromise(pending)) void pending.catch(() => {});\n } catch {\n // A Host observation has no authority over child execution or durable ownership.\n }\n}\n","import type { UnitRuntime } from '@sorbetai/runtime';\nimport type { ChildAgentCatalog } from './catalog.js';\nimport {\n observeChildAgents,\n type ChildAgentObservationPort,\n type ChildDeliveryBacklog,\n} from './telemetry-port.js';\n\n/** Observe committed facts without acquiring Sessions, scheduling work or writing a second ledger. */\nexport class ChildTelemetry {\n readonly #tracked = new Map<UnitRuntime, { stop: () => void; settled: () => Promise<void> }>();\n\n constructor(\n readonly catalog: ChildAgentCatalog,\n readonly observation: ChildAgentObservationPort | undefined\n ) {}\n\n track(unit: UnitRuntime): void {\n if (this.observation === undefined || this.#tracked.has(unit)) return;\n let after = unit.workSummary().observedUnitSequence;\n let dirty = false;\n let stopped = false;\n let pending: Promise<void> | undefined;\n const scan = async () => {\n while (dirty) {\n dirty = false;\n const current = await this.catalog.read(unit.unitId, after);\n after = current.observedUnitSequence;\n for (const event of current.observations) {\n observeChildAgents(() => {\n if (event.kind === 'spawn') this.observation?.childSpawnCommitted?.(event.data);\n else this.observation?.childDeliveryCommitted?.(event.data);\n });\n }\n const deliveries: ChildDeliveryBacklog[] = [];\n for (const direction of ['to_child', 'to_parent'] as const) {\n const entries = current.deliveries.filter((delivery) => delivery.direction === direction);\n const queued = entries.filter((delivery) => delivery.state === 'pending');\n deliveries.push({\n direction,\n pending: queued.length,\n dispatching: 0,\n awaitingInclusion: entries.filter(\n (delivery) => delivery.state === 'complete' && delivery.includedFactId === undefined\n ).length,\n oldestPendingEnqueuedAt: queued\n .flatMap((delivery) => delivery.enqueuedAt ?? [])\n .sort()[0],\n unknownPendingAge: queued.filter((delivery) => delivery.enqueuedAt === undefined)\n .length,\n });\n }\n observeChildAgents(() =>\n this.observation?.childLedgerProjected?.({\n parentSessionId: unit.unitId,\n activeChildren: current.activeChildren,\n deliveries,\n })\n );\n }\n };\n const schedule = () => {\n pending ??= scan()\n .catch(() => {\n // Diagnostic reads cannot fence execution. Retry from the last observed commit on the next update.\n })\n .finally(() => {\n pending = undefined;\n if (dirty && !stopped) schedule();\n });\n };\n const unsubscribe = unit.subscribeWork(() => {\n dirty = true;\n schedule();\n });\n const stop = () => {\n stopped = true;\n unsubscribe();\n };\n const tracked = { stop, settled: () => pending ?? Promise.resolve() };\n this.#tracked.set(unit, tracked);\n void unit.closed.then(async () => {\n stop();\n await tracked.settled();\n this.#tracked.delete(unit);\n observeChildAgents(() =>\n this.observation?.childLedgerDetached?.({ parentSessionId: unit.unitId })\n );\n });\n }\n\n async close(): Promise<void> {\n const tracked = [...this.#tracked.values()];\n for (const entry of tracked) entry.stop();\n await Promise.all(tracked.map((entry) => entry.settled()));\n this.#tracked.clear();\n }\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { UsageSchema, type NamedStateOwner } from '@sorbetai/context';\nimport type { RunTerminalOutcome } from '@sorbetai/runtime';\n\nconst NonEmptyString = s.str({ minLength: 1 });\n\n/** Named State for every child Session; parents use `ChildAgentManager.stateOwner` instead. */\nexport const subagentIdentity: NamedStateOwner = {\n stateName: 'agent_identity',\n schema: s.str(),\n read: async () => ({\n present: true,\n value: 'You are a subagent.',\n element: { kind: 'text', name: 'agent_identity', text: 'You are a subagent.' },\n }),\n};\n\nexport const ChildAgentNameSchema = s.str({\n minLength: 1,\n maxLength: 32,\n pattern: '\\\\S',\n description:\n 'A short, pleasant, memorable name for this child, such as Mint or Mochi. Give every child a name.',\n});\nexport const ChildAgentDescriptionSchema = s.str({\n minLength: 1,\n maxLength: 100,\n pattern: '\\\\S',\n description:\n 'A short phrase describing what this child is working on. Give every child a description.',\n});\n\nexport const ChildModelUsageRowSchema = s.obj(\n {\n provider: NonEmptyString,\n model: NonEmptyString,\n usage: UsageSchema,\n },\n { open: false }\n);\n\nexport const ChildModelUsageSnapshotSchema = s.obj(\n {\n committedResponses: s.int({ minimum: 0 }),\n activeRequests: s.int({ minimum: 0 }),\n unknownRequests: s.int({ minimum: 0 }),\n totalTokens: s.num({ minimum: 0 }),\n costUsd: s.num({ minimum: 0 }),\n // Absent on ledgers frozen before per-model rows existed.\n models: s.opt(s.arr(ChildModelUsageRowSchema)),\n },\n { open: false }\n);\n\nexport const ClosedChildUsageSchema = s.obj(\n {\n throughRunId: s.opt(NonEmptyString),\n modelUsage: ChildModelUsageSnapshotSchema,\n },\n { open: false }\n);\n\nexport type ClosedChildUsage = Readonly<s.Static<typeof ClosedChildUsageSchema>>;\n\nexport type ChildAgentState =\n 'starting' | 'running' | 'completed' | 'failed' | 'cancelled' | 'closed';\n\nexport interface ChildAgentSnapshot {\n readonly agentId: string;\n readonly childSessionId: string;\n /** Short display name chosen when this child was spawned. Older children may not have one. */\n readonly name?: string;\n /** Short description of the initial assignment. */\n readonly description?: string;\n readonly state: ChildAgentState;\n readonly modelUsage: ChildModelUsageSnapshot;\n readonly runId?: string;\n readonly outcome?: RunTerminalOutcome;\n readonly response?: {\n readonly text: string;\n readonly truncated: boolean;\n readonly offset?: number;\n readonly nextOffset?: number;\n };\n}\n\ninterface SpawnAgentOptions {\n readonly name?: string;\n readonly description?: string;\n readonly model?: string;\n readonly isBackground?: boolean;\n readonly completionDelivery?: 'auto' | 'manual';\n}\n\nexport type SpawnAgentRequest = { readonly prompt: string } & SpawnAgentOptions;\n\nexport interface SwarmAgentRequest {\n readonly tasks: readonly {\n readonly prompt: string;\n readonly taskId: string;\n readonly name?: string;\n readonly description?: string;\n }[];\n readonly model?: string;\n}\n\nexport interface SendInputRequest {\n readonly agentId: string;\n readonly prompt: string;\n readonly interrupt?: boolean;\n}\n\nexport interface SpawnAgentOutput {\n readonly agent: ChildAgentSnapshot;\n}\n\nexport type SwarmTaskOutput =\n | {\n readonly taskId: string;\n readonly status: 'completed';\n readonly agent: ChildAgentSnapshot;\n }\n | {\n readonly taskId: string;\n readonly status: 'failed';\n readonly agent: ChildAgentSnapshot;\n }\n | {\n readonly taskId: string;\n readonly status: 'failed';\n readonly error: { readonly code: string; readonly message: string };\n }\n | {\n readonly taskId: string;\n readonly status: 'cancelled';\n readonly error: { readonly code: string; readonly message: string };\n };\n\nexport interface SwarmAgentOutput {\n readonly tasks: readonly SwarmTaskOutput[];\n}\n\n/** Accepted input is durable; placement and the Run belong to the child. */\nexport interface SendInputOutput {\n readonly status: 'accepted';\n readonly deliveryId: string;\n readonly agent: ChildAgentSnapshot;\n}\n\nexport interface TeamPeerSnapshot {\n readonly agentId: string;\n readonly state: ChildAgentState;\n}\n\nexport interface ListTeamPeersOutput {\n readonly peers: readonly TeamPeerSnapshot[];\n}\n\nexport interface SendTeamMessageRequest {\n readonly agentId: string;\n readonly prompt: string;\n}\n\nexport interface SendTeamMessageOutput {\n /** The parent ledger owns delivery; the recipient may not have accepted the input yet. */\n readonly status: 'queued';\n readonly deliveryId: string;\n readonly recipient: { readonly agentId: string };\n}\n\nexport interface ListAgentsOutput {\n readonly agents: readonly ChildAgentSnapshot[];\n readonly modelUsage: ChildModelUsageSnapshot;\n}\n\nexport type ChildModelUsageSnapshot = Readonly<s.Static<typeof ChildModelUsageSnapshotSchema>>;\n\nexport interface CloseAgentOutput {\n readonly agent: ChildAgentSnapshot & { readonly state: 'closed' };\n}\n\nexport type ChildAgentFailureCode =\n | 'model_unavailable'\n | 'child_not_found'\n | 'child_closed'\n | 'child_provision_failed'\n | 'child_depth_exceeded'\n | 'child_delivery_conflict'\n | 'child_input_interrupted'\n | 'child_input_pending'\n | 'child_run_not_found'\n | 'team_self_message'\n | 'child_manager_closed';\n\nexport class ChildAgentError extends Error {\n override readonly name = 'ChildAgentError';\n\n constructor(\n readonly code: ChildAgentFailureCode,\n message: string\n ) {\n super(message);\n }\n}\n\nexport function childToolExecutionError(\n cause: Error,\n fallbackCode: 'agent_operation_failed' | 'team_operation_failed',\n fallbackMessage: string\n): Error {\n if (cause instanceof ChildAgentError) {\n return new Error(`${cause.code}: ${cause.message}`, { cause });\n }\n return new Error(`${fallbackCode}: ${fallbackMessage}`, { cause });\n}\n","import type * as Effect from 'effect/Effect';\n\nexport type ChildControlHealth = 'ready' | 'closing' | 'closed';\n\nexport interface ChildOperationIdentity {\n readonly id: symbol;\n readonly settled: Effect.Effect<void>;\n readonly parentSessionId?: string;\n}\n\nexport const childControlKey = (parentSessionId: string, agentId: string): string =>\n `${parentSessionId}:${agentId}`;\n","import * as Context from 'effect/Context';\nimport * as Deferred from 'effect/Deferred';\nimport * as Effect from 'effect/Effect';\nimport * as FiberMap from 'effect/FiberMap';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Ref from 'effect/Ref';\nimport * as Semaphore from 'effect/Semaphore';\nimport * as Exit from 'effect/Exit';\n\nimport { ChildAgentError } from '../contracts.js';\nimport { childControlKey, type ChildControlHealth, type ChildOperationIdentity } from './state.js';\n\ninterface ChildControlService {\n readonly admit: <A, E>(\n parentSessionId: string | undefined,\n operation: Effect.Effect<A, E>\n ) => Effect.Effect<A, E | ChildAgentError>;\n readonly activateParent: (parentSessionId: string) => Effect.Effect<void, ChildAgentError>;\n readonly admitClose: <A, E>(\n parentSessionId: string,\n operation: Effect.Effect<A, E>\n ) => Effect.Effect<A, E | ChildAgentError>;\n readonly interruptParent: (parentSessionId: string) => Effect.Effect<void>;\n readonly beginClose: Effect.Effect<boolean>;\n readonly finishClose: Effect.Effect<void>;\n readonly awaitOperations: Effect.Effect<void>;\n readonly withChildPermit: <A, E, R>(\n parentSessionId: string,\n agentId: string,\n effect: Effect.Effect<A, E, R>\n ) => Effect.Effect<A, E, R>;\n}\n\nexport class ChildControl extends Context.Service<ChildControl, ChildControlService>()(\n 'sorbet/node-agent/children/ChildControl'\n) {\n static readonly layer = Layer.effect(\n ChildControl,\n Effect.gen(function* () {\n const health = yield* Ref.make<ChildControlHealth>('ready');\n const operationGate = yield* Semaphore.make(1);\n const operations = yield* FiberMap.make<symbol, unknown, never>();\n const operationOwners = yield* Ref.make(new Map<symbol, ChildOperationIdentity>());\n const releasedParents = yield* Ref.make<ReadonlySet<string>>(new Set());\n const childPermits = yield* Ref.make(new Map<string, Semaphore.Semaphore>());\n\n const managerClosing = () =>\n new ChildAgentError('child_manager_closed', 'Child agent manager is closing');\n\n const assertReady = Ref.get(health).pipe(\n Effect.flatMap((current) =>\n current === 'ready' ? Effect.void : Effect.fail(managerClosing())\n )\n );\n\n const admit = Effect.fn('ChildControl.admit')(function* <A, E>(\n parentSessionId: string | undefined,\n operation: Effect.Effect<A, E>,\n admission: 'execution' | 'close' = 'execution'\n ): Effect.fn.Return<A, E | ChildAgentError> {\n return yield* Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const result = yield* Deferred.make<Exit.Exit<A, E>>();\n const identity: ChildOperationIdentity = {\n id: Symbol('child-operation'),\n settled: Deferred.await(result).pipe(Effect.asVoid),\n ...(parentSessionId === undefined ? {} : { parentSessionId }),\n };\n yield* restore(operationGate.take(1));\n const fiber = yield* Effect.gen(function* () {\n yield* assertReady;\n if (\n admission === 'execution' &&\n parentSessionId !== undefined &&\n (yield* Ref.get(releasedParents)).has(parentSessionId)\n ) {\n return yield* Effect.fail(managerClosing());\n }\n yield* Ref.update(operationOwners, (current) => {\n const next = new Map(current);\n next.set(identity.id, identity);\n return next;\n });\n const owned = yield* FiberMap.run(\n operations,\n identity.id,\n Effect.exit(restore(operation))\n );\n yield* Effect.sync(() => {\n // One exit observer feeds all waiters. rc.110 can skip a later Fiber.join\n // observer when an earlier join disposes itself during exit notification.\n owned.addObserver((exit) => {\n Effect.runSync(\n Ref.update(operationOwners, (current) => {\n const next = new Map(current);\n next.delete(identity.id);\n return next;\n })\n );\n const outcome: Exit.Exit<A, E> = Exit.isSuccess(exit)\n ? exit.value\n : Exit.failCause(exit.cause);\n Deferred.doneUnsafe(result, Exit.succeed(outcome));\n });\n });\n return owned;\n }).pipe(Effect.ensuring(operationGate.release(1)));\n const exit = yield* restore(Deferred.await(result)).pipe(\n Effect.onInterrupt(() =>\n Effect.sync(() => fiber.interruptUnsafe()).pipe(Effect.andThen(identity.settled))\n )\n );\n return yield* exit;\n })\n );\n });\n\n const semaphoreFor = Effect.fn('ChildControl.semaphoreFor')(function* (\n parentSessionId: string,\n agentId: string\n ) {\n const key = childControlKey(parentSessionId, agentId);\n const existing = (yield* Ref.get(childPermits)).get(key);\n if (existing !== undefined) return existing;\n const created = yield* Semaphore.make(1);\n return yield* Ref.modify(childPermits, (current) => {\n const winner = current.get(key);\n if (winner !== undefined) return [winner, current] as const;\n const next = new Map(current);\n next.set(key, created);\n return [created, next] as const;\n });\n });\n\n const interruptParent = Effect.fn('ChildControl.interruptParent')(function* (\n parentSessionId: string\n ) {\n const identities = yield* Semaphore.withPermit(\n operationGate,\n Ref.updateAndGet(releasedParents, (current) => {\n const next = new Set(current);\n next.add(parentSessionId);\n return next;\n }).pipe(\n Effect.andThen(Ref.get(operationOwners)),\n Effect.map((current) =>\n [...current.values()].filter(\n (identity) => identity.parentSessionId === parentSessionId\n )\n )\n )\n );\n yield* Effect.sync(() => {\n for (const identity of identities) {\n const fiber = FiberMap.getUnsafe(operations, identity.id);\n if (Option.isSome(fiber)) fiber.value.interruptUnsafe();\n }\n });\n yield* Effect.forEach(identities, (identity) => identity.settled, {\n concurrency: 'unbounded',\n discard: true,\n });\n });\n\n return ChildControl.of({\n admit,\n // Host close holds durable ownership but must leave execution fenced.\n admitClose: (parentSessionId, operation) => admit(parentSessionId, operation, 'close'),\n activateParent: (parentSessionId) =>\n Semaphore.withPermit(\n operationGate,\n assertReady.pipe(\n Effect.andThen(\n Ref.update(releasedParents, (current) => {\n const next = new Set(current);\n next.delete(parentSessionId);\n return next;\n })\n )\n )\n ),\n interruptParent,\n beginClose: Semaphore.withPermit(\n operationGate,\n Ref.modify(health, (current) =>\n current === 'closed' ? ([false, current] as const) : ([true, 'closing'] as const)\n )\n ),\n finishClose: Ref.set(health, 'closed'),\n awaitOperations: FiberMap.awaitEmpty(operations),\n withChildPermit: (parentSessionId, agentId, effect) =>\n semaphoreFor(parentSessionId, agentId).pipe(\n Effect.flatMap((semaphore) => Semaphore.withPermit(semaphore, effect))\n ),\n });\n })\n );\n}\n","import toError from 'ensure-error';\nimport * as Effect from 'effect/Effect';\nimport type * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport { ChildControl } from './service.js';\n\nexport type ChildControlOperation<A> = (signal: AbortSignal) => PromiseLike<A>;\n\n/**\n * Signals Promise cancellation on interruption, then keeps the fiber alive\n * until that same Promise settles. Child close and delivery replacement rely\n * on this stronger abort-and-drain contract; ordinary interruptible Session\n * ports only signal cancellation and stop awaiting.\n */\nconst operationEffect = <A>(\n span: string,\n operation: ChildControlOperation<A>\n): Effect.Effect<A, Error> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const controller = new AbortController();\n const result = Promise.resolve().then(() => operation(controller.signal));\n const awaitResult = Effect.tryPromise({ try: () => result, catch: toError });\n return yield* restore(awaitResult).pipe(\n Effect.onInterrupt(() =>\n Effect.sync(() => controller.abort()).pipe(Effect.andThen(awaitResult), Effect.ignore)\n )\n );\n })\n ).pipe(Effect.withSpan(span));\n\n/** Promise-facing boundary for the Effect-owned child control plane. */\nexport class ChildControlClient {\n readonly #runtime: ManagedRuntime.ManagedRuntime<ChildControl, never>;\n readonly #control: ChildControl['Service'];\n\n constructor(runtime: ManagedRuntime.ManagedRuntime<ChildControl, never>) {\n this.#runtime = runtime;\n this.#control = runtime.runSync(ChildControl);\n }\n\n admit<A>(\n parentSessionId: string | undefined,\n operationName: string,\n operation: ChildControlOperation<A>,\n signal?: AbortSignal\n ): Promise<A> {\n return this.#runtime.runPromise(\n this.#control.admit(\n parentSessionId,\n operationEffect(`ChildOperation.${operationName}`, operation)\n ),\n signal === undefined ? undefined : { signal }\n );\n }\n\n activateParent(parentSessionId: string): Promise<void> {\n return this.#runtime.runPromise(this.#control.activateParent(parentSessionId));\n }\n\n admitClose<A>(\n parentSessionId: string,\n operationName: string,\n operation: ChildControlOperation<A>\n ): Promise<A> {\n return this.#runtime.runPromise(\n this.#control.admitClose(\n parentSessionId,\n operationEffect(`ChildOperation.${operationName}`, operation)\n )\n );\n }\n\n interruptParent(parentSessionId: string): Promise<void> {\n return this.#runtime.runPromise(this.#control.interruptParent(parentSessionId));\n }\n\n withChildPermit<A>(\n parentSessionId: string,\n agentId: string,\n operationName: string,\n operation: ChildControlOperation<A>,\n signal?: AbortSignal\n ): Promise<A> {\n return this.#runtime.runPromise(\n this.#control.withChildPermit(\n parentSessionId,\n agentId,\n operationEffect(`ChildPermit.${operationName}`, operation)\n ),\n signal === undefined ? undefined : { signal }\n );\n }\n\n waitFor(\n operationName: string,\n operations: readonly ChildControlOperation<void>[],\n condition: 'any' | 'all',\n signal?: AbortSignal,\n timeoutMs?: number\n ): Promise<'terminal' | 'timeout'> {\n return this.#runtime.runPromise(\n this.#waitForEffect(operationName, operations, condition, timeoutMs),\n signal === undefined ? undefined : { signal }\n );\n }\n\n async close(\n parentSessionIds: readonly string[],\n releaseParent: (id: string) => Promise<void>\n ): Promise<void> {\n const started = await this.#runtime.runPromise(this.#control.beginClose);\n if (!started) return;\n const failures: Error[] = [];\n const collect = async (operation: PromiseLike<void>): Promise<void> => {\n try {\n await operation;\n } catch (cause) {\n failures.push(toError(cause));\n }\n };\n const releaseParents = async (): Promise<void> => {\n const results = await Promise.allSettled(\n parentSessionIds.map((parentSessionId) =>\n Promise.resolve().then(() => releaseParent(parentSessionId))\n )\n );\n for (const result of results) {\n if (result.status === 'rejected') failures.push(toError(result.reason));\n }\n };\n await releaseParents();\n await collect(this.#runtime.runPromise(this.#control.awaitOperations));\n await releaseParents();\n if (failures.length > 0) throw new AggregateError(failures, 'Child agent shutdown failed');\n await this.#runtime.runPromise(this.#control.finishClose);\n }\n\n dispose(): Promise<void> {\n return this.#runtime.dispose();\n }\n\n readonly #waitForEffect = Effect.fn('ChildControlClient.waitFor')(function* (\n operationName: string,\n operations: readonly ChildControlOperation<void>[],\n condition: 'any' | 'all',\n timeoutMs: number | undefined\n ) {\n const waits = operations.map((operation) =>\n operationEffect(`ChildWait.${operationName}`, operation)\n );\n const terminal = (\n condition === 'any'\n ? Effect.raceAllFirst(waits)\n : Effect.all(waits, { concurrency: 'unbounded', discard: true })\n ).pipe(Effect.as('terminal' as const));\n if (timeoutMs === undefined) return yield* terminal;\n return yield* Effect.raceFirst(\n terminal,\n Effect.sleep(timeoutMs).pipe(Effect.as('timeout' as const))\n );\n });\n}\n","import type { Usage } from '@sorbetai/context';\nimport type { RunInspection } from '@sorbetai/runtime';\nimport type { ChildModelUsageSnapshot } from './contracts.js';\n\n/** Journal-authoritative per-model rows, so a Host can account child spend by model. */\nexport function projectModelUsage(runs: readonly RunInspection[]): ChildModelUsageSnapshot {\n let committedResponses = 0;\n let activeRequests = 0;\n let unknownRequests = 0;\n let totalTokens = 0;\n let costUsd = 0;\n const models = new Map<string, { provider: string; model: string; usage: Usage }>();\n for (const run of runs) {\n for (const request of run.modelRequests) {\n if (request.status === 'requested') {\n activeRequests += 1;\n continue;\n }\n if (request.status === 'unknown') {\n unknownRequests += 1;\n continue;\n }\n committedResponses += 1;\n const message = request.response.payload.message;\n totalTokens += message.usage.totalTokens;\n costUsd += message.usage.cost.total;\n addModelUsage(models, message.provider, message.model, message.usage);\n }\n }\n return {\n committedResponses,\n activeRequests,\n unknownRequests,\n totalTokens,\n costUsd,\n models: [...models.values()],\n };\n}\n\nexport function addModelUsage(\n models: Map<string, { provider: string; model: string; usage: Usage }>,\n provider: string,\n model: string,\n usage: Usage\n): void {\n const key = JSON.stringify([provider, model]);\n const current = models.get(key);\n if (current === undefined) {\n models.set(key, { provider, model, usage: structuredClone(usage) });\n return;\n }\n addUsage(current.usage, usage);\n}\n\nexport function addUsage(target: Usage, usage: Usage): void {\n target.input += usage.input;\n target.output += usage.output;\n target.cacheRead += usage.cacheRead;\n target.cacheWrite += usage.cacheWrite;\n target.totalTokens += usage.totalTokens;\n if (usage.cacheWrite1h !== undefined)\n target.cacheWrite1h = (target.cacheWrite1h ?? 0) + usage.cacheWrite1h;\n if (usage.reasoning !== undefined) target.reasoning = (target.reasoning ?? 0) + usage.reasoning;\n target.cost.input += usage.cost.input;\n target.cost.output += usage.cost.output;\n target.cost.cacheRead += usage.cost.cacheRead;\n target.cost.cacheWrite += usage.cost.cacheWrite;\n target.cost.total += usage.cost.total;\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { ApprovalModeSchema, ToolPermissionPolicySchema } from '@sorbetai/runtime';\nimport { ChildAgentDescriptionSchema, ChildAgentNameSchema } from './contracts.js';\n\n/** Applied to the child's first Run. Open: hosts persist their own fields, such as a sandbox mode. */\nexport const ChildExecutionPolicySchema = s.obj(\n {\n toolPermissions: ToolPermissionPolicySchema,\n approvalMode: s.opt(ApprovalModeSchema),\n },\n { open: true }\n);\nexport type ChildExecutionPolicy = Readonly<s.Static<typeof ChildExecutionPolicySchema>>;\n\nconst Identity = s.str({ minLength: 1 });\n/** Immutable imported receipts; ongoing delivery is owned only by Unit Submissions. */\nexport const ImportedChildDeliverySchema = s.obj(\n {\n deliveryId: Identity,\n orderingKey: s.int({ minimum: 1 }),\n direction: s.union([s.lit('to_child'), s.lit('to_parent')]),\n sourceSessionId: Identity,\n sourceRunId: Identity,\n state: s.union([s.lit('pending'), s.lit('complete'), s.lit('cancelled')]),\n enqueuedAt: s.opt(s.str()),\n dispatchedAt: s.opt(s.str()),\n acceptedAt: s.opt(s.str()),\n acceptedRunId: s.opt(Identity),\n acceptedSessionId: s.opt(Identity),\n acceptedFactId: s.opt(Identity),\n acceptedMessageId: s.opt(Identity),\n acceptedCursor: s.opt(Identity),\n includedAt: s.opt(s.str()),\n includedModelRequestId: s.opt(Identity),\n includedSessionId: s.opt(Identity),\n includedFactId: s.opt(Identity),\n includedCursor: s.opt(Identity),\n },\n { open: true }\n);\nexport const ChildTaskInputSchema = s.obj(\n {\n agentId: Identity,\n childSessionId: Identity,\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n parentSessionId: Identity,\n parentRunId: Identity,\n spawnToolCallId: Identity,\n spawnEffectAttemptId: Identity,\n depth: s.lit(1),\n providerId: Identity,\n modelId: Identity,\n executionPolicy: ChildExecutionPolicySchema,\n ordinaryToolNames: s.arr(Identity, { uniqueItems: true }),\n initialMode: s.union([s.lit('foreground'), s.lit('background')]),\n initialCompletionDelivery: s.union([s.lit('auto'), s.lit('manual')]),\n /** Legacy children recorded a full context fork; decoding must keep accepting it. */\n contextMode: s.union([s.lit('fresh'), s.lit('full')]),\n createdAt: s.str({ format: 'date-time' }),\n initialSubmissionId: s.opt(Identity),\n imported: s.opt(\n s.obj(\n {\n initialRunId: s.opt(Identity),\n orderingKeyFloor: s.int({ minimum: 0 }),\n deliveries: s.arr(ImportedChildDeliverySchema),\n },\n { open: true }\n )\n ),\n },\n { open: true }\n);\nexport type ChildTaskInput = s.Static<typeof ChildTaskInputSchema>;\n","import * as s from '@earendil-works/pi-schema';\nimport { decode } from '@sorbetai/schema';\nimport { isEqual } from 'es-toolkit';\nimport {\n defineTask,\n projectSessionInspection,\n type UnitRuntime,\n type UnitTx,\n} from '@sorbetai/runtime';\n\nimport { ClosedChildUsageSchema } from './contracts.js';\nimport { ChildTaskInputSchema, type ChildTaskInput } from './record.js';\nimport { projectModelUsage } from './usage.js';\n\n// The persisted v1 phase is named 'closing' even while waiting for the close\n// request. Only session.closing fences new input; this checkpoint holds signals.\nconst CloseSignals = s.obj(\n {\n phase: s.lit('closing'),\n close: s.str(),\n released: s.str(),\n },\n { open: true }\n);\nconst Checkpoint = s.union([s.obj({ phase: s.lit('open') }, { open: true }), CloseSignals]);\n\nfunction waitForCloseRequest(tx: UnitTx) {\n const close = tx.createSignal({ key: 'close', type: 'host-command', payload: null });\n const released = tx.createSignal({ key: 'released', type: 'host-command', payload: null });\n return {\n status: 'waiting' as const,\n checkpoint: { phase: 'closing' as const, close, released },\n on: [{ signal: close }],\n policy: 'allSettled' as const,\n };\n}\n\n/** The Host handles close intent and confirms resource release; phases perform no resource I/O. */\nexport const childTaskDefinition = defineTask({\n name: 'sorbet.agent',\n version: 1,\n inputSchema: ChildTaskInputSchema,\n checkpointSchema: Checkpoint,\n resultSchema: ClosedChildUsageSchema,\n initial: () => ({ phase: 'open' as const }),\n phases: {\n open: async (_task, runtime) => {\n await runtime.commit(waitForCloseRequest);\n },\n closing: async (task, runtime) => {\n await runtime.commit((tx) => {\n const close = tx.signal(task.checkpoint.close);\n if (close?.state.status !== 'resolved') throw new Error('Child close was not requested');\n const released = tx.signal(task.checkpoint.released);\n if (released?.state.status !== 'resolved')\n return {\n status: 'waiting',\n checkpoint: task.checkpoint,\n on: [{ signal: task.checkpoint.released }],\n policy: 'allSettled',\n };\n const result = decode(ClosedChildUsageSchema, released.state.result);\n tx.closeSession(task.input.childSessionId);\n return { status: 'completed', result };\n });\n },\n },\n abort: async (task, runtime) => {\n await runtime.commit(() => ({\n status: 'aborted',\n reason: task.abortRequested?.reason ?? 'Child observation stopped',\n }));\n },\n});\n\n/** Fence placement in the same commit as close intent; cleanup can continue after a crash. */\nexport function stageChildClose(\n tx: UnitTx,\n anchorId: string,\n reason: string,\n commandId: string\n): void {\n const task = tx.getTask(anchorId);\n if (task?.kind !== childTaskDefinition.name) throw new Error('Child anchor is missing');\n const child = decode(ChildTaskInputSchema, task.input);\n tx.beginSessionClose(child.childSessionId);\n if (task.state.status === 'terminal') return;\n const checkpoint = decode(CloseSignals, task.checkpoint);\n if (tx.signal(checkpoint.close)?.state.status === 'resolved') return;\n tx.resolveSignal(checkpoint.close, reason, commandId);\n}\n\n/** Also used by the offline importer for already-created Sessions; it never starts a Run. */\nexport function stageChildAnchor(tx: UnitTx, child: ChildTaskInput): string {\n return tx.createTask(childTaskDefinition, child, {\n key: `spawn:${child.spawnEffectAttemptId}`,\n owner: { session: child.parentSessionId },\n background: true,\n initialize: waitForCloseRequest,\n });\n}\n\n/** Finish committed close intent without constructing a Session, Provider or Tool. */\nexport async function finishChildClose(\n unit: UnitRuntime,\n sessionId: string,\n release: () => Promise<void>,\n signal: AbortSignal\n): Promise<void> {\n signal.throwIfAborted();\n const session = unit.sessions().find((entry) => entry.sessionId === sessionId);\n if (session?.closed) return;\n if (!session?.closing) throw new Error('Child close intent is missing');\n const anchor = unit\n .inspect()\n .tasks.find(\n (task) =>\n task.kind === childTaskDefinition.name &&\n decode(ChildTaskInputSchema, task.input).childSessionId === sessionId\n );\n if (anchor === undefined) throw new Error('Closing child has no Task anchor');\n const reason = 'Child Session closed';\n const owned = unit\n .inspect()\n .tasks.filter(\n (task) => task.state.status !== 'terminal' && isEqual(task.owner, { session: sessionId })\n );\n // Stop delivery/schedule phases before resource disposal can publish process exit.\n // The anchor belongs to the parent and stays alive to commit final closure.\n for (const task of owned) await unit.abortTask(task.taskId, reason, anchor.taskId);\n await release();\n signal.throwIfAborted();\n const facts = await unit.participant(sessionId);\n const interrupted = await facts.unfinishedRun();\n if (interrupted !== undefined) await facts.abandonInterruptedRun(interrupted.runId, reason);\n for (const pending of await facts.pendingSubmissions())\n await (\n await unit.submission(pending.accepted.operationId)\n )?.withdraw({\n reason,\n commandId: `child-close:${anchor.taskId}:${pending.accepted.operationId}`,\n });\n for (const task of owned) await unit.task(task.taskId)?.settled(signal);\n const handle = unit.task(anchor.taskId);\n if (handle === undefined) throw new Error('Child anchor disappeared');\n if (handle.record().abortRequested !== undefined) await handle.settled(signal);\n if (handle.record().state.status === 'terminal') {\n await unit.closeSession(sessionId);\n return;\n }\n const checkpoint = decode(childTaskDefinition.checkpointSchema, handle.record().checkpoint);\n if (checkpoint.phase !== 'closing') throw new Error('Child close was not initialized');\n const history = await facts.journalSnapshot();\n const { runs } = projectSessionInspection(\n sessionId,\n { facts: history, cursor: history.at(-1)?.cursor, hasMore: false },\n { modelRequests: 'omit' }\n );\n const latest = runs.at(-1);\n await unit.group((group) =>\n group.tasks((tx) => {\n const current = tx.getTask(anchor.taskId);\n if (current === undefined) throw new Error('Child anchor disappeared');\n if (current.state.status === 'terminal' || current.abortRequested !== undefined) return;\n tx.resolveSignal(\n checkpoint.released,\n {\n ...(latest === undefined ? {} : { throughRunId: latest.lifecycle.runId }),\n modelUsage: projectModelUsage(runs),\n },\n `child-released:${anchor.taskId}`\n );\n })\n );\n // Observation may be aborted while cleanup drains. It cannot revoke close intent.\n const outcome = await handle.settled(signal);\n if (outcome.status !== 'completed') await unit.closeSession(sessionId);\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { check, decode } from '@sorbetai/schema';\nimport {\n isRunTerminalFactKind,\n RunInputProjection,\n type JournalFact,\n type UnitRecord,\n} from '@sorbetai/runtime';\nimport { cloneDeep } from 'es-toolkit';\nimport { CompletionStateSchema } from './completion-state.js';\nexport { CompletionStateSchema } from './completion-state.js';\n\nimport type {\n ChildDeliveryObservation,\n ChildDeliveryPage,\n ChildSpawnObservation,\n} from './telemetry-port.js';\nimport { childTaskDefinition } from './close.js';\nimport { ClosedChildUsageSchema, type ClosedChildUsage } from './contracts.js';\nimport { ChildTaskInputSchema, type ChildTaskInput } from './record.js';\n\nexport interface ChildAgentEntry extends ChildTaskInput {\n readonly anchorId: string;\n readonly initialRunId?: string;\n readonly closing: boolean;\n readonly closed: boolean;\n readonly closedUsage?: ClosedChildUsage;\n}\n\nconst Completion = s.obj(\n {\n agentId: s.str(),\n childSessionId: s.str(),\n childRunId: s.str(),\n },\n { open: true }\n);\nconst ParentInput = s.obj(\n {\n agentId: s.str(),\n parentSessionId: s.str(),\n parentRunId: s.str(),\n },\n { open: true }\n);\nconst TeamInput = s.obj(\n {\n recipientAgentId: s.str(),\n senderSessionId: s.str(),\n senderRunId: s.str(),\n },\n { open: true }\n);\ntype Delivery = ChildDeliveryPage['deliveries'][number];\n\ntype Observation =\n | { kind: 'spawn'; data: ChildSpawnObservation }\n | { kind: 'delivery'; data: ChildDeliveryObservation };\n\n/** Rebuildable facts only. The owning catalog drops this projection with the writer epoch. */\nexport class ChildProjection {\n readonly #inputs = new Map<string, RunInputProjection>();\n readonly anchors = new Map<string, ChildTaskInput>();\n readonly closed = new Set<string>();\n readonly closing = new Set<string>();\n readonly usages = new Map<string, ClosedChildUsage>();\n readonly deliveries = new Map<string, Delivery>();\n readonly messages = new Map<string, string>();\n readonly placements = new Map<string, string>();\n readonly activeRuns = new Map<string, string>();\n readonly completions = new Map<string, { agentId: string; runId: string; cursor: number }>();\n readonly observations: { sequence: number; event: Observation }[] = [];\n orderingKeyFloor = 0;\n\n constructor(\n readonly parentSessionId: string,\n readonly observeAfter: number\n ) {}\n\n apply(record: UnitRecord): void {\n const {\n anchors,\n closed,\n closing,\n usages,\n deliveries,\n messages,\n placements,\n activeRuns,\n completions,\n parentSessionId,\n } = this;\n const observeDelivery = (\n sequence: number,\n delivery: Delivery,\n transition: ChildDeliveryObservation['transition']\n ) => {\n this.observe(sequence, { kind: 'delivery', data: { ...delivery, transition } });\n };\n const { entry } = record;\n if (entry.scope === 'unit') {\n const fact = entry.fact;\n switch (fact.kind) {\n case 'task.created':\n case 'task.imported':\n if (fact.payload.kind === childTaskDefinition.name) {\n const child = decode(ChildTaskInputSchema, fact.payload.input);\n anchors.set(fact.taskId, child);\n this.orderingKeyFloor = Math.max(\n this.orderingKeyFloor,\n child.imported?.orderingKeyFloor ?? 0\n );\n for (const delivery of child.imported?.deliveries ?? []) {\n const { acceptedMessageId, ...fields } = delivery;\n if (acceptedMessageId !== undefined)\n messages.set(acceptedMessageId, delivery.deliveryId);\n const receipt = {\n ...fields,\n agentId: child.agentId,\n childSessionId: child.childSessionId,\n parentSessionId,\n };\n deliveries.set(delivery.deliveryId, receipt);\n if (delivery.direction === 'to_parent')\n completions.set(delivery.deliveryId, {\n agentId: child.agentId,\n runId: delivery.sourceRunId,\n cursor: delivery.orderingKey,\n });\n }\n this.observe(record.unitSequence, {\n kind: 'spawn',\n data: {\n parentSessionId: child.parentSessionId,\n parentRunId: child.parentRunId,\n childSessionId: child.childSessionId,\n agentId: child.agentId,\n toolCallId: child.spawnToolCallId,\n effectAttemptId: child.spawnEffectAttemptId,\n },\n });\n if (fact.kind === 'task.imported')\n usages.set(fact.taskId, decode(ClosedChildUsageSchema, fact.payload.result));\n }\n break;\n case 'task.settled':\n if (anchors.has(fact.taskId) && fact.payload.outcome.status === 'completed')\n usages.set(fact.taskId, decode(ClosedChildUsageSchema, fact.payload.outcome.result));\n break;\n case 'session.closing':\n closing.add(fact.payload.sessionId);\n break;\n case 'session.closed':\n closed.add(fact.payload.sessionId);\n closing.delete(fact.payload.sessionId);\n break;\n }\n return;\n }\n const fact = entry.fact;\n if (fact.kind === 'run.accepted') activeRuns.set(fact.runId, fact.sessionId);\n if (isRunTerminalFactKind(fact.kind) && fact.runId !== undefined) activeRuns.delete(fact.runId);\n if (fact.kind === 'submission.accepted') {\n const { input } = fact.payload;\n const base = {\n parentSessionId,\n deliveryId: fact.operationId,\n orderingKey:\n deliveries.get(fact.operationId)?.orderingKey ??\n record.unitSequence + this.orderingKeyFloor,\n state: 'pending' as const,\n enqueuedAt: fact.recordedAt,\n ...deliveries.get(fact.operationId),\n };\n // SDK hosts own Submission provenance. A matching label alone is not a child receipt.\n if (\n input.source.kind === 'node-agent.child-completion' &&\n fact.sessionId === parentSessionId &&\n check(Completion, input.source.data)\n ) {\n const data = input.source.data;\n deliveries.set(fact.operationId, {\n ...base,\n direction: 'to_parent',\n agentId: data.agentId,\n childSessionId: data.childSessionId,\n sourceSessionId: data.childSessionId,\n sourceRunId: data.childRunId,\n });\n completions.set(fact.operationId, {\n agentId: data.agentId,\n runId: data.childRunId,\n cursor: base.orderingKey,\n });\n } else if (\n input.source.kind === 'node-agent.parent-input' &&\n check(ParentInput, input.source.data)\n ) {\n const data = input.source.data;\n if (data.parentSessionId === parentSessionId)\n deliveries.set(fact.operationId, {\n ...base,\n direction: 'to_child',\n agentId: data.agentId,\n childSessionId: fact.sessionId,\n sourceSessionId: data.parentSessionId,\n sourceRunId: data.parentRunId,\n });\n } else if (\n input.source.kind === 'node-agent.team-message' &&\n check(TeamInput, input.source.data)\n ) {\n const data = input.source.data;\n deliveries.set(fact.operationId, {\n ...base,\n direction: 'to_child',\n agentId: data.recipientAgentId,\n childSessionId: fact.sessionId,\n sourceSessionId: data.senderSessionId,\n sourceRunId: data.senderRunId,\n });\n }\n }\n if (fact.kind === 'submission.accepted') {\n const delivery = deliveries.get(fact.operationId);\n if (delivery !== undefined) observeDelivery(record.unitSequence, delivery, 'enqueued');\n }\n const inputs = this.#inputs.get(fact.sessionId) ?? new RunInputProjection();\n this.#inputs.set(fact.sessionId, inputs);\n const input = inputs.apply(fact);\n if (input !== undefined) {\n const deliveryId = input.payload.deliveryId;\n if (\n deliveryId !== undefined &&\n [...anchors.values()].some((child) => child.initialSubmissionId === deliveryId)\n )\n placements.set(deliveryId, input.runId);\n const previous = deliveryId === undefined ? undefined : deliveries.get(deliveryId);\n if (previous !== undefined) {\n deliveries.set(previous.deliveryId, {\n ...previous,\n state: 'complete',\n acceptedAt: input.recordedAt,\n acceptedRunId: input.runId,\n acceptedSessionId: input.sessionId,\n acceptedFactId: input.id,\n acceptedCursor: input.cursor,\n });\n const accepted = deliveries.get(previous.deliveryId);\n if (accepted !== undefined) {\n observeDelivery(record.unitSequence, accepted, 'accepted');\n observeDelivery(record.unitSequence, accepted, 'completed');\n }\n messages.set(input.payload.messageId, previous.deliveryId);\n }\n }\n if (fact.kind === 'submission.withdrawn') {\n const previous = deliveries.get(fact.operationId);\n if (previous !== undefined) {\n const cancelled = { ...previous, state: 'cancelled' as const };\n deliveries.set(fact.operationId, cancelled);\n observeDelivery(record.unitSequence, cancelled, 'cancelled');\n }\n }\n if (fact.kind === 'model.requested') {\n for (const source of fact.payload.conversationSources ?? []) {\n if (source.kind !== 'conversation') continue;\n const id = messages.get(source.reference.messageId);\n const included = id === undefined ? undefined : include(deliveries, id, fact);\n if (included !== undefined) observeDelivery(record.unitSequence, included, 'included');\n }\n if (fact.sessionId !== parentSessionId) return;\n const state = fact.payload.contextSnapshot.namedStates.find(\n (item) => item.stateName === 'child_runs'\n );\n if (state?.present === true && check(CompletionStateSchema, state.value)) {\n for (const result of state.value.results) {\n const included = include(deliveries, `to-parent-${result.agentId}-${result.runId}`, fact);\n if (included !== undefined) observeDelivery(record.unitSequence, included, 'included');\n }\n }\n }\n }\n\n snapshot(tail: number, afterSequence: number) {\n const { anchors, closed, closing, usages, placements, activeRuns, completions, deliveries } =\n this;\n if (Number.isFinite(afterSequence)) {\n const first = this.observations.findIndex((item) => item.sequence > afterSequence);\n this.observations.splice(0, first < 0 ? this.observations.length : first);\n }\n return cloneDeep({\n children: [...anchors].map(([anchorId, input]): ChildAgentEntry => ({\n ...input,\n anchorId,\n initialRunId:\n input.initialSubmissionId === undefined\n ? input.imported?.initialRunId\n : placements.get(input.initialSubmissionId),\n closing: closing.has(input.childSessionId),\n closed: closed.has(input.childSessionId),\n closedUsage: usages.get(anchorId),\n })),\n observations: this.observations\n .filter((item) => item.sequence > afterSequence)\n .map((item) => item.event),\n observedUnitSequence: tail,\n activeChildren: [...anchors.values()].filter((child) =>\n [...activeRuns.values()].includes(child.childSessionId)\n ).length,\n completions: [...completions.values()].sort((left, right) => left.cursor - right.cursor),\n deliveries: [...deliveries.values()].sort(\n (left, right) => left.orderingKey - right.orderingKey\n ),\n });\n }\n\n private observe(sequence: number, event: Observation): void {\n if (sequence > this.observeAfter) this.observations.push({ sequence, event });\n }\n}\n\nfunction include(\n deliveries: Map<string, Delivery>,\n id: string,\n fact: Extract<JournalFact, { kind: 'model.requested' }>\n): Delivery | undefined {\n const previous = deliveries.get(id);\n if (previous === undefined || previous.includedFactId !== undefined) return;\n const included = {\n ...previous,\n includedAt: fact.recordedAt,\n includedModelRequestId: fact.payload.modelRequestId,\n includedFactId: fact.id,\n includedCursor: fact.cursor,\n includedSessionId: fact.sessionId,\n };\n deliveries.set(id, included);\n return included;\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { defineTask, type UnitTx } from '@sorbetai/runtime';\n\nimport type { ChildTaskInput } from './record.js';\n\nconst Identity = s.str({ minLength: 1 });\nconst ReporterIdentity = { agentId: Identity, childSessionId: Identity, parentSessionId: Identity };\nconst ReporterInput = s.union([\n s.obj(\n {\n ...ReporterIdentity,\n kind: s.opt(s.lit('submission')),\n submissionId: Identity,\n },\n { open: true }\n ),\n s.obj({ ...ReporterIdentity, kind: s.lit('legacy-run'), legacyRunId: Identity }, { open: true }),\n]);\nconst Report = s.obj({ phase: s.lit('report') }, { open: true });\n\n/** Submission settlement, completion acceptance and reporter settlement use durable identities. */\nexport const childReporterDefinition = defineTask({\n name: 'sorbet.agent.reporter',\n version: 1,\n inputSchema: ReporterInput,\n checkpointSchema: Report,\n resultSchema: s.obj(\n {\n runId: s.opt(s.str()),\n deliveryId: s.opt(s.str()),\n },\n { open: true }\n ),\n initial: () => ({ phase: 'report' as const }),\n phases: {\n report: async (task, runtime) => {\n await runtime.commit(\n (tx) => {\n const target =\n task.input.kind !== 'legacy-run'\n ? tx.submission(task.input.submissionId)\n : tx.run(task.input.legacyRunId);\n if (target === undefined) throw new Error('Child input or imported Run is missing');\n if (!target.ended)\n return {\n status: 'waiting',\n checkpoint: task.checkpoint,\n on: [\n task.input.kind !== 'legacy-run'\n ? { submission: task.input.submissionId }\n : { run: task.input.legacyRunId },\n ],\n policy: 'allSettled',\n };\n const runId =\n task.input.kind !== 'legacy-run'\n ? tx.submission(task.input.submissionId)?.runId\n : task.input.legacyRunId;\n if (runId === undefined) return { status: 'completed', result: {} };\n const deliveryId = `to-parent-${task.input.agentId}-${runId}`;\n tx.submit(\n task.input.parentSessionId,\n {\n kind: 'context-event',\n deliveryId,\n contextSources: [],\n source: {\n kind: 'node-agent.child-completion',\n data: {\n agentId: task.input.agentId,\n childSessionId: task.input.childSessionId,\n childRunId: runId,\n completionDeliveryId: deliveryId,\n },\n },\n },\n { whenBusy: 'followUp', preserveSource: true }\n );\n return { status: 'completed', result: { runId, deliveryId } };\n },\n { sessions: [task.input.parentSessionId] }\n );\n },\n },\n abort: async (task, runtime) => {\n await runtime.commit(() => ({\n status: 'aborted',\n reason: task.abortRequested?.reason ?? 'Child completion stopped',\n }));\n },\n});\n\n/** Call in the same group that accepts the child input, when automatic delivery is enabled. */\nexport function stageChildReporter(\n tx: UnitTx,\n anchorId: string,\n input: s.Static<typeof ReporterInput>\n): string {\n if (\n input.kind !== 'legacy-run' &&\n tx.submission(input.submissionId)?.sessionId !== input.childSessionId\n )\n throw new Error('Reporter Submission belongs to another child');\n return tx.createTask(childReporterDefinition, input, {\n key:\n input.kind !== 'legacy-run'\n ? `report:${input.submissionId}`\n : `report-run:${input.legacyRunId}`,\n owner: { task: anchorId },\n background: true,\n initialize: () => ({\n status: 'waiting',\n checkpoint: { phase: 'report' as const },\n on: [\n input.kind !== 'legacy-run'\n ? { submission: input.submissionId }\n : { run: input.legacyRunId },\n ],\n policy: 'allSettled',\n }),\n });\n}\n\n/**\n * Input acceptance and its completion reporter share one commit. Manual children\n * never create reporters. Foreground children omit the initial reporter.\n * Initial placement also records the child's execution policy.\n */\nexport function stageChildInput(\n tx: UnitTx,\n child: ChildTaskInput,\n anchorId: string,\n input: Parameters<UnitTx['submit']>[1],\n options: {\n readonly initial?: boolean;\n } = {}\n): void {\n const runConfiguration = options.initial\n ? {\n toolPermissionPolicy: child.executionPolicy.toolPermissions,\n approvalMode: child.executionPolicy.approvalMode,\n }\n : undefined;\n // Child input steers like any other Session input: it lands at the next Tool boundary of a\n // running child and starts a Run when the child is idle.\n tx.submit(child.childSessionId, input, {\n whenBusy: 'steer',\n preserveSource: true,\n runConfiguration,\n });\n if (\n child.initialCompletionDelivery === 'auto' &&\n (!options.initial || child.initialMode === 'background')\n )\n stageChildReporter(tx, anchorId, {\n agentId: child.agentId,\n childSessionId: child.childSessionId,\n parentSessionId: child.parentSessionId,\n submissionId: input.deliveryId,\n });\n}\n","import { addModelUsage, projectModelUsage } from './usage.js';\nimport { isRunTerminalFactKind, type SessionInspection } from '@sorbetai/runtime';\nimport type { NamedStateOwner, Usage } from '@sorbetai/context';\nimport type { ChildAgentEntry, ChildAgentCatalog } from './catalog.js';\nimport { CompletionStateSchema } from './projection.js';\nimport { childReporterDefinition } from './completion.js';\nimport { decode } from '@sorbetai/schema';\nimport type { UnitRuntime, WaitMember } from '@sorbetai/runtime';\n\nimport {\n ChildAgentError,\n type ChildAgentSnapshot,\n type ChildModelUsageSnapshot,\n type ClosedChildUsage,\n type ListAgentsOutput,\n} from './contracts.js';\nimport type { ChildControlClient } from './control/client.js';\nimport type { ChildAgentHost, ChildSessionRuntime } from './host.js';\nimport type { ChildOperation } from './operations.js';\n\nconst MAX_RESPONSE_CHARACTERS = 30_000;\n\nconst COMPLETION_STATE_LIMIT = 64;\n\ninterface ChildObservationCoordinatorOptions {\n readonly control: ChildControlClient;\n readonly catalog: ChildAgentCatalog;\n readonly host: ChildAgentHost;\n}\n\n/** Projects child state from Unit anchors and Session Journals without owning execution. */\nexport class ChildObservationCoordinator {\n readonly #options: ChildObservationCoordinatorOptions;\n\n constructor(options: ChildObservationCoordinatorOptions) {\n this.#options = options;\n }\n\n stateOwner(parentSessionId: string): NamedStateOwner<'child_runs', typeof CompletionStateSchema> {\n return {\n stateName: 'child_runs',\n schema: CompletionStateSchema,\n read: async ({ signal }) => {\n signal?.throwIfAborted();\n const state = await this.#completionState(parentSessionId);\n signal?.throwIfAborted();\n if (state.throughCompletion === 0) return { present: false };\n const results = state.results.slice(-COMPLETION_STATE_LIMIT);\n return {\n present: true,\n value: { ...state, results },\n element: {\n kind: 'container',\n name: 'child_runs',\n children: results.map(({ agentId, runId }) => ({\n kind: 'text',\n name: 'child_run',\n attributes: { agent: agentId, run: runId },\n text: '',\n })),\n },\n };\n },\n };\n }\n\n async listAgents(\n operation: ChildOperation & { readonly request: { readonly includeClosed?: boolean } }\n ): Promise<ListAgentsOutput> {\n return this.listAgentsForHost(operation.parentSessionId, operation.request.includeClosed);\n }\n\n async listAgentsForHost(\n parentSessionId: string,\n includeClosed?: boolean\n ): Promise<ListAgentsOutput> {\n const document = await this.#options.catalog.read(parentSessionId);\n const allAgents = await Promise.all(\n document.children.map((record) => this.snapshotRecord(record))\n );\n const agents = allAgents.filter((agent) => includeClosed === true || agent.state !== 'closed');\n return {\n agents,\n modelUsage: sumModelUsage(allAgents.map(({ modelUsage }) => modelUsage)),\n };\n }\n\n /**\n * The child of this parent whose Session ran `runId`. A child's initial Run is known from the\n * catalog; later Runs need its inspection, so only those scan the children.\n */\n async #findRun(parentSessionId: string, runId: string) {\n const { children } = await this.#options.catalog.read(parentSessionId);\n const initial = children.find((record) => record.initialRunId === runId);\n for (const record of initial === undefined ? children : [initial]) {\n const inspection = await this.#options.host.inspectChild(record);\n const runIndex = inspection.runs.findIndex((run) => run.lifecycle.runId === runId);\n if (runIndex !== -1) return { record, inspection, runIndex };\n }\n return undefined;\n }\n\n /**\n * A Reporter delivers an auto child's completion after the Run ends, in its own commit. Waiting\n * on the Reporter rather than the Run lets a wait withdraw that notification once it exists.\n * Manual and foreground Runs have no Reporter, so their Run is the member.\n */\n async waitMember(parentSessionId: string, runId: string): Promise<WaitMember | undefined> {\n const found = await this.#findRun(parentSessionId, runId);\n if (found === undefined) return undefined;\n const unit = this.#options.host.unit(parentSessionId);\n const reporters = unit\n .taskGraph({ sessionId: parentSessionId, kind: childReporterDefinition.name })\n .snapshot();\n for (const reporter of reporters) {\n const input = decode(childReporterDefinition.inputSchema, reporter.input);\n if (input.parentSessionId !== parentSessionId || input.agentId !== found.record.agentId)\n continue;\n const placed =\n input.kind === 'legacy-run'\n ? input.legacyRunId\n : await this.#placedRun(unit, input.submissionId);\n if (placed === runId) return { task: reporter.taskId };\n }\n return { run: runId };\n }\n\n /** A placed Submission never moves to another Run, so its Run is read once. */\n readonly #placedRuns = new Map<string, string>();\n async #placedRun(unit: UnitRuntime, submissionId: string): Promise<string | undefined> {\n const known = this.#placedRuns.get(submissionId);\n if (known !== undefined) return known;\n const runId = (await (await unit.submission(submissionId))?.status())?.placed?.runId;\n if (runId !== undefined) this.#placedRuns.set(submissionId, runId);\n return runId;\n }\n\n async describeRun(\n parentSessionId: string,\n runId: string\n ): Promise<ChildAgentSnapshot | undefined> {\n const found = await this.#findRun(parentSessionId, runId);\n return found === undefined\n ? undefined\n : this.#snapshotRun(found.record, found.inspection, found.runIndex);\n }\n\n async snapshotById(parentSessionId: string, agentId: string): Promise<ChildAgentSnapshot> {\n const record = await this.#options.catalog.record(parentSessionId, agentId);\n return this.snapshotRecord(record);\n }\n\n async snapshotRunById(\n parentSessionId: string,\n agentId: string,\n runId: string\n ): Promise<ChildAgentSnapshot> {\n const record = await this.#options.catalog.record(parentSessionId, agentId);\n const inspection = await this.#options.host.inspectChild(record);\n const runIndex = inspection.runs.findIndex((run) => run.lifecycle.runId === runId);\n if (runIndex === -1) {\n throw new ChildAgentError(\n 'child_run_not_found',\n 'Run does not belong to the requested child agent'\n );\n }\n return this.#snapshotRun(record, inspection, runIndex);\n }\n\n async getResult(\n operation: ChildOperation & {\n readonly agentId: string;\n readonly runId: string;\n readonly offset?: number;\n readonly limit?: number;\n }\n ): Promise<ChildAgentSnapshot> {\n operation.context.signal?.throwIfAborted();\n const snapshot = await this.snapshotRunById(\n operation.parentSessionId,\n operation.agentId,\n operation.runId\n );\n if (snapshot.response === undefined || snapshot.outcome?.kind !== 'completed') return snapshot;\n if (\n !snapshot.response.truncated &&\n operation.offset === undefined &&\n operation.limit === undefined\n )\n return snapshot;\n const record = await this.#options.catalog.record(operation.parentSessionId, operation.agentId);\n const inspection = await this.#options.host.inspectChild(record);\n const text = completedResponseText(inspection, snapshot.outcome.responseMessageId);\n if (text === undefined) throw new Error('Completed child response is missing');\n operation.context.signal?.throwIfAborted();\n const offset = Math.min(operation.offset ?? 0, text.length);\n const end = Math.min(offset + (operation.limit ?? MAX_RESPONSE_CHARACTERS), text.length);\n return {\n ...snapshot,\n response: {\n text: text.slice(offset, end),\n truncated: offset > 0 || end < text.length,\n offset,\n nextOffset: end < text.length ? end : undefined,\n },\n };\n }\n\n async listResults(\n operation: ChildOperation & { readonly after?: number; readonly limit?: number }\n ) {\n operation.context.signal?.throwIfAborted();\n const state = await this.#completionState(operation.parentSessionId);\n const available = state.results.filter((result) => result.cursor > (operation.after ?? 0));\n const page = available.slice(0, operation.limit ?? 32);\n return {\n results: page,\n nextCursor: available.length > page.length ? page.at(-1)?.cursor : undefined,\n };\n }\n\n async #completionState(parentSessionId: string) {\n const document = await this.#options.catalog.read(parentSessionId);\n return {\n throughCompletion: document.completions.at(-1)?.cursor ?? 0,\n resultCount: document.completions.length,\n results: document.completions,\n };\n }\n\n async snapshotRecord(record: ChildAgentEntry): Promise<ChildAgentSnapshot> {\n if (record.closed) {\n const closedUsage = record.closedUsage ?? (await this.#closedUsage(record));\n return {\n agentId: record.agentId,\n childSessionId: record.childSessionId,\n ...(record.name === undefined ? {} : { name: record.name }),\n ...(record.description === undefined ? {} : { description: record.description }),\n state: 'closed',\n modelUsage: closedUsage.modelUsage,\n };\n }\n const inspection = await this.#options.host.inspectChild(record);\n const runIndex = inspection.runs.length - 1;\n if (runIndex === -1) {\n return {\n agentId: record.agentId,\n childSessionId: record.childSessionId,\n ...(record.name === undefined ? {} : { name: record.name }),\n ...(record.description === undefined ? {} : { description: record.description }),\n state: 'starting',\n modelUsage: projectModelUsage(inspection.runs),\n };\n }\n return this.#snapshotRun(record, inspection, runIndex);\n }\n\n #snapshotRun(\n record: ChildAgentEntry,\n inspection: SessionInspection,\n runIndex: number\n ): ChildAgentSnapshot {\n const run = inspection.runs[runIndex];\n if (run === undefined) throw new Error('Child Run index is inconsistent');\n const modelUsage = projectModelUsage(inspection.runs);\n const outcome = run.lifecycle.outcome;\n if (outcome === undefined) {\n return {\n agentId: record.agentId,\n childSessionId: record.childSessionId,\n ...(record.name === undefined ? {} : { name: record.name }),\n ...(record.description === undefined ? {} : { description: record.description }),\n state: 'running',\n modelUsage,\n runId: run.lifecycle.runId,\n };\n }\n const state: ChildAgentSnapshot['state'] =\n outcome.kind === 'completed' ? 'completed' : outcome.kind;\n const response =\n outcome.kind === 'completed'\n ? completedText(inspection, outcome.responseMessageId)\n : undefined;\n return {\n agentId: record.agentId,\n childSessionId: record.childSessionId,\n ...(record.name === undefined ? {} : { name: record.name }),\n ...(record.description === undefined ? {} : { description: record.description }),\n state,\n modelUsage,\n runId: run.lifecycle.runId,\n outcome,\n ...(response === undefined ? {} : { response }),\n };\n }\n\n async #closedUsage(record: ChildAgentEntry): Promise<ClosedChildUsage> {\n const { runs } = await this.#options.host.inspectChild(record);\n const latestRun = runs.at(-1);\n const closedUsage: ClosedChildUsage = {\n ...(latestRun === undefined ? {} : { throughRunId: latestRun.lifecycle.runId }),\n modelUsage: projectModelUsage(runs),\n };\n return closedUsage;\n }\n}\n\nfunction sumModelUsage(usages: readonly ChildModelUsageSnapshot[]): ChildModelUsageSnapshot {\n let committedResponses = 0;\n let activeRequests = 0;\n let unknownRequests = 0;\n let totalTokens = 0;\n let costUsd = 0;\n const models = new Map<string, { provider: string; model: string; usage: Usage }>();\n for (const usage of usages) {\n committedResponses += usage.committedResponses;\n activeRequests += usage.activeRequests;\n unknownRequests += usage.unknownRequests;\n totalTokens += usage.totalTokens;\n costUsd += usage.costUsd;\n for (const row of usage.models ?? []) addModelUsage(models, row.provider, row.model, row.usage);\n }\n return {\n committedResponses,\n activeRequests,\n unknownRequests,\n totalTokens,\n costUsd,\n models: [...models.values()],\n };\n}\n\nfunction completedText(\n inspection: SessionInspection,\n responseMessageId: string\n): ChildAgentSnapshot['response'] | undefined {\n const text = completedResponseText(inspection, responseMessageId);\n if (text === undefined) return;\n return {\n text: text.slice(0, MAX_RESPONSE_CHARACTERS),\n truncated: text.length > MAX_RESPONSE_CHARACTERS,\n };\n}\n\nexport function completedResponseText(\n inspection: SessionInspection,\n responseMessageId: string\n): string | undefined {\n const entry = inspection.conversation.find(\n (candidate) => candidate.messageId === responseMessageId\n );\n if (entry?.message.role !== 'assistant') return;\n return entry.message.content\n .flatMap((content) => (content.type === 'text' ? [content.text] : []))\n .join('');\n}\n\n/** Observe the existing Run; cancellation stops the waiter, not the child execution. */\nexport async function waitForChildRun(\n child: ChildSessionRuntime,\n runId: string,\n signal?: AbortSignal\n): Promise<void> {\n signal?.throwIfAborted();\n const snapshot = await child.snapshot(runId);\n if (snapshot.outcome !== undefined) return;\n signal?.throwIfAborted();\n const facts = child.runFacts(runId, { after: snapshot.cursor });\n const close = () => facts.close();\n signal?.addEventListener('abort', close, { once: true });\n try {\n for await (const fact of facts) if (isRunTerminalFactKind(fact.kind)) return;\n signal?.throwIfAborted();\n const current = await child.snapshot(runId);\n if (current.outcome === undefined)\n throw new Error('Child execution unloaded before Run settlement');\n } finally {\n signal?.removeEventListener('abort', close);\n facts.close();\n }\n}\n","import { raceSignal } from 'race-signal';\nimport type { SessionInputSource } from '@sorbetai/runtime';\nimport {\n ChildAgentError,\n type SendInputRequest,\n type SendInputOutput,\n type SendTeamMessageRequest,\n type SendTeamMessageOutput,\n type ListTeamPeersOutput,\n} from './contracts.js';\nimport type { ChildAgentCatalog } from './catalog.js';\nimport type { ChildControlClient } from './control/client.js';\nimport type { ChildAgentHost } from './host.js';\nimport { waitForChildRun, type ChildObservationCoordinator } from './observation.js';\nimport type { ChildOperation } from './operations.js';\nimport { stageChildInput } from './completion.js';\n\nconst NeverAbortSignal = AbortSignal.any([]);\ninterface Options {\n readonly catalog: ChildAgentCatalog;\n readonly host: ChildAgentHost;\n readonly control: ChildControlClient;\n readonly observation: ChildObservationCoordinator;\n}\n\n/** Input and its Reporter share admission; placement remains owned by the Unit and Pi. */\nexport class ChildDeliveryCoordinator {\n constructor(readonly options: Options) {}\n\n send(\n operation: ChildOperation & { readonly request: SendInputRequest }\n ): Promise<SendInputOutput> {\n return this.#send(\n operation,\n operation.request.agentId,\n `to-child-${operation.context.effectAttemptId}`,\n operation.request.prompt,\n {\n kind: 'node-agent.parent-input',\n data: {\n parentSessionId: operation.parentSessionId,\n parentRunId: operation.context.runId,\n toolCallId: operation.context.toolCallId,\n effectAttemptId: operation.context.effectAttemptId,\n agentId: operation.request.agentId,\n interrupt: operation.request.interrupt === true,\n },\n },\n operation.request.interrupt === true\n );\n }\n\n async listTeamPeers(\n operation: ChildOperation & { readonly senderAgentId: string }\n ): Promise<ListTeamPeersOutput> {\n await this.#assertSender(operation);\n const { children } = await this.options.catalog.read(operation.parentSessionId);\n const peers = await Promise.all(\n children\n .filter(\n (child) => child.agentId !== operation.senderAgentId && !child.closed && !child.closing\n )\n .map(async (child) => {\n const snapshot = await this.options.observation.snapshotRecord(child);\n return { agentId: child.agentId, state: snapshot.state };\n })\n );\n return { peers };\n }\n\n async sendTeamMessage(\n operation: ChildOperation & {\n readonly senderAgentId: string;\n readonly request: SendTeamMessageRequest;\n }\n ): Promise<SendTeamMessageOutput> {\n await this.#assertSender(operation);\n if (operation.request.agentId === operation.senderAgentId)\n throw new ChildAgentError(\n 'team_self_message',\n 'A child cannot send a Team message to itself'\n );\n const deliveryId = `team-${operation.senderAgentId}-${operation.context.effectAttemptId}`;\n await this.#admit(\n operation,\n operation.request.agentId,\n deliveryId,\n operation.request.prompt,\n {\n kind: 'node-agent.team-message',\n data: {\n parentSessionId: operation.parentSessionId,\n senderAgentId: operation.senderAgentId,\n senderSessionId: operation.context.sessionId,\n senderRunId: operation.context.runId,\n toolCallId: operation.context.toolCallId,\n effectAttemptId: operation.context.effectAttemptId,\n recipientAgentId: operation.request.agentId,\n },\n },\n false\n );\n return { status: 'queued', deliveryId, recipient: { agentId: operation.request.agentId } };\n }\n\n async #assertSender(\n operation: ChildOperation & { readonly senderAgentId: string }\n ): Promise<void> {\n const sender = await this.options.catalog.record(\n operation.parentSessionId,\n operation.senderAgentId\n );\n if (sender.closed || sender.closing)\n throw new ChildAgentError('child_closed', 'Sender child is closed');\n if (sender.childSessionId !== operation.context.sessionId)\n throw new ChildAgentError(\n 'child_not_found',\n 'Team sender does not match the invoking Session'\n );\n }\n\n async #admit(\n operation: ChildOperation,\n agentId: string,\n deliveryId: string,\n prompt: string,\n source: SessionInputSource,\n interrupt: boolean\n ) {\n const signal = operation.context.signal ?? NeverAbortSignal;\n signal.throwIfAborted();\n const unit = this.options.host.unit(operation.parentSessionId);\n const record = await this.options.catalog.record(operation.parentSessionId, agentId);\n await this.options.control.withChildPermit(\n operation.parentSessionId,\n agentId,\n 'input',\n async () => {\n signal.throwIfAborted();\n const current = await this.options.catalog.record(operation.parentSessionId, agentId);\n if (current.closed || current.closing)\n throw new ChildAgentError('child_closed', 'Child agent is closed');\n if (interrupt && (await unit.submission(deliveryId)) === undefined) {\n const facts = await unit.participant(record.childSessionId);\n for (const pending of await facts.pendingSubmissions()) {\n await (\n await unit.submission(pending.accepted.operationId)\n )?.withdraw({\n reason: 'Child input superseded by interrupt',\n commandId: `interrupt:${deliveryId}:${pending.accepted.operationId}`,\n });\n }\n const child = await this.options.host.loadChild(record);\n const active = await child.getActiveRun();\n if (active !== undefined) {\n await child.abortRun(active.receipt.runId, 'Child input interrupted by sender');\n await waitForChildRun(child, active.receipt.runId, signal);\n }\n }\n await unit.prepareSessions([record.childSessionId]);\n signal.throwIfAborted();\n await unit.group((group) =>\n group.tasks((tx) => {\n stageChildInput(tx, record, record.anchorId, {\n kind: 'user-message',\n deliveryId,\n prompt,\n source,\n });\n })\n );\n },\n signal\n );\n const submission = await unit.submission(deliveryId);\n if (submission === undefined) throw new Error('Child input admission is missing');\n await unit.resume();\n return { unit, record, submission };\n }\n\n async #send(\n operation: ChildOperation,\n agentId: string,\n deliveryId: string,\n prompt: string,\n source: SessionInputSource,\n interrupt: boolean\n ): Promise<SendInputOutput> {\n const signal = operation.context.signal ?? NeverAbortSignal;\n const { unit, record, submission } = await this.#admit(\n operation,\n agentId,\n deliveryId,\n prompt,\n source,\n interrupt\n );\n try {\n await raceSignal(unit.notifyAvailable(record.childSessionId), signal);\n const recovery = unit\n .recovery()\n .decisions.find((entry) => entry.sessionId === record.childSessionId);\n if (recovery?.status === 'faulted')\n throw new ChildAgentError(\n 'child_provision_failed',\n recovery.error?.message ?? 'Child environment could not be acquired'\n );\n signal.throwIfAborted();\n } catch (cause) {\n if (signal.aborted)\n await submission.withdraw({\n reason: 'Child delivery cancelled',\n commandId: `cancel:${deliveryId}`,\n });\n throw cause;\n }\n return {\n status: 'accepted',\n deliveryId,\n agent: await this.options.observation.snapshotById(record.parentSessionId, agentId),\n };\n }\n}\n","export interface AvailableAgentModel {\n readonly selector: string;\n readonly providerId: string;\n readonly modelId: string;\n readonly displayName: string;\n}\n\nexport interface ModelSelector {\n readonly providerId: string;\n readonly modelId: string;\n}\n\nexport function encodeModelSelector(providerId: string, modelId: string): string {\n return `${encodeURIComponent(providerId)}/${encodeURIComponent(modelId)}`;\n}\n\nexport function decodeModelSelector(selector: string): ModelSelector | undefined {\n const segments = selector.split('/');\n if (segments.length !== 2) return;\n let providerId: string;\n let modelId: string;\n try {\n providerId = decodeURIComponent(segments[0] ?? '');\n modelId = decodeURIComponent(segments[1] ?? '');\n } catch {\n return;\n }\n if (\n providerId.length === 0 ||\n modelId.length === 0 ||\n encodeModelSelector(providerId, modelId) !== selector\n ) {\n return;\n }\n return { providerId, modelId };\n}\n","import type { JsonValue, UnitRuntime, UnitTx } from '@sorbetai/runtime';\nimport { raceSignal } from 'race-signal';\nimport * as Effect from 'effect/Effect';\nimport { decodeModelSelector, type AvailableAgentModel } from './models.js';\nimport {\n ChildAgentError,\n type CloseAgentOutput,\n type SpawnAgentOutput,\n type SwarmAgentOutput,\n type SwarmTaskOutput,\n} from './contracts.js';\nimport type { ChildAgentHost, ChildAgentParent } from './host.js';\nimport type { ChildAgentCatalog } from './catalog.js';\nimport { stageChildAnchor, stageChildClose } from './close.js';\nimport { stageChildInput } from './completion.js';\nimport type { ChildTaskInput } from './record.js';\nimport type { ChildObservationCoordinator } from './observation.js';\nimport { waitForChildRun } from './observation.js';\nimport type { ChildOperation, SpawnOperation, SwarmOperation } from './operations.js';\n\nconst NeverAbortSignal = AbortSignal.any([]);\n\ninterface ChildAdmission {\n readonly child: ChildTaskInput;\n readonly submission: NonNullable<Awaited<ReturnType<UnitRuntime['submission']>>>;\n}\n\ninterface ChildLifecycleCoordinatorOptions {\n readonly catalog: ChildAgentCatalog;\n readonly maxActiveChildrenPerParent?: number;\n readonly host: ChildAgentHost;\n readonly observation: ChildObservationCoordinator;\n readonly createId: () => string;\n readonly now: () => Date;\n}\n\n/** Admission is durable before observation; Unit recovery owns execution and close cleanup. */\nexport class ChildLifecycleCoordinator {\n readonly #options: ChildLifecycleCoordinatorOptions;\n constructor(options: ChildLifecycleCoordinatorOptions) {\n this.#options = options;\n }\n\n async spawn(operation: SpawnOperation): Promise<SpawnAgentOutput> {\n const { child } = await this.#admitChild(operation);\n return {\n agent: await this.#options.observation.snapshotById(child.parentSessionId, child.agentId),\n };\n }\n\n /**\n * Durable admission only; the child Run settles on its own and reports back. `admitted`\n * runs once the child is committed, before the waits that a cancellation can interrupt.\n */\n async #admitChild(\n operation: SpawnOperation,\n admitted?: (admission: ChildAdmission) => void\n ): Promise<ChildAdmission> {\n const signal = operation.context.signal ?? NeverAbortSignal;\n signal.throwIfAborted();\n const parent = this.#parent(operation.parentSessionId);\n if (parent.depth !== 0)\n throw new ChildAgentError('child_depth_exceeded', 'Direct children cannot spawn agents');\n const identity = this.#modelIdentity(parent, operation.request.model);\n const model = await this.#selectModel(identity);\n const existing = (await this.#options.catalog.read(operation.parentSessionId)).children.find(\n (child) => child.spawnEffectAttemptId === operation.context.effectAttemptId\n );\n const display = existing ?? operation.request;\n const child: ChildTaskInput & { initialSubmissionId: string } = {\n agentId: existing?.agentId ?? this.#options.createId(),\n childSessionId: existing?.childSessionId ?? this.#options.createId(),\n ...(display.name === undefined ? {} : { name: display.name.trim() }),\n ...(display.description === undefined ? {} : { description: display.description.trim() }),\n parentSessionId: operation.parentSessionId,\n parentRunId: operation.context.runId,\n spawnToolCallId: operation.context.toolCallId,\n spawnEffectAttemptId: operation.context.effectAttemptId,\n depth: 1,\n providerId: model.providerId,\n modelId: model.modelId,\n executionPolicy: parent.executionPolicy(operation.context.runId),\n ordinaryToolNames: existing?.ordinaryToolNames ?? [...(await parent.ordinaryToolNames())],\n contextMode: 'fresh',\n initialMode: 'background',\n initialCompletionDelivery: operation.request.completionDelivery ?? 'auto',\n createdAt: existing?.createdAt ?? this.#options.now().toISOString(),\n initialSubmissionId: `child-spawn-${operation.context.effectAttemptId}`,\n };\n const unit = this.#options.host.unit(operation.parentSessionId);\n // A retried attempt keeps the committed metadata: createSession requires it to match.\n const metadata =\n unit.sessions().find((session) => session.sessionId === child.childSessionId)?.metadata ??\n (await this.#options.host.childMetadata(child));\n await unit.prepareSessions(\n existing === undefined\n ? [operation.parentSessionId]\n : [operation.parentSessionId, child.childSessionId]\n );\n signal.throwIfAborted();\n await unit.group((group) =>\n group.tasks((tx) =>\n stageChildAgent(tx, {\n child,\n metadata,\n input: {\n kind: 'user-message',\n deliveryId: child.initialSubmissionId,\n prompt: operation.request.prompt,\n source: {\n kind: 'node-agent.parent-spawn',\n data: {\n parentSessionId: child.parentSessionId,\n parentRunId: child.parentRunId,\n toolCallId: child.spawnToolCallId,\n effectAttemptId: child.spawnEffectAttemptId,\n agentId: child.agentId,\n },\n },\n },\n })\n )\n );\n const submission = await unit.submission(child.initialSubmissionId);\n if (submission === undefined) throw new Error('Child initial input is missing');\n admitted?.({ child, submission });\n await unit.resume();\n await raceSignal(unit.notifyAvailable(child.childSessionId), signal);\n const recovery = unit\n .recovery()\n .decisions.find((entry) => entry.sessionId === child.childSessionId);\n if (recovery?.status === 'faulted')\n throw new ChildAgentError(\n 'child_provision_failed',\n recovery.error?.message ?? 'Child environment could not be acquired'\n );\n signal.throwIfAborted();\n // The Tool result must name the child Run, so wait for acceptance; settlement stays with the child.\n await submission.placed(signal);\n signal.throwIfAborted();\n return { child, submission };\n }\n async swarm(operation: SwarmOperation): Promise<SwarmAgentOutput> {\n const signal = operation.context.signal ?? NeverAbortSignal;\n // Swarm is the one gather: it admits concurrently and waits for every admitted Run.\n const tasks = await Effect.runPromise(\n Effect.forEach(\n operation.request.tasks,\n (task, index) =>\n Effect.promise(async (): Promise<SwarmTaskOutput> => {\n let admission: ChildAdmission | undefined;\n try {\n const { child, submission } = await this.#admitChild(\n {\n parentSessionId: operation.parentSessionId,\n request: {\n prompt: task.prompt,\n name: task.name,\n description: task.description,\n model: operation.request.model,\n completionDelivery: 'manual',\n },\n context: {\n ...operation.context,\n signal,\n effectAttemptId: `${operation.context.effectAttemptId}.${index}`,\n },\n },\n (admitted) => {\n admission = admitted;\n }\n );\n await submission.settled(signal);\n const agent = await this.#options.observation.snapshotById(\n child.parentSessionId,\n child.agentId\n );\n return agent.state === 'completed'\n ? { taskId: task.taskId, status: 'completed', agent }\n : { taskId: task.taskId, status: 'failed', agent };\n } catch (cause) {\n // A task that never settled leaves a live child behind; stop it whatever ended the gather.\n if (admission !== undefined) await this.#stopChild(admission, 'Swarm task cancelled');\n if (signal.aborted) {\n const cancellation =\n signal.reason instanceof ChildAgentError\n ? { code: signal.reason.code, message: signal.reason.message }\n : { code: 'agent_operation_cancelled', message: 'Swarm task cancelled' };\n return { taskId: task.taskId, status: 'cancelled', error: cancellation };\n }\n const error =\n cause instanceof ChildAgentError\n ? { code: cause.code, message: cause.message }\n : { code: 'agent_operation_failed', message: 'Swarm task failed' };\n return { taskId: task.taskId, status: 'failed', error };\n }\n }),\n { concurrency: this.#options.maxActiveChildrenPerParent ?? 'unbounded' }\n )\n );\n return { tasks };\n }\n\n /**\n * Withdraws the initial input if it was not placed yet, otherwise aborts the Run it placed.\n * An unloaded child has no execution in this process; only loaded Runs can be aborted.\n */\n async #stopChild({ child, submission }: ChildAdmission, reason: string): Promise<void> {\n const withdrawn = await submission\n .withdraw({ reason, commandId: `stop:${submission.submissionId}` })\n .catch(() => false);\n if (withdrawn) return;\n const runId = (await submission.status().catch(() => undefined))?.placed?.runId;\n const session = this.#options.host.loaded(child.childSessionId);\n if (runId === undefined || session === undefined) return;\n await session.abortRun(runId, reason).catch(() => undefined);\n // \"Stopped\" means the Run settled, not that cancellation was requested.\n await waitForChildRun(session, runId).catch(() => undefined);\n }\n\n async closeChild(\n operation: ChildOperation & { readonly agentId: string }\n ): Promise<CloseAgentOutput> {\n return this.closeChildForHost(\n operation.parentSessionId,\n operation.agentId,\n operation.context.signal\n );\n }\n\n async closeChildForHost(\n parentSessionId: string,\n agentId: string,\n signal?: AbortSignal,\n reason = 'Child agent closed by parent'\n ): Promise<CloseAgentOutput> {\n signal?.throwIfAborted();\n const record = await this.#options.catalog.record(parentSessionId, agentId);\n if (!record.closed) {\n const unit = this.#options.host.unit(parentSessionId);\n await unit.group((group) =>\n group.tasks((tx) =>\n stageChildClose(tx, record.anchorId, reason, `close:${record.anchorId}`)\n )\n );\n await unit.resume();\n await unit.notifyAvailable(record.childSessionId);\n const decision = unit\n .recovery()\n .decisions.find((entry) => entry.sessionId === record.childSessionId);\n if (decision?.status === 'faulted') throw decision.error;\n if (!unit.sessions().find((entry) => entry.sessionId === record.childSessionId)?.closed)\n throw new Error('Child close is waiting for Host cleanup');\n }\n const snapshot = await this.#options.observation.snapshotById(parentSessionId, agentId);\n if (snapshot.state !== 'closed') throw new Error('Closed child projection is inconsistent');\n return { agent: { ...snapshot, state: 'closed' } };\n }\n\n /** False when no child anchor of this parent owns the Session. */\n async closeBySession(\n parentSessionId: string,\n childSessionId: string,\n signal?: AbortSignal\n ): Promise<boolean> {\n const record = (await this.#options.catalog.read(parentSessionId)).children.find(\n (child) => child.childSessionId === childSessionId\n );\n if (record === undefined) return false;\n await this.closeChildForHost(record.parentSessionId, record.agentId, signal);\n return true;\n }\n\n releaseParent(parentSessionId: string): Promise<void> {\n return this.#options.host.releaseChildren(parentSessionId);\n }\n\n #parent(sessionId: string): ChildAgentParent {\n const parent = this.#options.host.parent(sessionId);\n if (parent === undefined)\n throw new ChildAgentError('child_not_found', 'Parent Session is not loaded');\n return parent;\n }\n #modelIdentity(\n parent: ChildAgentParent,\n selector?: string\n ): { readonly providerId: string; readonly modelId: string } {\n const selected = selector === undefined ? undefined : decodeModelSelector(selector);\n if (selector !== undefined && selected === undefined) {\n throw new ChildAgentError('model_unavailable', 'Child model selector is invalid');\n }\n return {\n providerId: selected?.providerId ?? parent.providerId,\n modelId: selected?.modelId ?? parent.modelId,\n };\n }\n\n async #selectModel(identity: {\n readonly providerId: string;\n readonly modelId: string;\n }): Promise<AvailableAgentModel> {\n const available = await this.#options.host.availableModels();\n const model = available.find(\n (candidate) =>\n candidate.providerId === identity.providerId && candidate.modelId === identity.modelId\n );\n if (model === undefined) {\n throw new ChildAgentError('model_unavailable', 'Requested child model is unavailable');\n }\n return model;\n }\n}\n\n/** Commit before waiting for a child Run or Tool result. A failed receipt cannot undo admission. */\nexport function stageChildAgent(\n tx: UnitTx,\n request: {\n readonly child: ChildTaskInput & { readonly initialSubmissionId: string };\n readonly metadata: JsonValue;\n readonly input: Parameters<UnitTx['submit']>[1];\n }\n): string {\n const { child } = request;\n if (request.input.deliveryId !== child.initialSubmissionId)\n throw new Error('Child initial Submission identity does not match');\n tx.createSession({\n sessionId: child.childSessionId,\n parentSessionId: child.parentSessionId,\n key: `child:${child.spawnEffectAttemptId}`,\n metadata: request.metadata,\n });\n const anchorId = stageChildAnchor(tx, child);\n stageChildInput(tx, child, anchorId, request.input, { initial: true });\n return anchorId;\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { check, decode } from '@sorbetai/schema';\nimport { JsonValueSchema, type UnitRuntime } from '@sorbetai/runtime';\nimport type { WaitTargetSource } from '../contracts.js';\nimport { ChildTelemetry } from './telemetry.js';\nimport type { ChildAgentObservationPort } from './telemetry-port.js';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport {\n type CloseAgentOutput,\n type ListAgentsOutput,\n type ListTeamPeersOutput,\n type SendInputOutput,\n type SendInputRequest,\n type SendTeamMessageOutput,\n type SendTeamMessageRequest,\n type SpawnAgentOutput,\n type SwarmAgentOutput,\n} from './contracts.js';\nimport { ChildControlClient } from './control/client.js';\nimport { ChildControl } from './control/service.js';\nimport { ChildDeliveryCoordinator } from './delivery.js';\nimport type { ChildAgentHost } from './host.js';\nimport { ChildLifecycleCoordinator } from './lifecycle.js';\nimport type { ChildAgentCatalog } from './catalog.js';\nimport { ChildObservationCoordinator } from './observation.js';\nimport type { ChildOperation, SpawnOperation, SwarmOperation } from './operations.js';\n\nconst RunTarget = s.obj({ runId: s.str() }, { open: false });\nconst ChildCompletionSource = s.obj(\n {\n kind: s.lit('node-agent.child-completion'),\n data: s.obj({ childRunId: s.str() }, { open: true }),\n },\n { open: true }\n);\n\nexport class ChildAgentManager {\n readonly #telemetry: ChildTelemetry;\n readonly #catalog: ChildAgentCatalog;\n readonly #observationPort: ChildAgentObservationPort | undefined;\n readonly #runtime = ManagedRuntime.make(ChildControl.layer);\n readonly #control = new ChildControlClient(this.#runtime);\n readonly #observation: ChildObservationCoordinator;\n readonly #delivery: ChildDeliveryCoordinator;\n readonly #lifecycle: ChildLifecycleCoordinator;\n #closing: Promise<void> | undefined;\n #shutdown: Promise<void> | undefined;\n\n constructor(options: {\n readonly catalog: ChildAgentCatalog;\n readonly host: ChildAgentHost;\n /**\n * Swarm admission concurrency, unbounded by default. Run placement is bounded\n * separately by the Unit's `policies.concurrency.childRunsPerParent`.\n */\n readonly maxActiveChildrenPerParent?: number;\n readonly createId: () => string;\n readonly now: () => Date;\n readonly observation?: ChildAgentObservationPort;\n }) {\n this.#catalog = options.catalog;\n this.#telemetry = new ChildTelemetry(options.catalog, options.observation);\n this.#observationPort = options.observation;\n this.#observation = new ChildObservationCoordinator({\n control: this.#control,\n catalog: options.catalog,\n host: options.host,\n });\n this.#delivery = new ChildDeliveryCoordinator({\n control: this.#control,\n catalog: options.catalog,\n host: options.host,\n observation: this.#observation,\n });\n this.#lifecycle = new ChildLifecycleCoordinator({\n catalog: options.catalog,\n maxActiveChildrenPerParent: options.maxActiveChildrenPerParent,\n host: options.host,\n observation: this.#observation,\n createId: options.createId,\n now: options.now,\n });\n }\n\n spawn(operation: SpawnOperation): Promise<SpawnAgentOutput> {\n return this.#runOperation('spawn', operation, (controlled) =>\n this.#lifecycle.spawn(controlled)\n );\n }\n\n stateOwner(parentSessionId: string) {\n return this.#observation.stateOwner(parentSessionId);\n }\n\n getResult(\n operation: ChildOperation & {\n readonly agentId: string;\n readonly runId: string;\n readonly offset?: number;\n readonly limit?: number;\n }\n ) {\n return this.#runOperation('getResult', operation, (controlled) =>\n this.#observation.getResult(controlled)\n );\n }\n\n listResults(operation: ChildOperation & { readonly after?: number; readonly limit?: number }) {\n return this.#runOperation('listResults', operation, (controlled) =>\n this.#observation.listResults(controlled)\n );\n }\n\n swarm(operation: SwarmOperation): Promise<SwarmAgentOutput> {\n return this.#runOperation('swarm', operation, (controlled) =>\n this.#lifecycle.swarm(controlled)\n );\n }\n\n send(\n operation: ChildOperation & { readonly request: SendInputRequest }\n ): Promise<SendInputOutput> {\n return this.#runOperation('send', operation, (controlled) => this.#delivery.send(controlled));\n }\n\n listTeamPeers(\n operation: ChildOperation & { readonly senderAgentId: string }\n ): Promise<ListTeamPeersOutput> {\n return this.#runOperation('listTeamPeers', operation, (controlled) =>\n this.#delivery.listTeamPeers(controlled)\n );\n }\n\n sendTeamMessage(\n operation: ChildOperation & {\n readonly senderAgentId: string;\n readonly request: SendTeamMessageRequest;\n }\n ): Promise<SendTeamMessageOutput> {\n return this.#runOperation('sendTeamMessage', operation, (controlled) =>\n this.#delivery.sendTeamMessage(controlled)\n );\n }\n\n listAgents(\n operation: ChildOperation & { readonly request: { readonly includeClosed?: boolean } }\n ): Promise<ListAgentsOutput> {\n return this.#runOperation('listAgents', operation, (controlled) =>\n this.#observation.listAgents(controlled)\n );\n }\n\n listAgentsForHost(parentSessionId: string, includeClosed = true): Promise<ListAgentsOutput> {\n return this.#observation.listAgentsForHost(parentSessionId, includeClosed);\n }\n\n closeChild(operation: ChildOperation & { readonly agentId: string }): Promise<CloseAgentOutput> {\n return this.#runOperation('closeChild', operation, (controlled) =>\n this.#lifecycle.closeChild(controlled)\n );\n }\n\n closeChildForHost(\n parentSessionId: string,\n agentId: string,\n signal?: AbortSignal,\n reason?: string\n ): Promise<CloseAgentOutput> {\n return this.#control.admitClose(parentSessionId, 'closeChildForHost', (controlSignal) =>\n this.#lifecycle.closeChildForHost(\n parentSessionId,\n agentId,\n signal === undefined ? controlSignal : AbortSignal.any([signal, controlSignal]),\n reason\n )\n );\n }\n\n /** Lets the durable `wait` Tool wait for child Runs of the Session that owns them. */\n waitTargets(): WaitTargetSource {\n return {\n resolve: async (sessionId, target) => {\n if (!check(RunTarget, target)) return undefined;\n const member = await this.#observation.waitMember(sessionId, target.runId);\n return member === undefined\n ? { kind: 'refused', reason: `No child Run ${target.runId} belongs to this Session` }\n : { kind: 'member', member };\n },\n describe: async (sessionId, target) => {\n if (!check(RunTarget, target)) return {};\n const snapshot = await this.#observation.describeRun(sessionId, target.runId);\n return snapshot === undefined\n ? { state: 'missing' }\n : decode(s.map(JsonValueSchema), snapshot);\n },\n notification: (input) =>\n input.kind === 'context-event' && check(ChildCompletionSource, input.source)\n ? { runId: input.source.data.childRunId }\n : undefined,\n };\n }\n\n trackUnit(unit: UnitRuntime): void {\n this.#catalog.track(unit, this.#observationPort !== undefined);\n this.#telemetry.track(unit);\n }\n\n activateParent(parentSessionId: string): Promise<void> {\n return this.#control.activateParent(parentSessionId);\n }\n\n async releaseParent(parentSessionId: string): Promise<void> {\n await this.#control.interruptParent(parentSessionId);\n await this.#lifecycle.releaseParent(parentSessionId);\n }\n\n closeBySession(parentSessionId: string, childSessionId: string): Promise<boolean> {\n return this.#control.admit(undefined, 'closeBySession', (signal) =>\n this.#lifecycle.closeBySession(parentSessionId, childSessionId, signal)\n );\n }\n\n shutdown(parentSessionIds: readonly string[]): Promise<void> {\n this.#shutdown ??= this.#control\n .close(parentSessionIds, (parentSessionId) => this.releaseParent(parentSessionId))\n .catch((cause) => {\n this.#shutdown = undefined;\n throw cause;\n });\n this.#closing ??= this.#shutdown\n .then(() => this.#telemetry.close())\n .then(() => this.#control.dispose())\n .catch((cause) => {\n this.#closing = undefined;\n throw cause;\n });\n return this.#closing;\n }\n\n #runOperation<Operation extends ChildOperation, Result>(\n operationName: string,\n operation: Operation,\n run: (operation: Operation) => Promise<Result>\n ): Promise<Result> {\n return this.#control.admit(operation.parentSessionId, operationName, (controlSignal) =>\n run({\n ...operation,\n context: {\n ...operation.context,\n signal:\n operation.context.signal === undefined\n ? controlSignal\n : AbortSignal.any([operation.context.signal, controlSignal]),\n },\n })\n );\n }\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { decode } from '@sorbetai/schema';\nimport type { JournalCursor, UnitReader, UnitRuntime } from '@sorbetai/runtime';\n\nimport { ChildAgentError } from './contracts.js';\nimport { ChildProjection, type ChildAgentEntry } from './projection.js';\nimport type { ChildDeliveryPage } from './telemetry-port.js';\n\nexport type { ChildAgentEntry } from './projection.js';\n\ninterface OwnedProjection {\n readonly unit: UnitRuntime;\n readonly observeAfter: number;\n projection: ChildProjection;\n cursor?: JournalCursor;\n sequence: number;\n pending: Promise<void>;\n}\n\n/** Cold reads pin a committed prefix; owned reads incrementally reuse that writer's index. */\nexport class ChildAgentCatalog {\n readonly #owned = new Map<string, OwnedProjection>();\n\n constructor(readonly openReader: (parentSessionId: string) => Promise<UnitReader>) {}\n\n track(unit: UnitRuntime, observe: boolean): void {\n if (this.#owned.get(unit.unitId)?.unit === unit) return;\n const observeAfter = observe\n ? unit.workSummary().observedUnitSequence\n : Number.POSITIVE_INFINITY;\n const state: OwnedProjection = {\n unit,\n observeAfter,\n projection: new ChildProjection(unit.unitId, observeAfter),\n sequence: 0,\n pending: Promise.resolve(),\n };\n this.#owned.set(unit.unitId, state);\n void unit.closed.then(() => {\n if (this.#owned.get(unit.unitId) === state) this.#owned.delete(unit.unitId);\n });\n }\n\n async record(parentSessionId: string, agentId: string): Promise<ChildAgentEntry> {\n const record = (await this.read(parentSessionId)).children.find(\n (child) => child.agentId === agentId\n );\n if (record === undefined)\n throw new ChildAgentError('child_not_found', 'Child agent was not found');\n return record;\n }\n\n read(parentSessionId: string, afterSequence = Number.POSITIVE_INFINITY) {\n const owned = this.#owned.get(parentSessionId);\n if (owned === undefined) return this.#readCold(parentSessionId, afterSequence);\n const work = owned.pending.then(async () => {\n const tail = owned.unit.workSummary().observedUnitSequence;\n try {\n while (owned.sequence < tail) {\n // Bound each page to this read's prefix even if the writer commits during I/O.\n const page = await owned.unit.readHistory({\n after: owned.cursor,\n limit: Math.min(256, tail - owned.sequence),\n });\n for (const record of page.records) owned.projection.apply(record);\n owned.sequence = page.records.at(-1)?.unitSequence ?? tail;\n owned.cursor = page.cursor;\n }\n return owned.projection.snapshot(tail, afterSequence);\n } catch (cause) {\n owned.projection = new ChildProjection(parentSessionId, owned.observeAfter);\n owned.sequence = 0;\n owned.cursor = undefined;\n throw cause;\n }\n });\n owned.pending = work.then(\n () => {},\n () => {}\n );\n return work;\n }\n\n async #readCold(parentSessionId: string, afterSequence: number) {\n const reader = await this.openReader(parentSessionId);\n const projection = new ChildProjection(parentSessionId, afterSequence);\n const tail = reader.tail;\n let sequence = 0;\n let cursor: JournalCursor | undefined;\n try {\n while (sequence < tail) {\n const page = await reader.read({ after: cursor, limit: Math.min(256, tail - sequence) });\n for (const record of page.records) projection.apply(record);\n cursor = page.cursor;\n sequence = page.records.at(-1)?.unitSequence ?? tail;\n }\n return projection.snapshot(tail, afterSequence);\n } finally {\n await reader.close();\n }\n }\n\n async inspectDeliveries(\n parentSessionId: string,\n options: { readonly afterOrderingKey?: number; readonly limit?: number } = {}\n ): Promise<ChildDeliveryPage> {\n const limit = decode(s.int({ minimum: 1, maximum: 256 }), options.limit ?? 64);\n const after = decode(s.int({ minimum: 0 }), options.afterOrderingKey ?? 0);\n const available = (await this.read(parentSessionId)).deliveries.filter(\n (delivery) => delivery.orderingKey > after\n );\n const selected = available.slice(0, limit);\n return {\n parentSessionId,\n deliveries: selected,\n nextOrderingKey: available.length > limit ? selected.at(-1)?.orderingKey : undefined,\n };\n }\n}\n","import * as s from '@earendil-works/pi-schema';\nimport toError from 'ensure-error';\nimport { parseToolParameters, type ContextualTool } from '@sorbetai/runtime';\n\nimport type { AvailableAgentModel } from './models.js';\nimport type { ChildAgentManager } from './manager.js';\nimport {\n childToolExecutionError,\n ChildAgentDescriptionSchema,\n ChildAgentNameSchema,\n type ChildAgentSnapshot,\n type CloseAgentOutput,\n type ListAgentsOutput,\n type SendInputOutput,\n type SpawnAgentOutput,\n type SwarmAgentOutput,\n} from './contracts.js';\n\nconst NON_EMPTY_STRING_MIN_LENGTH = 1;\nconst SAFE_ID_PATTERN = '^[A-Za-z0-9][A-Za-z0-9._-]*$';\nconst NonEmptyString = s.str({ minLength: NON_EMPTY_STRING_MIN_LENGTH });\nconst SafeId = s.str({ pattern: SAFE_ID_PATTERN });\n\nconst AgentActionSchema = s.union([\n s.obj({ action: s.lit('list_models') }, { open: false }),\n s.obj(\n {\n action: s.lit('get_result'),\n agentId: NonEmptyString,\n runId: NonEmptyString,\n offset: s.opt(s.int({ minimum: 0 })),\n limit: s.opt(s.int({ minimum: 1, maximum: 30_000 })),\n },\n { open: false }\n ),\n s.obj(\n {\n action: s.lit('list_results'),\n after: s.opt(s.int({ minimum: 0 })),\n limit: s.opt(s.int({ minimum: 1, maximum: 64 })),\n },\n { open: false }\n ),\n s.obj(\n {\n action: s.lit('spawn'),\n prompt: NonEmptyString,\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n model: s.opt(NonEmptyString),\n completionDelivery: s.opt(s.union([s.lit('auto'), s.lit('manual')])),\n },\n { open: false }\n ),\n s.obj(\n {\n action: s.lit('swarm'),\n tasks: s.arr(\n s.obj(\n {\n taskId: SafeId,\n prompt: NonEmptyString,\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n },\n { open: false }\n ),\n { minItems: 1 }\n ),\n model: s.opt(NonEmptyString),\n },\n { open: false }\n ),\n s.obj(\n {\n action: s.lit('send_input'),\n agentId: NonEmptyString,\n prompt: NonEmptyString,\n interrupt: s.opt(s.bool()),\n },\n { open: false }\n ),\n s.obj({ action: s.lit('list'), includeClosed: s.opt(s.bool()) }, { open: false }),\n s.obj({ action: s.lit('close'), agentId: NonEmptyString }, { open: false }),\n]);\ntype AgentAction = s.Static<typeof AgentActionSchema>;\n\nfunction parseAgentAction(action: AgentAction): AgentAction {\n if (action.action === 'swarm') {\n const taskIds = new Set(action.tasks.map(({ taskId }) => taskId));\n if (taskIds.size !== action.tasks.length)\n throw new TypeError('Swarm taskId values must be unique');\n }\n return action;\n}\n\n// Keep the Provider schema compatible with APIs that reject anyOf/const. Pi calls\n// prepareArguments before permission and Effect admission to enforce the exact union.\nconst AgentToolParametersSchema = s.obj(\n {\n action: {\n type: 'string',\n enum: [\n 'list_models',\n 'spawn',\n 'swarm',\n 'send_input',\n 'list',\n 'close',\n 'get_result',\n 'list_results',\n ],\n description: 'The model query or child-agent operation to perform.',\n } as s.Schema<AgentAction>,\n prompt: s.opt(\n s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Required input for spawn and send_input.',\n })\n ),\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n tasks: s.opt(\n s.arr(\n s.obj(\n {\n taskId: s.str({\n pattern: SAFE_ID_PATTERN,\n description: 'Stable caller-chosen identity for this Swarm task.',\n }),\n prompt: s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Complete input for this child.',\n }),\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n },\n { open: false }\n ),\n { minItems: 1, description: 'Required by swarm. Tasks wait for parent child capacity.' }\n )\n ),\n model: s.opt(\n s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Optional child model selector for spawn and swarm.',\n })\n ),\n completionDelivery: s.opt({\n type: 'string',\n enum: ['auto', 'manual'],\n description:\n 'For spawn only; defaults to auto. Completions refresh child_runs and wake this Session unless already included in a parent model request. manual suppresses automatic delivery for this child, including later send_input Runs; retrieve results with get_result.',\n } as s.Schema<'auto' | 'manual'>),\n agentId: s.opt(\n s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Required by send_input, close, and get_result.',\n })\n ),\n runId: s.opt(\n s.str({\n minLength: 1,\n description:\n 'Required by get_result. Identifies one retained child Run, including after close.',\n })\n ),\n after: s.opt(\n s.int({\n minimum: 0,\n description: 'For list_results, return automatic completions after this cursor.',\n })\n ),\n offset: s.opt(\n s.int({\n minimum: 0,\n description:\n 'For get_result, the UTF-16 text offset. Follow response.nextOffset to read the next page.',\n })\n ),\n limit: s.opt(\n s.int({\n minimum: 1,\n maximum: 30_000,\n description:\n 'For get_result, text characters per page (default/max 30000). For list_results, references per page (default 32, max 64).',\n })\n ),\n interrupt: s.opt(\n s.bool({ description: 'For send_input, cancel active work before replacement.' })\n ),\n includeClosed: s.opt(s.bool({ description: 'For list, include permanently closed children.' })),\n },\n { open: false }\n) as s.Schema<AgentAction>;\n\ninterface ListModelsOutput {\n readonly inheritedModel: string;\n readonly models: readonly AvailableAgentModel[];\n}\n\nexport type AgentToolDetails =\n | ({ readonly action: 'get_result' } & { readonly agent: ChildAgentSnapshot })\n | ({ readonly action: 'list_results' } & Awaited<ReturnType<ChildAgentManager['listResults']>>)\n | ({ readonly action: 'list_models' } & ListModelsOutput)\n | ({ readonly action: 'spawn' } & SpawnAgentOutput)\n | ({ readonly action: 'swarm' } & SwarmAgentOutput)\n | ({ readonly action: 'send_input' } & SendInputOutput)\n | ({ readonly action: 'list' } & ListAgentsOutput)\n | ({ readonly action: 'close' } & CloseAgentOutput);\n\n// This Tool owns exact pre-admission validation, action dispatch, and model-visible results.\nexport function createAgentTool(options: {\n readonly parentSessionId: string;\n readonly inheritedModel: string;\n readonly listAvailableModels: () => Promise<readonly AvailableAgentModel[]>;\n readonly manager: ChildAgentManager;\n}): ContextualTool<typeof AgentToolParametersSchema, AgentToolDetails> {\n return {\n name: 'agent',\n label: 'Agent',\n description:\n 'Query models or manage persistent direct child Sessions. Give every spawned child a short, pleasant name and a brief assignment description. Children inherit the parent Run Tool permissions, Sandbox policy, Workspace, and ordinary Tool set. spawn returns after admission with auto delivery by default; completionDelivery manual disables automatic delivery for the lifetime of that child. swarm admits prompts concurrently, waits for all admitted Runs to settle, and returns their results; its children use manual delivery, including later send_input Runs. send_input steers a running child at its next tool boundary or starts a Run when idle; it returns once accepted, without waiting for completion. interrupt cancels the current Run first. For auto children, completions refresh child_runs and wake this Session unless their references already appeared in a committed parent model request; report ongoing work and end your turn instead of polling. Manual children never wake this Session: when the next step needs a result, call the wait Tool with the child runId, then read it with get_result. For auto children, use wait only when the next step needs the result. get_result reads an exact agentId/runId result, including closed children; follow response.nextOffset with offset for remaining text. list_results pages only automatic completion references, excluding manual results. list inspects owned children; close releases execution resources. Every child snapshot reports cumulative committed Pi usage and unsettled request counts. Use list_models before selecting a non-inherited model.',\n parameters: AgentToolParametersSchema,\n prepareArguments: (input) =>\n parseAgentAction(parseToolParameters('agent', AgentActionSchema, input)),\n executionMode: 'parallel',\n execute: async (action, context) => {\n try {\n let details: AgentToolDetails;\n switch (action.action) {\n case 'get_result':\n details = {\n action: 'get_result',\n agent: await options.manager.getResult({\n parentSessionId: options.parentSessionId,\n agentId: action.agentId,\n runId: action.runId,\n offset: action.offset,\n limit: action.limit,\n context,\n }),\n };\n break;\n case 'list_results':\n details = {\n action: 'list_results',\n ...(await options.manager.listResults({\n parentSessionId: options.parentSessionId,\n after: action.after,\n limit: action.limit,\n context,\n })),\n };\n break;\n case 'list_models': {\n context.signal?.throwIfAborted();\n const models = await options.listAvailableModels();\n context.signal?.throwIfAborted();\n details = {\n action: 'list_models',\n inheritedModel: options.inheritedModel,\n models,\n };\n break;\n }\n case 'spawn':\n details = {\n action: 'spawn',\n ...(await options.manager.spawn({\n parentSessionId: options.parentSessionId,\n request: action,\n context,\n })),\n };\n break;\n case 'swarm':\n details = {\n action: 'swarm',\n ...(await options.manager.swarm({\n parentSessionId: options.parentSessionId,\n request: action,\n context,\n })),\n };\n break;\n case 'send_input':\n details = {\n action: 'send_input',\n ...(await options.manager.send({\n parentSessionId: options.parentSessionId,\n request: action,\n context,\n })),\n };\n break;\n case 'list':\n details = {\n action: 'list',\n ...(await options.manager.listAgents({\n parentSessionId: options.parentSessionId,\n request: action,\n context,\n })),\n };\n break;\n case 'close':\n details = {\n action: 'close',\n ...(await options.manager.closeChild({\n parentSessionId: options.parentSessionId,\n agentId: action.agentId,\n context,\n })),\n };\n break;\n }\n return {\n content: [{ type: 'text', text: JSON.stringify(details) }],\n details,\n };\n } catch (cause) {\n throw childToolExecutionError(\n toError(cause),\n 'agent_operation_failed',\n `Agent ${action.action} failed`\n );\n }\n },\n };\n}\n","import * as s from '@earendil-works/pi-schema';\nimport toError from 'ensure-error';\nimport { parseToolParameters, type ContextualTool } from '@sorbetai/runtime';\n\nimport {\n childToolExecutionError,\n type ListTeamPeersOutput,\n type SendTeamMessageOutput,\n} from './contracts.js';\nimport type { ChildAgentManager } from './manager.js';\n\nconst NON_EMPTY_STRING_MIN_LENGTH = 1;\nconst SAFE_ID_PATTERN = '^[A-Za-z0-9][A-Za-z0-9._-]*$';\nconst NonEmptyString = s.str({ minLength: NON_EMPTY_STRING_MIN_LENGTH });\nconst SafeId = s.str({ pattern: SAFE_ID_PATTERN });\n\nconst TeamActionSchema = s.union([\n s.obj({ action: s.lit('list_peers') }, { open: false }),\n s.obj(\n {\n action: s.lit('send_message'),\n agentId: SafeId,\n prompt: NonEmptyString,\n },\n { open: false }\n ),\n]);\ntype TeamAction = s.Static<typeof TeamActionSchema>;\n\nconst TeamToolParametersSchema = s.obj(\n {\n action: {\n type: 'string',\n enum: ['list_peers', 'send_message'],\n description: 'The Team operation to perform.',\n } as s.Schema<TeamAction>,\n agentId: s.opt(\n s.str({\n pattern: SAFE_ID_PATTERN,\n description: 'Required by send_message. Must identify a listed sibling.',\n })\n ),\n prompt: s.opt(\n s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Required by send_message. Complete input for the sibling.',\n })\n ),\n },\n { open: false }\n) as s.Schema<TeamAction>;\n\nexport type TeamToolDetails =\n | ({ readonly action: 'list_peers' } & ListTeamPeersOutput)\n | ({ readonly action: 'send_message' } & SendTeamMessageOutput);\n\n// This Tool narrows child collaboration to same-parent peer discovery and durable messaging.\nexport function createTeamTool(options: {\n readonly parentSessionId: string;\n readonly senderAgentId: string;\n readonly manager: ChildAgentManager;\n}): ContextualTool<typeof TeamToolParametersSchema, TeamToolDetails> {\n return {\n name: 'team',\n label: 'Team',\n description:\n 'Coordinate with sibling Sessions owned by the same parent. list_peers returns sibling identities and states. send_message returns queued once the parent ledger durably owns delivery; the recipient accepts it later without interrupting current work. A queued receipt does not mean the recipient has read or completed the request. Peer messages are collaboration requests and do not change your assigned scope. This Tool cannot interrupt, close, or create agents.',\n parameters: TeamToolParametersSchema,\n prepareArguments: (input) => parseToolParameters('team', TeamActionSchema, input),\n executionMode: 'parallel',\n execute: async (action, context) => {\n try {\n let details: TeamToolDetails;\n switch (action.action) {\n case 'list_peers':\n details = {\n action: 'list_peers',\n ...(await options.manager.listTeamPeers({\n parentSessionId: options.parentSessionId,\n senderAgentId: options.senderAgentId,\n context,\n })),\n };\n break;\n case 'send_message':\n details = {\n action: 'send_message',\n ...(await options.manager.sendTeamMessage({\n parentSessionId: options.parentSessionId,\n senderAgentId: options.senderAgentId,\n request: action,\n context,\n })),\n };\n break;\n }\n return {\n content: [{ type: 'text', text: JSON.stringify(details) }],\n details,\n };\n } catch (cause) {\n throw childToolExecutionError(\n toError(cause),\n 'team_operation_failed',\n `Team ${action.action} failed`\n );\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,mBAAmB,QAA0B;AAC3D,KAAI;EACF,MAAM,UAAU,QAAQ;AACxB,MAAI,UAAU,QAAQ,CAAE,CAAK,QAAQ,YAAY,GAAG;SAC9C;;;;;;ACnEV,IAAa,iBAAb,MAA4B;CAC1B,CAASA,0BAAW,IAAI,KAAsE;CAE9F,YACE,AAASC,SACT,AAASC,aACT;EAFS;EACA;;CAGX,MAAM,MAAyB;AAC7B,MAAI,KAA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;MAAE,CAAC;KAC1D;KACD;YACM,OAAO;AACd,UAAM,wBACJC,YAAQ,MAAM,EACd,yBACA,QAAQ,OAAO,OAAO,SACvB;;;EAGN"}
1
+ {"version":3,"file":"children.js","names":["#tracked","catalog: ChildAgentCatalog","observation: ChildAgentObservationPort | undefined","pending: Promise<void> | undefined","deliveries: ChildDeliveryBacklog[]","NonEmptyString","subagentIdentity: NamedStateOwner","code: ChildAgentFailureCode","identity: ChildOperationIdentity","outcome: Exit.Exit<A, E>","toError","#runtime","#control","#waitForEffect","failures: Error[]","Identity","#inputs","parentSessionId: string","observeAfter: number","fact","input","#options","#completionState","#findRun","#placedRun","#placedRuns","#snapshotRun","#closedUsage","state: ChildAgentSnapshot['state']","NeverAbortSignal","options: Options","#send","#assertSender","#admit","providerId: string","modelId: string","#options","#admitChild","#parent","#modelIdentity","#selectModel","child","child: ChildTaskInput & { initialSubmissionId: string }","admission: ChildAdmission | undefined","#stopChild","#telemetry","#catalog","#observationPort","#runtime","#control","#observation","#delivery","#lifecycle","#runOperation","#shutdown","#closing","#owned","openReader: (parentSessionId: string) => Promise<UnitReader>","state: OwnedProjection","#readCold","cursor: JournalCursor | undefined","NON_EMPTY_STRING_MIN_LENGTH","SAFE_ID_PATTERN","NonEmptyString","SafeId","details: AgentToolDetails","toError","details: TeamToolDetails","toError"],"sources":["../src/children/telemetry-port.ts","../src/children/telemetry.ts","../src/children/contracts.ts","../src/children/control/state.ts","../src/children/control/service.ts","../src/children/control/client.ts","../src/children/usage.ts","../src/children/record.ts","../src/children/close.ts","../src/children/projection.ts","../src/children/completion.ts","../src/children/observation.ts","../src/children/delivery.ts","../src/children/models.ts","../src/children/lifecycle.ts","../src/children/manager.ts","../src/children/catalog.ts","../src/children/tools.ts","../src/children/team-tools.ts"],"sourcesContent":["import { isPromise } from 'es-toolkit';\n\nexport interface ChildDeliveryBacklog {\n readonly direction: 'to_child' | 'to_parent';\n readonly pending: number;\n readonly dispatching: number;\n readonly awaitingInclusion: number;\n /** Wall-clock bound; absent when no pending delivery has a recorded enqueue time. */\n readonly oldestPendingEnqueuedAt?: string;\n readonly unknownPendingAge: number;\n}\n\n/** The callback name is retained for compatibility; its data derives from committed Unit facts. */\nexport interface ChildLedgerObservation {\n readonly parentSessionId: string;\n /** Children with a nonterminal Run, including interrupted or parked Runs; not a resource-usage gauge. */\n readonly activeChildren: number;\n readonly deliveries: readonly ChildDeliveryBacklog[];\n}\n\nexport interface ChildDeliveryObservation {\n readonly parentSessionId: string;\n readonly agentId: string;\n readonly childSessionId?: string;\n readonly deliveryId: string;\n readonly orderingKey: number;\n readonly sourceSessionId: string;\n readonly sourceRunId: string;\n readonly direction: 'to_child' | 'to_parent';\n readonly state: 'pending' | 'dispatching' | 'complete' | 'cancelled';\n readonly transition:\n 'enqueued' | 'dispatched' | 'accepted' | 'included' | 'completed' | 'cancelled';\n /** Persisted wall times, never reconstructed as a continuous monotonic span. */\n readonly enqueuedAt?: string;\n readonly dispatchedAt?: string;\n readonly acceptedAt?: string;\n readonly acceptedRunId?: string;\n readonly acceptedSessionId?: string;\n readonly acceptedFactId?: string;\n readonly acceptedCursor?: string;\n readonly includedAt?: string;\n readonly includedModelRequestId?: string;\n readonly includedFactId?: string;\n readonly includedCursor?: string;\n readonly includedSessionId?: string;\n}\n\nexport interface ChildDeliveryPage {\n readonly parentSessionId: string;\n readonly deliveries: readonly Omit<ChildDeliveryObservation, 'transition'>[];\n readonly nextOrderingKey?: number;\n}\n\nexport interface ChildSpawnObservation {\n readonly parentSessionId: string;\n readonly parentRunId: string;\n readonly childSessionId: string;\n readonly agentId: string;\n readonly toolCallId: string;\n readonly effectAttemptId: string;\n}\n\n/** Borrowed passive metadata callbacks. Durable transitions report only after an atomic\n * Unit commit; reopening a Unit does not replay historical transition counters. Throws and\n * accidental rejected promises cannot alter child admission, delivery, or cleanup. */\nexport interface ChildAgentObservationPort {\n childLedgerProjected?(data: ChildLedgerObservation): void;\n childDeliveryCommitted?(data: ChildDeliveryObservation): void;\n childSpawnCommitted?(data: ChildSpawnObservation): void;\n childLedgerDetached?(data: { readonly parentSessionId: string }): void;\n}\n\nexport function observeChildAgents(report: () => void): void {\n try {\n const pending = report();\n if (isPromise(pending)) void pending.catch(() => {});\n } catch {\n // A Host observation has no authority over child execution or durable ownership.\n }\n}\n","import type { UnitRuntime } from '@sorbetai/runtime';\nimport type { ChildAgentCatalog } from './catalog.js';\nimport {\n observeChildAgents,\n type ChildAgentObservationPort,\n type ChildDeliveryBacklog,\n} from './telemetry-port.js';\n\n/** Observe committed facts without acquiring Sessions, scheduling work or writing a second ledger. */\nexport class ChildTelemetry {\n readonly #tracked = new Map<UnitRuntime, { stop: () => void; settled: () => Promise<void> }>();\n\n constructor(\n readonly catalog: ChildAgentCatalog,\n readonly observation: ChildAgentObservationPort | undefined\n ) {}\n\n track(unit: UnitRuntime): void {\n if (this.observation === undefined || this.#tracked.has(unit)) return;\n let after = unit.workSummary().observedUnitSequence;\n let dirty = false;\n let stopped = false;\n let pending: Promise<void> | undefined;\n const scan = async () => {\n while (dirty) {\n dirty = false;\n const current = await this.catalog.read(unit.unitId, after);\n after = current.observedUnitSequence;\n for (const event of current.observations) {\n observeChildAgents(() => {\n if (event.kind === 'spawn') this.observation?.childSpawnCommitted?.(event.data);\n else this.observation?.childDeliveryCommitted?.(event.data);\n });\n }\n const deliveries: ChildDeliveryBacklog[] = [];\n for (const direction of ['to_child', 'to_parent'] as const) {\n const entries = current.deliveries.filter((delivery) => delivery.direction === direction);\n const queued = entries.filter((delivery) => delivery.state === 'pending');\n deliveries.push({\n direction,\n pending: queued.length,\n dispatching: 0,\n awaitingInclusion: entries.filter(\n (delivery) => delivery.state === 'complete' && delivery.includedFactId === undefined\n ).length,\n oldestPendingEnqueuedAt: queued\n .flatMap((delivery) => delivery.enqueuedAt ?? [])\n .sort()[0],\n unknownPendingAge: queued.filter((delivery) => delivery.enqueuedAt === undefined)\n .length,\n });\n }\n observeChildAgents(() =>\n this.observation?.childLedgerProjected?.({\n parentSessionId: unit.unitId,\n activeChildren: current.activeChildren,\n deliveries,\n })\n );\n }\n };\n const schedule = () => {\n pending ??= scan()\n .catch(() => {\n // Diagnostic reads cannot fence execution. Retry from the last observed commit on the next update.\n })\n .finally(() => {\n pending = undefined;\n if (dirty && !stopped) schedule();\n });\n };\n const unsubscribe = unit.subscribeWork(() => {\n dirty = true;\n schedule();\n });\n const stop = () => {\n stopped = true;\n unsubscribe();\n };\n const tracked = { stop, settled: () => pending ?? Promise.resolve() };\n this.#tracked.set(unit, tracked);\n void unit.closed.then(async () => {\n stop();\n await tracked.settled();\n this.#tracked.delete(unit);\n observeChildAgents(() =>\n this.observation?.childLedgerDetached?.({ parentSessionId: unit.unitId })\n );\n });\n }\n\n async close(): Promise<void> {\n const tracked = [...this.#tracked.values()];\n for (const entry of tracked) entry.stop();\n await Promise.all(tracked.map((entry) => entry.settled()));\n this.#tracked.clear();\n }\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { UsageSchema, type NamedStateOwner } from '@sorbetai/context';\nimport type { RunTerminalOutcome } from '@sorbetai/runtime';\n\nconst NonEmptyString = s.str({ minLength: 1 });\n\n/** Named State for every child Session; parents use `ChildAgentManager.stateOwner` instead. */\nexport const subagentIdentity: NamedStateOwner = {\n stateName: 'agent_identity',\n schema: s.str(),\n read: async () => ({\n present: true,\n value: 'You are a subagent.',\n element: { kind: 'text', name: 'agent_identity', text: 'You are a subagent.' },\n }),\n};\n\nexport const ChildAgentNameSchema = s.str({\n minLength: 1,\n maxLength: 32,\n pattern: '\\\\S',\n description:\n 'A short, pleasant, memorable name for this child, such as Mint or Mochi. Give every child a name.',\n});\nexport const ChildAgentDescriptionSchema = s.str({\n minLength: 1,\n maxLength: 100,\n pattern: '\\\\S',\n description:\n 'A short phrase describing what this child is working on. Give every child a description.',\n});\n\nexport const ChildModelUsageRowSchema = s.obj(\n {\n provider: NonEmptyString,\n model: NonEmptyString,\n usage: UsageSchema,\n },\n { open: false }\n);\n\nexport const ChildModelUsageSnapshotSchema = s.obj(\n {\n committedResponses: s.int({ minimum: 0 }),\n activeRequests: s.int({ minimum: 0 }),\n unknownRequests: s.int({ minimum: 0 }),\n totalTokens: s.num({ minimum: 0 }),\n costUsd: s.num({ minimum: 0 }),\n // Absent on ledgers frozen before per-model rows existed.\n models: s.opt(s.arr(ChildModelUsageRowSchema)),\n },\n { open: false }\n);\n\nexport const ClosedChildUsageSchema = s.obj(\n {\n throughRunId: s.opt(NonEmptyString),\n modelUsage: ChildModelUsageSnapshotSchema,\n },\n { open: false }\n);\n\nexport type ClosedChildUsage = Readonly<s.Static<typeof ClosedChildUsageSchema>>;\n\nexport type ChildAgentState =\n 'starting' | 'running' | 'completed' | 'failed' | 'cancelled' | 'closed';\n\nexport interface ChildAgentSnapshot {\n readonly agentId: string;\n readonly childSessionId: string;\n /** Short display name chosen when this child was spawned. Older children may not have one. */\n readonly name?: string;\n /** Short description of the initial assignment. */\n readonly description?: string;\n readonly state: ChildAgentState;\n /** Run of the parent that admitted this child. */\n readonly parentRunId: string;\n /** Parent Tool call that admitted this child; anchors the child in task projections. */\n readonly spawnToolCallId: string;\n readonly createdAt: string;\n readonly modelUsage: ChildModelUsageSnapshot;\n readonly runId?: string;\n readonly outcome?: RunTerminalOutcome;\n readonly response?: {\n readonly text: string;\n readonly truncated: boolean;\n readonly offset?: number;\n readonly nextOffset?: number;\n };\n}\n\ninterface SpawnAgentOptions {\n readonly name?: string;\n readonly description?: string;\n readonly model?: string;\n readonly isBackground?: boolean;\n readonly completionDelivery?: 'auto' | 'manual';\n}\n\nexport type SpawnAgentRequest = { readonly prompt: string } & SpawnAgentOptions;\n\nexport interface SwarmAgentRequest {\n readonly tasks: readonly {\n readonly prompt: string;\n readonly taskId: string;\n readonly name?: string;\n readonly description?: string;\n }[];\n readonly model?: string;\n}\n\nexport interface SendInputRequest {\n readonly agentId: string;\n readonly prompt: string;\n readonly interrupt?: boolean;\n}\n\nexport interface SpawnAgentOutput {\n readonly agent: ChildAgentSnapshot;\n}\n\nexport type SwarmTaskOutput =\n | {\n readonly taskId: string;\n readonly status: 'completed';\n readonly agent: ChildAgentSnapshot;\n }\n | {\n readonly taskId: string;\n readonly status: 'failed';\n readonly agent: ChildAgentSnapshot;\n }\n | {\n readonly taskId: string;\n readonly status: 'failed';\n readonly error: { readonly code: string; readonly message: string };\n }\n | {\n readonly taskId: string;\n readonly status: 'cancelled';\n readonly error: { readonly code: string; readonly message: string };\n };\n\nexport interface SwarmAgentOutput {\n readonly tasks: readonly SwarmTaskOutput[];\n}\n\n/** Accepted input is durable; placement and the Run belong to the child. */\nexport interface SendInputOutput {\n readonly status: 'accepted';\n readonly deliveryId: string;\n readonly agent: ChildAgentSnapshot;\n}\n\nexport interface TeamPeerSnapshot {\n readonly agentId: string;\n readonly state: ChildAgentState;\n}\n\nexport interface ListTeamPeersOutput {\n readonly peers: readonly TeamPeerSnapshot[];\n}\n\nexport interface SendTeamMessageRequest {\n readonly agentId: string;\n readonly prompt: string;\n}\n\nexport interface SendTeamMessageOutput {\n /** The parent ledger owns delivery; the recipient may not have accepted the input yet. */\n readonly status: 'queued';\n readonly deliveryId: string;\n readonly recipient: { readonly agentId: string };\n}\n\nexport interface ListAgentsOutput {\n readonly agents: readonly ChildAgentSnapshot[];\n readonly modelUsage: ChildModelUsageSnapshot;\n}\n\nexport type ChildModelUsageSnapshot = Readonly<s.Static<typeof ChildModelUsageSnapshotSchema>>;\n\nexport interface CloseAgentOutput {\n readonly agent: ChildAgentSnapshot & { readonly state: 'closed' };\n}\n\nexport type ChildAgentFailureCode =\n | 'model_unavailable'\n | 'child_not_found'\n | 'child_closed'\n | 'child_provision_failed'\n | 'child_depth_exceeded'\n | 'child_delivery_conflict'\n | 'child_input_interrupted'\n | 'child_input_pending'\n | 'child_run_not_found'\n | 'team_self_message'\n | 'child_manager_closed';\n\nexport class ChildAgentError extends Error {\n override readonly name = 'ChildAgentError';\n\n constructor(\n readonly code: ChildAgentFailureCode,\n message: string\n ) {\n super(message);\n }\n}\n\nexport function childToolExecutionError(\n cause: Error,\n fallbackCode: 'agent_operation_failed' | 'team_operation_failed',\n fallbackMessage: string\n): Error {\n if (cause instanceof ChildAgentError) {\n return new Error(`${cause.code}: ${cause.message}`, { cause });\n }\n return new Error(`${fallbackCode}: ${fallbackMessage}`, { cause });\n}\n","import type * as Effect from 'effect/Effect';\n\nexport type ChildControlHealth = 'ready' | 'closing' | 'closed';\n\nexport interface ChildOperationIdentity {\n readonly id: symbol;\n readonly settled: Effect.Effect<void>;\n readonly parentSessionId?: string;\n}\n\nexport const childControlKey = (parentSessionId: string, agentId: string): string =>\n `${parentSessionId}:${agentId}`;\n","import * as Context from 'effect/Context';\nimport * as Deferred from 'effect/Deferred';\nimport * as Effect from 'effect/Effect';\nimport * as FiberMap from 'effect/FiberMap';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Ref from 'effect/Ref';\nimport * as Semaphore from 'effect/Semaphore';\nimport * as Exit from 'effect/Exit';\n\nimport { ChildAgentError } from '../contracts.js';\nimport { childControlKey, type ChildControlHealth, type ChildOperationIdentity } from './state.js';\n\ninterface ChildControlService {\n readonly admit: <A, E>(\n parentSessionId: string | undefined,\n operation: Effect.Effect<A, E>\n ) => Effect.Effect<A, E | ChildAgentError>;\n readonly activateParent: (parentSessionId: string) => Effect.Effect<void, ChildAgentError>;\n readonly admitClose: <A, E>(\n parentSessionId: string,\n operation: Effect.Effect<A, E>\n ) => Effect.Effect<A, E | ChildAgentError>;\n readonly interruptParent: (parentSessionId: string) => Effect.Effect<void>;\n readonly beginClose: Effect.Effect<boolean>;\n readonly finishClose: Effect.Effect<void>;\n readonly awaitOperations: Effect.Effect<void>;\n readonly withChildPermit: <A, E, R>(\n parentSessionId: string,\n agentId: string,\n effect: Effect.Effect<A, E, R>\n ) => Effect.Effect<A, E, R>;\n}\n\nexport class ChildControl extends Context.Service<ChildControl, ChildControlService>()(\n 'sorbet/node-agent/children/ChildControl'\n) {\n static readonly layer = Layer.effect(\n ChildControl,\n Effect.gen(function* () {\n const health = yield* Ref.make<ChildControlHealth>('ready');\n const operationGate = yield* Semaphore.make(1);\n const operations = yield* FiberMap.make<symbol, unknown, never>();\n const operationOwners = yield* Ref.make(new Map<symbol, ChildOperationIdentity>());\n const releasedParents = yield* Ref.make<ReadonlySet<string>>(new Set());\n const childPermits = yield* Ref.make(new Map<string, Semaphore.Semaphore>());\n\n const managerClosing = () =>\n new ChildAgentError('child_manager_closed', 'Child agent manager is closing');\n\n const assertReady = Ref.get(health).pipe(\n Effect.flatMap((current) =>\n current === 'ready' ? Effect.void : Effect.fail(managerClosing())\n )\n );\n\n const admit = Effect.fn('ChildControl.admit')(function* <A, E>(\n parentSessionId: string | undefined,\n operation: Effect.Effect<A, E>,\n admission: 'execution' | 'close' = 'execution'\n ): Effect.fn.Return<A, E | ChildAgentError> {\n return yield* Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const result = yield* Deferred.make<Exit.Exit<A, E>>();\n const identity: ChildOperationIdentity = {\n id: Symbol('child-operation'),\n settled: Deferred.await(result).pipe(Effect.asVoid),\n ...(parentSessionId === undefined ? {} : { parentSessionId }),\n };\n yield* restore(operationGate.take(1));\n const fiber = yield* Effect.gen(function* () {\n yield* assertReady;\n if (\n admission === 'execution' &&\n parentSessionId !== undefined &&\n (yield* Ref.get(releasedParents)).has(parentSessionId)\n ) {\n return yield* Effect.fail(managerClosing());\n }\n yield* Ref.update(operationOwners, (current) => {\n const next = new Map(current);\n next.set(identity.id, identity);\n return next;\n });\n const owned = yield* FiberMap.run(\n operations,\n identity.id,\n Effect.exit(restore(operation))\n );\n yield* Effect.sync(() => {\n // One exit observer feeds all waiters. rc.110 can skip a later Fiber.join\n // observer when an earlier join disposes itself during exit notification.\n owned.addObserver((exit) => {\n Effect.runSync(\n Ref.update(operationOwners, (current) => {\n const next = new Map(current);\n next.delete(identity.id);\n return next;\n })\n );\n const outcome: Exit.Exit<A, E> = Exit.isSuccess(exit)\n ? exit.value\n : Exit.failCause(exit.cause);\n Deferred.doneUnsafe(result, Exit.succeed(outcome));\n });\n });\n return owned;\n }).pipe(Effect.ensuring(operationGate.release(1)));\n const exit = yield* restore(Deferred.await(result)).pipe(\n Effect.onInterrupt(() =>\n Effect.sync(() => fiber.interruptUnsafe()).pipe(Effect.andThen(identity.settled))\n )\n );\n return yield* exit;\n })\n );\n });\n\n const semaphoreFor = Effect.fn('ChildControl.semaphoreFor')(function* (\n parentSessionId: string,\n agentId: string\n ) {\n const key = childControlKey(parentSessionId, agentId);\n const existing = (yield* Ref.get(childPermits)).get(key);\n if (existing !== undefined) return existing;\n const created = yield* Semaphore.make(1);\n return yield* Ref.modify(childPermits, (current) => {\n const winner = current.get(key);\n if (winner !== undefined) return [winner, current] as const;\n const next = new Map(current);\n next.set(key, created);\n return [created, next] as const;\n });\n });\n\n const interruptParent = Effect.fn('ChildControl.interruptParent')(function* (\n parentSessionId: string\n ) {\n const identities = yield* Semaphore.withPermit(\n operationGate,\n Ref.updateAndGet(releasedParents, (current) => {\n const next = new Set(current);\n next.add(parentSessionId);\n return next;\n }).pipe(\n Effect.andThen(Ref.get(operationOwners)),\n Effect.map((current) =>\n [...current.values()].filter(\n (identity) => identity.parentSessionId === parentSessionId\n )\n )\n )\n );\n yield* Effect.sync(() => {\n for (const identity of identities) {\n const fiber = FiberMap.getUnsafe(operations, identity.id);\n if (Option.isSome(fiber)) fiber.value.interruptUnsafe();\n }\n });\n yield* Effect.forEach(identities, (identity) => identity.settled, {\n concurrency: 'unbounded',\n discard: true,\n });\n });\n\n return ChildControl.of({\n admit,\n // Host close holds durable ownership but must leave execution fenced.\n admitClose: (parentSessionId, operation) => admit(parentSessionId, operation, 'close'),\n activateParent: (parentSessionId) =>\n Semaphore.withPermit(\n operationGate,\n assertReady.pipe(\n Effect.andThen(\n Ref.update(releasedParents, (current) => {\n const next = new Set(current);\n next.delete(parentSessionId);\n return next;\n })\n )\n )\n ),\n interruptParent,\n beginClose: Semaphore.withPermit(\n operationGate,\n Ref.modify(health, (current) =>\n current === 'closed' ? ([false, current] as const) : ([true, 'closing'] as const)\n )\n ),\n finishClose: Ref.set(health, 'closed'),\n awaitOperations: FiberMap.awaitEmpty(operations),\n withChildPermit: (parentSessionId, agentId, effect) =>\n semaphoreFor(parentSessionId, agentId).pipe(\n Effect.flatMap((semaphore) => Semaphore.withPermit(semaphore, effect))\n ),\n });\n })\n );\n}\n","import toError from 'ensure-error';\nimport * as Effect from 'effect/Effect';\nimport type * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport { ChildControl } from './service.js';\n\nexport type ChildControlOperation<A> = (signal: AbortSignal) => PromiseLike<A>;\n\n/**\n * Signals Promise cancellation on interruption, then keeps the fiber alive\n * until that same Promise settles. Child close and delivery replacement rely\n * on this stronger abort-and-drain contract; ordinary interruptible Session\n * ports only signal cancellation and stop awaiting.\n */\nconst operationEffect = <A>(\n span: string,\n operation: ChildControlOperation<A>\n): Effect.Effect<A, Error> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const controller = new AbortController();\n const result = Promise.resolve().then(() => operation(controller.signal));\n const awaitResult = Effect.tryPromise({ try: () => result, catch: toError });\n return yield* restore(awaitResult).pipe(\n Effect.onInterrupt(() =>\n Effect.sync(() => controller.abort()).pipe(Effect.andThen(awaitResult), Effect.ignore)\n )\n );\n })\n ).pipe(Effect.withSpan(span));\n\n/** Promise-facing boundary for the Effect-owned child control plane. */\nexport class ChildControlClient {\n readonly #runtime: ManagedRuntime.ManagedRuntime<ChildControl, never>;\n readonly #control: ChildControl['Service'];\n\n constructor(runtime: ManagedRuntime.ManagedRuntime<ChildControl, never>) {\n this.#runtime = runtime;\n this.#control = runtime.runSync(ChildControl);\n }\n\n admit<A>(\n parentSessionId: string | undefined,\n operationName: string,\n operation: ChildControlOperation<A>,\n signal?: AbortSignal\n ): Promise<A> {\n return this.#runtime.runPromise(\n this.#control.admit(\n parentSessionId,\n operationEffect(`ChildOperation.${operationName}`, operation)\n ),\n signal === undefined ? undefined : { signal }\n );\n }\n\n activateParent(parentSessionId: string): Promise<void> {\n return this.#runtime.runPromise(this.#control.activateParent(parentSessionId));\n }\n\n admitClose<A>(\n parentSessionId: string,\n operationName: string,\n operation: ChildControlOperation<A>\n ): Promise<A> {\n return this.#runtime.runPromise(\n this.#control.admitClose(\n parentSessionId,\n operationEffect(`ChildOperation.${operationName}`, operation)\n )\n );\n }\n\n interruptParent(parentSessionId: string): Promise<void> {\n return this.#runtime.runPromise(this.#control.interruptParent(parentSessionId));\n }\n\n withChildPermit<A>(\n parentSessionId: string,\n agentId: string,\n operationName: string,\n operation: ChildControlOperation<A>,\n signal?: AbortSignal\n ): Promise<A> {\n return this.#runtime.runPromise(\n this.#control.withChildPermit(\n parentSessionId,\n agentId,\n operationEffect(`ChildPermit.${operationName}`, operation)\n ),\n signal === undefined ? undefined : { signal }\n );\n }\n\n waitFor(\n operationName: string,\n operations: readonly ChildControlOperation<void>[],\n condition: 'any' | 'all',\n signal?: AbortSignal,\n timeoutMs?: number\n ): Promise<'terminal' | 'timeout'> {\n return this.#runtime.runPromise(\n this.#waitForEffect(operationName, operations, condition, timeoutMs),\n signal === undefined ? undefined : { signal }\n );\n }\n\n async close(\n parentSessionIds: readonly string[],\n releaseParent: (id: string) => Promise<void>\n ): Promise<void> {\n const started = await this.#runtime.runPromise(this.#control.beginClose);\n if (!started) return;\n const failures: Error[] = [];\n const collect = async (operation: PromiseLike<void>): Promise<void> => {\n try {\n await operation;\n } catch (cause) {\n failures.push(toError(cause));\n }\n };\n const releaseParents = async (): Promise<void> => {\n const results = await Promise.allSettled(\n parentSessionIds.map((parentSessionId) =>\n Promise.resolve().then(() => releaseParent(parentSessionId))\n )\n );\n for (const result of results) {\n if (result.status === 'rejected') failures.push(toError(result.reason));\n }\n };\n await releaseParents();\n await collect(this.#runtime.runPromise(this.#control.awaitOperations));\n await releaseParents();\n if (failures.length > 0) throw new AggregateError(failures, 'Child agent shutdown failed');\n await this.#runtime.runPromise(this.#control.finishClose);\n }\n\n dispose(): Promise<void> {\n return this.#runtime.dispose();\n }\n\n readonly #waitForEffect = Effect.fn('ChildControlClient.waitFor')(function* (\n operationName: string,\n operations: readonly ChildControlOperation<void>[],\n condition: 'any' | 'all',\n timeoutMs: number | undefined\n ) {\n const waits = operations.map((operation) =>\n operationEffect(`ChildWait.${operationName}`, operation)\n );\n const terminal = (\n condition === 'any'\n ? Effect.raceAllFirst(waits)\n : Effect.all(waits, { concurrency: 'unbounded', discard: true })\n ).pipe(Effect.as('terminal' as const));\n if (timeoutMs === undefined) return yield* terminal;\n return yield* Effect.raceFirst(\n terminal,\n Effect.sleep(timeoutMs).pipe(Effect.as('timeout' as const))\n );\n });\n}\n","import type { Usage } from '@sorbetai/context';\nimport type { RunInspection } from '@sorbetai/runtime';\nimport type { ChildModelUsageSnapshot } from './contracts.js';\n\n/** Journal-authoritative per-model rows, so a Host can account child spend by model. */\nexport function projectModelUsage(runs: readonly RunInspection[]): ChildModelUsageSnapshot {\n let committedResponses = 0;\n let activeRequests = 0;\n let unknownRequests = 0;\n let totalTokens = 0;\n let costUsd = 0;\n const models = new Map<string, { provider: string; model: string; usage: Usage }>();\n for (const run of runs) {\n for (const request of run.modelRequests) {\n if (request.status === 'requested') {\n activeRequests += 1;\n continue;\n }\n if (request.status === 'unknown') {\n unknownRequests += 1;\n continue;\n }\n committedResponses += 1;\n const message = request.response.payload.message;\n totalTokens += message.usage.totalTokens;\n costUsd += message.usage.cost.total;\n addModelUsage(models, message.provider, message.model, message.usage);\n }\n }\n return {\n committedResponses,\n activeRequests,\n unknownRequests,\n totalTokens,\n costUsd,\n models: [...models.values()],\n };\n}\n\nexport function addModelUsage(\n models: Map<string, { provider: string; model: string; usage: Usage }>,\n provider: string,\n model: string,\n usage: Usage\n): void {\n const key = JSON.stringify([provider, model]);\n const current = models.get(key);\n if (current === undefined) {\n models.set(key, { provider, model, usage: structuredClone(usage) });\n return;\n }\n addUsage(current.usage, usage);\n}\n\nexport function addUsage(target: Usage, usage: Usage): void {\n target.input += usage.input;\n target.output += usage.output;\n target.cacheRead += usage.cacheRead;\n target.cacheWrite += usage.cacheWrite;\n target.totalTokens += usage.totalTokens;\n if (usage.cacheWrite1h !== undefined)\n target.cacheWrite1h = (target.cacheWrite1h ?? 0) + usage.cacheWrite1h;\n if (usage.reasoning !== undefined) target.reasoning = (target.reasoning ?? 0) + usage.reasoning;\n target.cost.input += usage.cost.input;\n target.cost.output += usage.cost.output;\n target.cost.cacheRead += usage.cost.cacheRead;\n target.cost.cacheWrite += usage.cost.cacheWrite;\n target.cost.total += usage.cost.total;\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { ApprovalModeSchema, ToolPermissionPolicySchema } from '@sorbetai/runtime';\nimport { ChildAgentDescriptionSchema, ChildAgentNameSchema } from './contracts.js';\n\n/** Applied to the child's first Run. Open: hosts persist their own fields, such as a sandbox mode. */\nexport const ChildExecutionPolicySchema = s.obj(\n {\n toolPermissions: ToolPermissionPolicySchema,\n approvalMode: s.opt(ApprovalModeSchema),\n },\n { open: true }\n);\nexport type ChildExecutionPolicy = Readonly<s.Static<typeof ChildExecutionPolicySchema>>;\n\nconst Identity = s.str({ minLength: 1 });\n/** Immutable imported receipts; ongoing delivery is owned only by Unit Submissions. */\nexport const ImportedChildDeliverySchema = s.obj(\n {\n deliveryId: Identity,\n orderingKey: s.int({ minimum: 1 }),\n direction: s.union([s.lit('to_child'), s.lit('to_parent')]),\n sourceSessionId: Identity,\n sourceRunId: Identity,\n state: s.union([s.lit('pending'), s.lit('complete'), s.lit('cancelled')]),\n enqueuedAt: s.opt(s.str()),\n dispatchedAt: s.opt(s.str()),\n acceptedAt: s.opt(s.str()),\n acceptedRunId: s.opt(Identity),\n acceptedSessionId: s.opt(Identity),\n acceptedFactId: s.opt(Identity),\n acceptedMessageId: s.opt(Identity),\n acceptedCursor: s.opt(Identity),\n includedAt: s.opt(s.str()),\n includedModelRequestId: s.opt(Identity),\n includedSessionId: s.opt(Identity),\n includedFactId: s.opt(Identity),\n includedCursor: s.opt(Identity),\n },\n { open: true }\n);\nexport const ChildTaskInputSchema = s.obj(\n {\n agentId: Identity,\n childSessionId: Identity,\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n parentSessionId: Identity,\n parentRunId: Identity,\n spawnToolCallId: Identity,\n spawnEffectAttemptId: Identity,\n depth: s.lit(1),\n providerId: Identity,\n modelId: Identity,\n executionPolicy: ChildExecutionPolicySchema,\n ordinaryToolNames: s.arr(Identity, { uniqueItems: true }),\n initialMode: s.union([s.lit('foreground'), s.lit('background')]),\n initialCompletionDelivery: s.union([s.lit('auto'), s.lit('manual')]),\n /** Legacy children recorded a full context fork; decoding must keep accepting it. */\n contextMode: s.union([s.lit('fresh'), s.lit('full')]),\n createdAt: s.str({ format: 'date-time' }),\n initialSubmissionId: s.opt(Identity),\n imported: s.opt(\n s.obj(\n {\n initialRunId: s.opt(Identity),\n orderingKeyFloor: s.int({ minimum: 0 }),\n deliveries: s.arr(ImportedChildDeliverySchema),\n },\n { open: true }\n )\n ),\n },\n { open: true }\n);\nexport type ChildTaskInput = s.Static<typeof ChildTaskInputSchema>;\n","import * as s from '@earendil-works/pi-schema';\nimport { decode } from '@sorbetai/schema';\nimport { isEqual } from 'es-toolkit';\nimport {\n defineTask,\n projectSessionInspection,\n type UnitRuntime,\n type UnitTx,\n} from '@sorbetai/runtime';\n\nimport { ClosedChildUsageSchema } from './contracts.js';\nimport { ChildTaskInputSchema, type ChildTaskInput } from './record.js';\nimport { projectModelUsage } from './usage.js';\n\n// The persisted v1 phase is named 'closing' even while waiting for the close\n// request. Only session.closing fences new input; this checkpoint holds signals.\nconst CloseSignals = s.obj(\n {\n phase: s.lit('closing'),\n close: s.str(),\n released: s.str(),\n },\n { open: true }\n);\nconst Checkpoint = s.union([s.obj({ phase: s.lit('open') }, { open: true }), CloseSignals]);\n\nfunction waitForCloseRequest(tx: UnitTx) {\n const close = tx.createSignal({ key: 'close', type: 'host-command', payload: null });\n const released = tx.createSignal({ key: 'released', type: 'host-command', payload: null });\n return {\n status: 'waiting' as const,\n checkpoint: { phase: 'closing' as const, close, released },\n on: [{ signal: close }],\n policy: 'allSettled' as const,\n };\n}\n\n/** The Host handles close intent and confirms resource release; phases perform no resource I/O. */\nexport const childTaskDefinition = defineTask({\n name: 'sorbet.agent',\n version: 1,\n inputSchema: ChildTaskInputSchema,\n checkpointSchema: Checkpoint,\n resultSchema: ClosedChildUsageSchema,\n initial: () => ({ phase: 'open' as const }),\n phases: {\n open: async (_task, runtime) => {\n await runtime.commit(waitForCloseRequest);\n },\n closing: async (task, runtime) => {\n await runtime.commit((tx) => {\n const close = tx.signal(task.checkpoint.close);\n if (close?.state.status !== 'resolved') throw new Error('Child close was not requested');\n const released = tx.signal(task.checkpoint.released);\n if (released?.state.status !== 'resolved')\n return {\n status: 'waiting',\n checkpoint: task.checkpoint,\n on: [{ signal: task.checkpoint.released }],\n policy: 'allSettled',\n };\n const result = decode(ClosedChildUsageSchema, released.state.result);\n tx.closeSession(task.input.childSessionId);\n return { status: 'completed', result };\n });\n },\n },\n abort: async (task, runtime) => {\n await runtime.commit(() => ({\n status: 'aborted',\n reason: task.abortRequested?.reason ?? 'Child observation stopped',\n }));\n },\n});\n\n/** Fence placement in the same commit as close intent; cleanup can continue after a crash. */\nexport function stageChildClose(\n tx: UnitTx,\n anchorId: string,\n reason: string,\n commandId: string\n): void {\n const task = tx.getTask(anchorId);\n if (task?.kind !== childTaskDefinition.name) throw new Error('Child anchor is missing');\n const child = decode(ChildTaskInputSchema, task.input);\n tx.beginSessionClose(child.childSessionId);\n if (task.state.status === 'terminal') return;\n const checkpoint = decode(CloseSignals, task.checkpoint);\n if (tx.signal(checkpoint.close)?.state.status === 'resolved') return;\n tx.resolveSignal(checkpoint.close, reason, commandId);\n}\n\n/** Also used by the offline importer for already-created Sessions; it never starts a Run. */\nexport function stageChildAnchor(tx: UnitTx, child: ChildTaskInput): string {\n return tx.createTask(childTaskDefinition, child, {\n key: `spawn:${child.spawnEffectAttemptId}`,\n owner: { session: child.parentSessionId },\n background: true,\n initialize: waitForCloseRequest,\n });\n}\n\n/** Finish committed close intent without constructing a Session, Provider or Tool. */\nexport async function finishChildClose(\n unit: UnitRuntime,\n sessionId: string,\n release: () => Promise<void>,\n signal: AbortSignal\n): Promise<void> {\n signal.throwIfAborted();\n const session = unit.sessions().find((entry) => entry.sessionId === sessionId);\n if (session?.closed) return;\n if (!session?.closing) throw new Error('Child close intent is missing');\n const anchor = unit\n .inspect()\n .tasks.find(\n (task) =>\n task.kind === childTaskDefinition.name &&\n decode(ChildTaskInputSchema, task.input).childSessionId === sessionId\n );\n if (anchor === undefined) throw new Error('Closing child has no Task anchor');\n const reason = 'Child Session closed';\n const owned = unit\n .inspect()\n .tasks.filter(\n (task) => task.state.status !== 'terminal' && isEqual(task.owner, { session: sessionId })\n );\n // Stop delivery/schedule phases before resource disposal can publish process exit.\n // The anchor belongs to the parent and stays alive to commit final closure.\n for (const task of owned) await unit.abortTask(task.taskId, reason, anchor.taskId);\n await release();\n signal.throwIfAborted();\n const facts = await unit.participant(sessionId);\n const interrupted = await facts.unfinishedRun();\n if (interrupted !== undefined) await facts.abandonInterruptedRun(interrupted.runId, reason);\n for (const pending of await facts.pendingSubmissions())\n await (\n await unit.submission(pending.accepted.operationId)\n )?.withdraw({\n reason,\n commandId: `child-close:${anchor.taskId}:${pending.accepted.operationId}`,\n });\n for (const task of owned) await unit.task(task.taskId)?.settled(signal);\n const handle = unit.task(anchor.taskId);\n if (handle === undefined) throw new Error('Child anchor disappeared');\n if (handle.record().abortRequested !== undefined) await handle.settled(signal);\n if (handle.record().state.status === 'terminal') {\n await unit.closeSession(sessionId);\n return;\n }\n const checkpoint = decode(childTaskDefinition.checkpointSchema, handle.record().checkpoint);\n if (checkpoint.phase !== 'closing') throw new Error('Child close was not initialized');\n const history = await facts.journalSnapshot();\n const { runs } = projectSessionInspection(\n sessionId,\n { facts: history, cursor: history.at(-1)?.cursor, hasMore: false },\n { modelRequests: 'omit' }\n );\n const latest = runs.at(-1);\n await unit.group((group) =>\n group.tasks((tx) => {\n const current = tx.getTask(anchor.taskId);\n if (current === undefined) throw new Error('Child anchor disappeared');\n if (current.state.status === 'terminal' || current.abortRequested !== undefined) return;\n tx.resolveSignal(\n checkpoint.released,\n {\n ...(latest === undefined ? {} : { throughRunId: latest.lifecycle.runId }),\n modelUsage: projectModelUsage(runs),\n },\n `child-released:${anchor.taskId}`\n );\n })\n );\n // Observation may be aborted while cleanup drains. It cannot revoke close intent.\n const outcome = await handle.settled(signal);\n if (outcome.status !== 'completed') await unit.closeSession(sessionId);\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { check, decode } from '@sorbetai/schema';\nimport {\n isRunTerminalFactKind,\n RunInputProjection,\n type JournalFact,\n type UnitRecord,\n} from '@sorbetai/runtime';\nimport { cloneDeep } from 'es-toolkit';\nimport { CompletionStateSchema } from './completion-state.js';\nexport { CompletionStateSchema } from './completion-state.js';\n\nimport type {\n ChildDeliveryObservation,\n ChildDeliveryPage,\n ChildSpawnObservation,\n} from './telemetry-port.js';\nimport { childTaskDefinition } from './close.js';\nimport { ClosedChildUsageSchema, type ClosedChildUsage } from './contracts.js';\nimport { ChildTaskInputSchema, type ChildTaskInput } from './record.js';\n\nexport interface ChildAgentEntry extends ChildTaskInput {\n readonly anchorId: string;\n readonly initialRunId?: string;\n readonly closing: boolean;\n readonly closed: boolean;\n readonly closedUsage?: ClosedChildUsage;\n}\n\nconst Completion = s.obj(\n {\n agentId: s.str(),\n childSessionId: s.str(),\n childRunId: s.str(),\n },\n { open: true }\n);\nconst ParentInput = s.obj(\n {\n agentId: s.str(),\n parentSessionId: s.str(),\n parentRunId: s.str(),\n },\n { open: true }\n);\nconst TeamInput = s.obj(\n {\n recipientAgentId: s.str(),\n senderSessionId: s.str(),\n senderRunId: s.str(),\n },\n { open: true }\n);\ntype Delivery = ChildDeliveryPage['deliveries'][number];\n\ntype Observation =\n | { kind: 'spawn'; data: ChildSpawnObservation }\n | { kind: 'delivery'; data: ChildDeliveryObservation };\n\n/** Rebuildable facts only. The owning catalog drops this projection with the writer epoch. */\nexport class ChildProjection {\n readonly #inputs = new Map<string, RunInputProjection>();\n readonly anchors = new Map<string, ChildTaskInput>();\n readonly closed = new Set<string>();\n readonly closing = new Set<string>();\n readonly usages = new Map<string, ClosedChildUsage>();\n readonly deliveries = new Map<string, Delivery>();\n readonly messages = new Map<string, string>();\n readonly placements = new Map<string, string>();\n readonly activeRuns = new Map<string, string>();\n readonly completions = new Map<string, { agentId: string; runId: string; cursor: number }>();\n readonly observations: { sequence: number; event: Observation }[] = [];\n orderingKeyFloor = 0;\n\n constructor(\n readonly parentSessionId: string,\n readonly observeAfter: number\n ) {}\n\n apply(record: UnitRecord): void {\n const {\n anchors,\n closed,\n closing,\n usages,\n deliveries,\n messages,\n placements,\n activeRuns,\n completions,\n parentSessionId,\n } = this;\n const observeDelivery = (\n sequence: number,\n delivery: Delivery,\n transition: ChildDeliveryObservation['transition']\n ) => {\n this.observe(sequence, { kind: 'delivery', data: { ...delivery, transition } });\n };\n const { entry } = record;\n if (entry.scope === 'unit') {\n const fact = entry.fact;\n switch (fact.kind) {\n case 'task.created':\n case 'task.imported':\n if (fact.payload.kind === childTaskDefinition.name) {\n const child = decode(ChildTaskInputSchema, fact.payload.input);\n anchors.set(fact.taskId, child);\n this.orderingKeyFloor = Math.max(\n this.orderingKeyFloor,\n child.imported?.orderingKeyFloor ?? 0\n );\n for (const delivery of child.imported?.deliveries ?? []) {\n const { acceptedMessageId, ...fields } = delivery;\n if (acceptedMessageId !== undefined)\n messages.set(acceptedMessageId, delivery.deliveryId);\n const receipt = {\n ...fields,\n agentId: child.agentId,\n childSessionId: child.childSessionId,\n parentSessionId,\n };\n deliveries.set(delivery.deliveryId, receipt);\n if (delivery.direction === 'to_parent')\n completions.set(delivery.deliveryId, {\n agentId: child.agentId,\n runId: delivery.sourceRunId,\n cursor: delivery.orderingKey,\n });\n }\n this.observe(record.unitSequence, {\n kind: 'spawn',\n data: {\n parentSessionId: child.parentSessionId,\n parentRunId: child.parentRunId,\n childSessionId: child.childSessionId,\n agentId: child.agentId,\n toolCallId: child.spawnToolCallId,\n effectAttemptId: child.spawnEffectAttemptId,\n },\n });\n if (fact.kind === 'task.imported')\n usages.set(fact.taskId, decode(ClosedChildUsageSchema, fact.payload.result));\n }\n break;\n case 'task.settled':\n if (anchors.has(fact.taskId) && fact.payload.outcome.status === 'completed')\n usages.set(fact.taskId, decode(ClosedChildUsageSchema, fact.payload.outcome.result));\n break;\n case 'session.closing':\n closing.add(fact.payload.sessionId);\n break;\n case 'session.closed':\n closed.add(fact.payload.sessionId);\n closing.delete(fact.payload.sessionId);\n break;\n }\n return;\n }\n const fact = entry.fact;\n if (fact.kind === 'run.accepted') activeRuns.set(fact.runId, fact.sessionId);\n if (isRunTerminalFactKind(fact.kind) && fact.runId !== undefined) activeRuns.delete(fact.runId);\n if (fact.kind === 'submission.accepted') {\n const { input } = fact.payload;\n const base = {\n parentSessionId,\n deliveryId: fact.operationId,\n orderingKey:\n deliveries.get(fact.operationId)?.orderingKey ??\n record.unitSequence + this.orderingKeyFloor,\n state: 'pending' as const,\n enqueuedAt: fact.recordedAt,\n ...deliveries.get(fact.operationId),\n };\n // SDK hosts own Submission provenance. A matching label alone is not a child receipt.\n if (\n input.source.kind === 'node-agent.child-completion' &&\n fact.sessionId === parentSessionId &&\n check(Completion, input.source.data)\n ) {\n const data = input.source.data;\n deliveries.set(fact.operationId, {\n ...base,\n direction: 'to_parent',\n agentId: data.agentId,\n childSessionId: data.childSessionId,\n sourceSessionId: data.childSessionId,\n sourceRunId: data.childRunId,\n });\n completions.set(fact.operationId, {\n agentId: data.agentId,\n runId: data.childRunId,\n cursor: base.orderingKey,\n });\n } else if (\n input.source.kind === 'node-agent.parent-input' &&\n check(ParentInput, input.source.data)\n ) {\n const data = input.source.data;\n if (data.parentSessionId === parentSessionId)\n deliveries.set(fact.operationId, {\n ...base,\n direction: 'to_child',\n agentId: data.agentId,\n childSessionId: fact.sessionId,\n sourceSessionId: data.parentSessionId,\n sourceRunId: data.parentRunId,\n });\n } else if (\n input.source.kind === 'node-agent.team-message' &&\n check(TeamInput, input.source.data)\n ) {\n const data = input.source.data;\n deliveries.set(fact.operationId, {\n ...base,\n direction: 'to_child',\n agentId: data.recipientAgentId,\n childSessionId: fact.sessionId,\n sourceSessionId: data.senderSessionId,\n sourceRunId: data.senderRunId,\n });\n }\n }\n if (fact.kind === 'submission.accepted') {\n const delivery = deliveries.get(fact.operationId);\n if (delivery !== undefined) observeDelivery(record.unitSequence, delivery, 'enqueued');\n }\n const inputs = this.#inputs.get(fact.sessionId) ?? new RunInputProjection();\n this.#inputs.set(fact.sessionId, inputs);\n const input = inputs.apply(fact);\n if (input !== undefined) {\n const deliveryId = input.payload.deliveryId;\n if (\n deliveryId !== undefined &&\n [...anchors.values()].some((child) => child.initialSubmissionId === deliveryId)\n )\n placements.set(deliveryId, input.runId);\n const previous = deliveryId === undefined ? undefined : deliveries.get(deliveryId);\n if (previous !== undefined) {\n deliveries.set(previous.deliveryId, {\n ...previous,\n state: 'complete',\n acceptedAt: input.recordedAt,\n acceptedRunId: input.runId,\n acceptedSessionId: input.sessionId,\n acceptedFactId: input.id,\n acceptedCursor: input.cursor,\n });\n const accepted = deliveries.get(previous.deliveryId);\n if (accepted !== undefined) {\n observeDelivery(record.unitSequence, accepted, 'accepted');\n observeDelivery(record.unitSequence, accepted, 'completed');\n }\n messages.set(input.payload.messageId, previous.deliveryId);\n }\n }\n if (fact.kind === 'submission.withdrawn') {\n const previous = deliveries.get(fact.operationId);\n if (previous !== undefined) {\n const cancelled = { ...previous, state: 'cancelled' as const };\n deliveries.set(fact.operationId, cancelled);\n observeDelivery(record.unitSequence, cancelled, 'cancelled');\n }\n }\n if (fact.kind === 'model.requested') {\n for (const source of fact.payload.conversationSources ?? []) {\n if (source.kind !== 'conversation') continue;\n const id = messages.get(source.reference.messageId);\n const included = id === undefined ? undefined : include(deliveries, id, fact);\n if (included !== undefined) observeDelivery(record.unitSequence, included, 'included');\n }\n if (fact.sessionId !== parentSessionId) return;\n const state = fact.payload.contextSnapshot.namedStates.find(\n (item) => item.stateName === 'child_runs'\n );\n if (state?.present === true && check(CompletionStateSchema, state.value)) {\n for (const result of state.value.results) {\n const included = include(deliveries, `to-parent-${result.agentId}-${result.runId}`, fact);\n if (included !== undefined) observeDelivery(record.unitSequence, included, 'included');\n }\n }\n }\n }\n\n snapshot(tail: number, afterSequence: number) {\n const { anchors, closed, closing, usages, placements, activeRuns, completions, deliveries } =\n this;\n if (Number.isFinite(afterSequence)) {\n const first = this.observations.findIndex((item) => item.sequence > afterSequence);\n this.observations.splice(0, first < 0 ? this.observations.length : first);\n }\n return cloneDeep({\n children: [...anchors].map(([anchorId, input]): ChildAgentEntry => ({\n ...input,\n anchorId,\n initialRunId:\n input.initialSubmissionId === undefined\n ? input.imported?.initialRunId\n : placements.get(input.initialSubmissionId),\n closing: closing.has(input.childSessionId),\n closed: closed.has(input.childSessionId),\n closedUsage: usages.get(anchorId),\n })),\n observations: this.observations\n .filter((item) => item.sequence > afterSequence)\n .map((item) => item.event),\n observedUnitSequence: tail,\n activeChildren: [...anchors.values()].filter((child) =>\n [...activeRuns.values()].includes(child.childSessionId)\n ).length,\n completions: [...completions.values()].sort((left, right) => left.cursor - right.cursor),\n deliveries: [...deliveries.values()].sort(\n (left, right) => left.orderingKey - right.orderingKey\n ),\n });\n }\n\n private observe(sequence: number, event: Observation): void {\n if (sequence > this.observeAfter) this.observations.push({ sequence, event });\n }\n}\n\nfunction include(\n deliveries: Map<string, Delivery>,\n id: string,\n fact: Extract<JournalFact, { kind: 'model.requested' }>\n): Delivery | undefined {\n const previous = deliveries.get(id);\n if (previous === undefined || previous.includedFactId !== undefined) return;\n const included = {\n ...previous,\n includedAt: fact.recordedAt,\n includedModelRequestId: fact.payload.modelRequestId,\n includedFactId: fact.id,\n includedCursor: fact.cursor,\n includedSessionId: fact.sessionId,\n };\n deliveries.set(id, included);\n return included;\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { defineTask, type UnitTx } from '@sorbetai/runtime';\n\nimport type { ChildTaskInput } from './record.js';\n\nconst Identity = s.str({ minLength: 1 });\nconst ReporterIdentity = { agentId: Identity, childSessionId: Identity, parentSessionId: Identity };\nconst ReporterInput = s.union([\n s.obj(\n {\n ...ReporterIdentity,\n kind: s.opt(s.lit('submission')),\n submissionId: Identity,\n },\n { open: true }\n ),\n s.obj({ ...ReporterIdentity, kind: s.lit('legacy-run'), legacyRunId: Identity }, { open: true }),\n]);\nconst Report = s.obj({ phase: s.lit('report') }, { open: true });\n\n/** Submission settlement, completion acceptance and reporter settlement use durable identities. */\nexport const childReporterDefinition = defineTask({\n name: 'sorbet.agent.reporter',\n version: 1,\n inputSchema: ReporterInput,\n checkpointSchema: Report,\n resultSchema: s.obj(\n {\n runId: s.opt(s.str()),\n deliveryId: s.opt(s.str()),\n },\n { open: true }\n ),\n initial: () => ({ phase: 'report' as const }),\n phases: {\n report: async (task, runtime) => {\n await runtime.commit(\n (tx) => {\n const target =\n task.input.kind !== 'legacy-run'\n ? tx.submission(task.input.submissionId)\n : tx.run(task.input.legacyRunId);\n if (target === undefined) throw new Error('Child input or imported Run is missing');\n if (!target.ended)\n return {\n status: 'waiting',\n checkpoint: task.checkpoint,\n on: [\n task.input.kind !== 'legacy-run'\n ? { submission: task.input.submissionId }\n : { run: task.input.legacyRunId },\n ],\n policy: 'allSettled',\n };\n const runId =\n task.input.kind !== 'legacy-run'\n ? tx.submission(task.input.submissionId)?.runId\n : task.input.legacyRunId;\n if (runId === undefined) return { status: 'completed', result: {} };\n const deliveryId = `to-parent-${task.input.agentId}-${runId}`;\n tx.submit(\n task.input.parentSessionId,\n {\n kind: 'context-event',\n deliveryId,\n contextSources: [],\n source: {\n kind: 'node-agent.child-completion',\n data: {\n agentId: task.input.agentId,\n childSessionId: task.input.childSessionId,\n childRunId: runId,\n completionDeliveryId: deliveryId,\n },\n },\n },\n { whenBusy: 'followUp', preserveSource: true }\n );\n return { status: 'completed', result: { runId, deliveryId } };\n },\n { sessions: [task.input.parentSessionId] }\n );\n },\n },\n abort: async (task, runtime) => {\n await runtime.commit(() => ({\n status: 'aborted',\n reason: task.abortRequested?.reason ?? 'Child completion stopped',\n }));\n },\n});\n\n/** Call in the same group that accepts the child input, when automatic delivery is enabled. */\nexport function stageChildReporter(\n tx: UnitTx,\n anchorId: string,\n input: s.Static<typeof ReporterInput>\n): string {\n if (\n input.kind !== 'legacy-run' &&\n tx.submission(input.submissionId)?.sessionId !== input.childSessionId\n )\n throw new Error('Reporter Submission belongs to another child');\n return tx.createTask(childReporterDefinition, input, {\n key:\n input.kind !== 'legacy-run'\n ? `report:${input.submissionId}`\n : `report-run:${input.legacyRunId}`,\n owner: { task: anchorId },\n background: true,\n initialize: () => ({\n status: 'waiting',\n checkpoint: { phase: 'report' as const },\n on: [\n input.kind !== 'legacy-run'\n ? { submission: input.submissionId }\n : { run: input.legacyRunId },\n ],\n policy: 'allSettled',\n }),\n });\n}\n\n/**\n * Input acceptance and its completion reporter share one commit. Manual children\n * never create reporters. Foreground children omit the initial reporter.\n * Initial placement also records the child's execution policy.\n */\nexport function stageChildInput(\n tx: UnitTx,\n child: ChildTaskInput,\n anchorId: string,\n input: Parameters<UnitTx['submit']>[1],\n options: {\n readonly initial?: boolean;\n } = {}\n): void {\n const runConfiguration = options.initial\n ? {\n toolPermissionPolicy: child.executionPolicy.toolPermissions,\n approvalMode: child.executionPolicy.approvalMode,\n }\n : undefined;\n // Child input steers like any other Session input: it lands at the next Tool boundary of a\n // running child and starts a Run when the child is idle.\n tx.submit(child.childSessionId, input, {\n whenBusy: 'steer',\n preserveSource: true,\n runConfiguration,\n });\n if (\n child.initialCompletionDelivery === 'auto' &&\n (!options.initial || child.initialMode === 'background')\n )\n stageChildReporter(tx, anchorId, {\n agentId: child.agentId,\n childSessionId: child.childSessionId,\n parentSessionId: child.parentSessionId,\n submissionId: input.deliveryId,\n });\n}\n","import { addModelUsage, projectModelUsage } from './usage.js';\nimport { isRunTerminalFactKind, type SessionInspection } from '@sorbetai/runtime';\nimport type { NamedStateOwner, Usage } from '@sorbetai/context';\nimport type { ChildAgentEntry, ChildAgentCatalog } from './catalog.js';\nimport { CompletionStateSchema } from './projection.js';\nimport { childReporterDefinition } from './completion.js';\nimport { decode } from '@sorbetai/schema';\nimport type { UnitRuntime, WaitMember } from '@sorbetai/runtime';\n\nimport {\n ChildAgentError,\n type ChildAgentSnapshot,\n type ChildModelUsageSnapshot,\n type ClosedChildUsage,\n type ListAgentsOutput,\n} from './contracts.js';\nimport type { ChildControlClient } from './control/client.js';\nimport type { ChildAgentHost, ChildSessionRuntime } from './host.js';\nimport type { ChildOperation } from './operations.js';\n\nconst MAX_RESPONSE_CHARACTERS = 30_000;\n\nconst COMPLETION_STATE_LIMIT = 64;\n\ninterface ChildObservationCoordinatorOptions {\n readonly control: ChildControlClient;\n readonly catalog: ChildAgentCatalog;\n readonly host: ChildAgentHost;\n}\n\n/** Projects child state from Unit anchors and Session Journals without owning execution. */\nexport class ChildObservationCoordinator {\n readonly #options: ChildObservationCoordinatorOptions;\n\n constructor(options: ChildObservationCoordinatorOptions) {\n this.#options = options;\n }\n\n stateOwner(parentSessionId: string): NamedStateOwner<'child_runs', typeof CompletionStateSchema> {\n return {\n stateName: 'child_runs',\n schema: CompletionStateSchema,\n read: async ({ signal }) => {\n signal?.throwIfAborted();\n const state = await this.#completionState(parentSessionId);\n signal?.throwIfAborted();\n if (state.throughCompletion === 0) return { present: false };\n const results = state.results.slice(-COMPLETION_STATE_LIMIT);\n return {\n present: true,\n value: { ...state, results },\n element: {\n kind: 'container',\n name: 'child_runs',\n children: results.map(({ agentId, runId }) => ({\n kind: 'text',\n name: 'child_run',\n attributes: { agent: agentId, run: runId },\n text: '',\n })),\n },\n };\n },\n };\n }\n\n async listAgents(\n operation: ChildOperation & { readonly request: { readonly includeClosed?: boolean } }\n ): Promise<ListAgentsOutput> {\n return this.listAgentsForHost(operation.parentSessionId, operation.request.includeClosed);\n }\n\n async listAgentsForHost(\n parentSessionId: string,\n includeClosed?: boolean\n ): Promise<ListAgentsOutput> {\n const document = await this.#options.catalog.read(parentSessionId);\n const allAgents = await Promise.all(\n document.children.map((record) => this.snapshotRecord(record))\n );\n const agents = allAgents.filter((agent) => includeClosed === true || agent.state !== 'closed');\n return {\n agents,\n modelUsage: sumModelUsage(allAgents.map(({ modelUsage }) => modelUsage)),\n };\n }\n\n /**\n * The child of this parent whose Session ran `runId`. A child's initial Run is known from the\n * catalog; later Runs need its inspection, so only those scan the children.\n */\n async #findRun(parentSessionId: string, runId: string) {\n const { children } = await this.#options.catalog.read(parentSessionId);\n const initial = children.find((record) => record.initialRunId === runId);\n for (const record of initial === undefined ? children : [initial]) {\n const inspection = await this.#options.host.inspectChild(record);\n const runIndex = inspection.runs.findIndex((run) => run.lifecycle.runId === runId);\n if (runIndex !== -1) return { record, inspection, runIndex };\n }\n return undefined;\n }\n\n /**\n * A Reporter delivers an auto child's completion after the Run ends, in its own commit. Waiting\n * on the Reporter rather than the Run lets a wait withdraw that notification once it exists.\n * Manual and foreground Runs have no Reporter, so their Run is the member.\n */\n async waitMember(parentSessionId: string, runId: string): Promise<WaitMember | undefined> {\n const found = await this.#findRun(parentSessionId, runId);\n if (found === undefined) return undefined;\n const unit = this.#options.host.unit(parentSessionId);\n const reporters = unit\n .taskGraph({ sessionId: parentSessionId, kind: childReporterDefinition.name })\n .snapshot();\n for (const reporter of reporters) {\n const input = decode(childReporterDefinition.inputSchema, reporter.input);\n if (input.parentSessionId !== parentSessionId || input.agentId !== found.record.agentId)\n continue;\n const placed =\n input.kind === 'legacy-run'\n ? input.legacyRunId\n : await this.#placedRun(unit, input.submissionId);\n if (placed === runId) return { task: reporter.taskId };\n }\n return { run: runId };\n }\n\n /** A placed Submission never moves to another Run, so its Run is read once. */\n readonly #placedRuns = new Map<string, string>();\n async #placedRun(unit: UnitRuntime, submissionId: string): Promise<string | undefined> {\n const known = this.#placedRuns.get(submissionId);\n if (known !== undefined) return known;\n const runId = (await (await unit.submission(submissionId))?.status())?.placed?.runId;\n if (runId !== undefined) this.#placedRuns.set(submissionId, runId);\n return runId;\n }\n\n async describeRun(\n parentSessionId: string,\n runId: string\n ): Promise<ChildAgentSnapshot | undefined> {\n const found = await this.#findRun(parentSessionId, runId);\n return found === undefined\n ? undefined\n : this.#snapshotRun(found.record, found.inspection, found.runIndex);\n }\n\n async snapshotById(parentSessionId: string, agentId: string): Promise<ChildAgentSnapshot> {\n const record = await this.#options.catalog.record(parentSessionId, agentId);\n return this.snapshotRecord(record);\n }\n\n async snapshotRunById(\n parentSessionId: string,\n agentId: string,\n runId: string\n ): Promise<ChildAgentSnapshot> {\n const record = await this.#options.catalog.record(parentSessionId, agentId);\n const inspection = await this.#options.host.inspectChild(record);\n const runIndex = inspection.runs.findIndex((run) => run.lifecycle.runId === runId);\n if (runIndex === -1) {\n throw new ChildAgentError(\n 'child_run_not_found',\n 'Run does not belong to the requested child agent'\n );\n }\n return this.#snapshotRun(record, inspection, runIndex);\n }\n\n async getResult(\n operation: ChildOperation & {\n readonly agentId: string;\n readonly runId: string;\n readonly offset?: number;\n readonly limit?: number;\n }\n ): Promise<ChildAgentSnapshot> {\n operation.context.signal?.throwIfAborted();\n const snapshot = await this.snapshotRunById(\n operation.parentSessionId,\n operation.agentId,\n operation.runId\n );\n if (snapshot.response === undefined || snapshot.outcome?.kind !== 'completed') return snapshot;\n if (\n !snapshot.response.truncated &&\n operation.offset === undefined &&\n operation.limit === undefined\n )\n return snapshot;\n const record = await this.#options.catalog.record(operation.parentSessionId, operation.agentId);\n const inspection = await this.#options.host.inspectChild(record);\n const text = completedResponseText(inspection, snapshot.outcome.responseMessageId);\n if (text === undefined) throw new Error('Completed child response is missing');\n operation.context.signal?.throwIfAborted();\n const offset = Math.min(operation.offset ?? 0, text.length);\n const end = Math.min(offset + (operation.limit ?? MAX_RESPONSE_CHARACTERS), text.length);\n return {\n ...snapshot,\n response: {\n text: text.slice(offset, end),\n truncated: offset > 0 || end < text.length,\n offset,\n nextOffset: end < text.length ? end : undefined,\n },\n };\n }\n\n async listResults(\n operation: ChildOperation & { readonly after?: number; readonly limit?: number }\n ) {\n operation.context.signal?.throwIfAborted();\n const state = await this.#completionState(operation.parentSessionId);\n const available = state.results.filter((result) => result.cursor > (operation.after ?? 0));\n const page = available.slice(0, operation.limit ?? 32);\n return {\n results: page,\n nextCursor: available.length > page.length ? page.at(-1)?.cursor : undefined,\n };\n }\n\n async #completionState(parentSessionId: string) {\n const document = await this.#options.catalog.read(parentSessionId);\n return {\n throughCompletion: document.completions.at(-1)?.cursor ?? 0,\n resultCount: document.completions.length,\n results: document.completions,\n };\n }\n\n async snapshotRecord(record: ChildAgentEntry): Promise<ChildAgentSnapshot> {\n if (record.closed) {\n const closedUsage = record.closedUsage ?? (await this.#closedUsage(record));\n return {\n ...snapshotIdentity(record),\n state: 'closed',\n modelUsage: closedUsage.modelUsage,\n };\n }\n const inspection = await this.#options.host.inspectChild(record);\n const runIndex = inspection.runs.length - 1;\n if (runIndex === -1) {\n return {\n ...snapshotIdentity(record),\n state: 'starting',\n modelUsage: projectModelUsage(inspection.runs),\n };\n }\n return this.#snapshotRun(record, inspection, runIndex);\n }\n\n #snapshotRun(\n record: ChildAgentEntry,\n inspection: SessionInspection,\n runIndex: number\n ): ChildAgentSnapshot {\n const run = inspection.runs[runIndex];\n if (run === undefined) throw new Error('Child Run index is inconsistent');\n const modelUsage = projectModelUsage(inspection.runs);\n const outcome = run.lifecycle.outcome;\n if (outcome === undefined) {\n return {\n ...snapshotIdentity(record),\n state: 'running',\n modelUsage,\n runId: run.lifecycle.runId,\n };\n }\n const state: ChildAgentSnapshot['state'] =\n outcome.kind === 'completed' ? 'completed' : outcome.kind;\n const response =\n outcome.kind === 'completed'\n ? completedText(inspection, outcome.responseMessageId)\n : undefined;\n return {\n ...snapshotIdentity(record),\n state,\n modelUsage,\n runId: run.lifecycle.runId,\n outcome,\n ...(response === undefined ? {} : { response }),\n };\n }\n\n async #closedUsage(record: ChildAgentEntry): Promise<ClosedChildUsage> {\n const { runs } = await this.#options.host.inspectChild(record);\n const latestRun = runs.at(-1);\n const closedUsage: ClosedChildUsage = {\n ...(latestRun === undefined ? {} : { throughRunId: latestRun.lifecycle.runId }),\n modelUsage: projectModelUsage(runs),\n };\n return closedUsage;\n }\n}\n\nfunction snapshotIdentity(record: ChildAgentEntry): Pick<\n ChildAgentSnapshot,\n | 'agentId'\n | 'childSessionId'\n | 'name'\n | 'description'\n | 'parentRunId'\n | 'spawnToolCallId'\n | 'createdAt'\n> {\n return {\n agentId: record.agentId,\n childSessionId: record.childSessionId,\n ...(record.name === undefined ? {} : { name: record.name }),\n ...(record.description === undefined ? {} : { description: record.description }),\n parentRunId: record.parentRunId,\n spawnToolCallId: record.spawnToolCallId,\n createdAt: record.createdAt,\n };\n}\n\nfunction sumModelUsage(usages: readonly ChildModelUsageSnapshot[]): ChildModelUsageSnapshot {\n let committedResponses = 0;\n let activeRequests = 0;\n let unknownRequests = 0;\n let totalTokens = 0;\n let costUsd = 0;\n const models = new Map<string, { provider: string; model: string; usage: Usage }>();\n for (const usage of usages) {\n committedResponses += usage.committedResponses;\n activeRequests += usage.activeRequests;\n unknownRequests += usage.unknownRequests;\n totalTokens += usage.totalTokens;\n costUsd += usage.costUsd;\n for (const row of usage.models ?? []) addModelUsage(models, row.provider, row.model, row.usage);\n }\n return {\n committedResponses,\n activeRequests,\n unknownRequests,\n totalTokens,\n costUsd,\n models: [...models.values()],\n };\n}\n\nfunction completedText(\n inspection: SessionInspection,\n responseMessageId: string\n): ChildAgentSnapshot['response'] | undefined {\n const text = completedResponseText(inspection, responseMessageId);\n if (text === undefined) return;\n return {\n text: text.slice(0, MAX_RESPONSE_CHARACTERS),\n truncated: text.length > MAX_RESPONSE_CHARACTERS,\n };\n}\n\nexport function completedResponseText(\n inspection: SessionInspection,\n responseMessageId: string\n): string | undefined {\n const entry = inspection.conversation.find(\n (candidate) => candidate.messageId === responseMessageId\n );\n if (entry?.message.role !== 'assistant') return;\n return entry.message.content\n .flatMap((content) => (content.type === 'text' ? [content.text] : []))\n .join('');\n}\n\n/** Observe the existing Run; cancellation stops the waiter, not the child execution. */\nexport async function waitForChildRun(\n child: ChildSessionRuntime,\n runId: string,\n signal?: AbortSignal\n): Promise<void> {\n signal?.throwIfAborted();\n const snapshot = await child.snapshot(runId);\n if (snapshot.outcome !== undefined) return;\n signal?.throwIfAborted();\n const facts = child.runFacts(runId, { after: snapshot.cursor });\n const close = () => facts.close();\n signal?.addEventListener('abort', close, { once: true });\n try {\n for await (const fact of facts) if (isRunTerminalFactKind(fact.kind)) return;\n signal?.throwIfAborted();\n const current = await child.snapshot(runId);\n if (current.outcome === undefined)\n throw new Error('Child execution unloaded before Run settlement');\n } finally {\n signal?.removeEventListener('abort', close);\n facts.close();\n }\n}\n","import { raceSignal } from 'race-signal';\nimport type { SessionInputSource } from '@sorbetai/runtime';\nimport {\n ChildAgentError,\n type SendInputRequest,\n type SendInputOutput,\n type SendTeamMessageRequest,\n type SendTeamMessageOutput,\n type ListTeamPeersOutput,\n} from './contracts.js';\nimport type { ChildAgentCatalog } from './catalog.js';\nimport type { ChildControlClient } from './control/client.js';\nimport type { ChildAgentHost } from './host.js';\nimport { waitForChildRun, type ChildObservationCoordinator } from './observation.js';\nimport type { ChildOperation } from './operations.js';\nimport { stageChildInput } from './completion.js';\n\nconst NeverAbortSignal = AbortSignal.any([]);\ninterface Options {\n readonly catalog: ChildAgentCatalog;\n readonly host: ChildAgentHost;\n readonly control: ChildControlClient;\n readonly observation: ChildObservationCoordinator;\n}\n\n/** Input and its Reporter share admission; placement remains owned by the Unit and Pi. */\nexport class ChildDeliveryCoordinator {\n constructor(readonly options: Options) {}\n\n send(\n operation: ChildOperation & { readonly request: SendInputRequest }\n ): Promise<SendInputOutput> {\n return this.#send(\n operation,\n operation.request.agentId,\n `to-child-${operation.context.effectAttemptId}`,\n operation.request.prompt,\n {\n kind: 'node-agent.parent-input',\n data: {\n parentSessionId: operation.parentSessionId,\n parentRunId: operation.context.runId,\n toolCallId: operation.context.toolCallId,\n effectAttemptId: operation.context.effectAttemptId,\n agentId: operation.request.agentId,\n interrupt: operation.request.interrupt === true,\n },\n },\n operation.request.interrupt === true\n );\n }\n\n async listTeamPeers(\n operation: ChildOperation & { readonly senderAgentId: string }\n ): Promise<ListTeamPeersOutput> {\n await this.#assertSender(operation);\n const { children } = await this.options.catalog.read(operation.parentSessionId);\n const peers = await Promise.all(\n children\n .filter(\n (child) => child.agentId !== operation.senderAgentId && !child.closed && !child.closing\n )\n .map(async (child) => {\n const snapshot = await this.options.observation.snapshotRecord(child);\n return { agentId: child.agentId, state: snapshot.state };\n })\n );\n return { peers };\n }\n\n async sendTeamMessage(\n operation: ChildOperation & {\n readonly senderAgentId: string;\n readonly request: SendTeamMessageRequest;\n }\n ): Promise<SendTeamMessageOutput> {\n await this.#assertSender(operation);\n if (operation.request.agentId === operation.senderAgentId)\n throw new ChildAgentError(\n 'team_self_message',\n 'A child cannot send a Team message to itself'\n );\n const deliveryId = `team-${operation.senderAgentId}-${operation.context.effectAttemptId}`;\n await this.#admit(\n operation,\n operation.request.agentId,\n deliveryId,\n operation.request.prompt,\n {\n kind: 'node-agent.team-message',\n data: {\n parentSessionId: operation.parentSessionId,\n senderAgentId: operation.senderAgentId,\n senderSessionId: operation.context.sessionId,\n senderRunId: operation.context.runId,\n toolCallId: operation.context.toolCallId,\n effectAttemptId: operation.context.effectAttemptId,\n recipientAgentId: operation.request.agentId,\n },\n },\n false\n );\n return { status: 'queued', deliveryId, recipient: { agentId: operation.request.agentId } };\n }\n\n async #assertSender(\n operation: ChildOperation & { readonly senderAgentId: string }\n ): Promise<void> {\n const sender = await this.options.catalog.record(\n operation.parentSessionId,\n operation.senderAgentId\n );\n if (sender.closed || sender.closing)\n throw new ChildAgentError('child_closed', 'Sender child is closed');\n if (sender.childSessionId !== operation.context.sessionId)\n throw new ChildAgentError(\n 'child_not_found',\n 'Team sender does not match the invoking Session'\n );\n }\n\n async #admit(\n operation: ChildOperation,\n agentId: string,\n deliveryId: string,\n prompt: string,\n source: SessionInputSource,\n interrupt: boolean\n ) {\n const signal = operation.context.signal ?? NeverAbortSignal;\n signal.throwIfAborted();\n const unit = this.options.host.unit(operation.parentSessionId);\n const record = await this.options.catalog.record(operation.parentSessionId, agentId);\n await this.options.control.withChildPermit(\n operation.parentSessionId,\n agentId,\n 'input',\n async () => {\n signal.throwIfAborted();\n const current = await this.options.catalog.record(operation.parentSessionId, agentId);\n if (current.closed || current.closing)\n throw new ChildAgentError('child_closed', 'Child agent is closed');\n if (interrupt && (await unit.submission(deliveryId)) === undefined) {\n const facts = await unit.participant(record.childSessionId);\n for (const pending of await facts.pendingSubmissions()) {\n await (\n await unit.submission(pending.accepted.operationId)\n )?.withdraw({\n reason: 'Child input superseded by interrupt',\n commandId: `interrupt:${deliveryId}:${pending.accepted.operationId}`,\n });\n }\n const child = await this.options.host.loadChild(record);\n const active = await child.getActiveRun();\n if (active !== undefined) {\n await child.abortRun(active.receipt.runId, 'Child input interrupted by sender');\n await waitForChildRun(child, active.receipt.runId, signal);\n }\n }\n await unit.prepareSessions([record.childSessionId]);\n signal.throwIfAborted();\n await unit.group((group) =>\n group.tasks((tx) => {\n stageChildInput(tx, record, record.anchorId, {\n kind: 'user-message',\n deliveryId,\n prompt,\n source,\n });\n })\n );\n },\n signal\n );\n const submission = await unit.submission(deliveryId);\n if (submission === undefined) throw new Error('Child input admission is missing');\n await unit.resume();\n return { unit, record, submission };\n }\n\n async #send(\n operation: ChildOperation,\n agentId: string,\n deliveryId: string,\n prompt: string,\n source: SessionInputSource,\n interrupt: boolean\n ): Promise<SendInputOutput> {\n const signal = operation.context.signal ?? NeverAbortSignal;\n const { unit, record, submission } = await this.#admit(\n operation,\n agentId,\n deliveryId,\n prompt,\n source,\n interrupt\n );\n try {\n await raceSignal(unit.notifyAvailable(record.childSessionId), signal);\n const recovery = unit\n .recovery()\n .decisions.find((entry) => entry.sessionId === record.childSessionId);\n if (recovery?.status === 'faulted')\n throw new ChildAgentError(\n 'child_provision_failed',\n recovery.error?.message ?? 'Child environment could not be acquired'\n );\n signal.throwIfAborted();\n } catch (cause) {\n if (signal.aborted)\n await submission.withdraw({\n reason: 'Child delivery cancelled',\n commandId: `cancel:${deliveryId}`,\n });\n throw cause;\n }\n return {\n status: 'accepted',\n deliveryId,\n agent: await this.options.observation.snapshotById(record.parentSessionId, agentId),\n };\n }\n}\n","export interface AvailableAgentModel {\n readonly selector: string;\n readonly providerId: string;\n readonly modelId: string;\n readonly displayName: string;\n}\n\nexport interface ModelSelector {\n readonly providerId: string;\n readonly modelId: string;\n}\n\nexport function encodeModelSelector(providerId: string, modelId: string): string {\n return `${encodeURIComponent(providerId)}/${encodeURIComponent(modelId)}`;\n}\n\nexport function decodeModelSelector(selector: string): ModelSelector | undefined {\n const segments = selector.split('/');\n if (segments.length !== 2) return;\n let providerId: string;\n let modelId: string;\n try {\n providerId = decodeURIComponent(segments[0] ?? '');\n modelId = decodeURIComponent(segments[1] ?? '');\n } catch {\n return;\n }\n if (\n providerId.length === 0 ||\n modelId.length === 0 ||\n encodeModelSelector(providerId, modelId) !== selector\n ) {\n return;\n }\n return { providerId, modelId };\n}\n","import type { JsonValue, UnitRuntime, UnitTx } from '@sorbetai/runtime';\nimport { raceSignal } from 'race-signal';\nimport * as Effect from 'effect/Effect';\nimport { decodeModelSelector, type AvailableAgentModel } from './models.js';\nimport {\n ChildAgentError,\n type CloseAgentOutput,\n type SpawnAgentOutput,\n type SwarmAgentOutput,\n type SwarmTaskOutput,\n} from './contracts.js';\nimport type { ChildAgentHost, ChildAgentParent } from './host.js';\nimport type { ChildAgentCatalog } from './catalog.js';\nimport { stageChildAnchor, stageChildClose } from './close.js';\nimport { stageChildInput } from './completion.js';\nimport type { ChildTaskInput } from './record.js';\nimport type { ChildObservationCoordinator } from './observation.js';\nimport { waitForChildRun } from './observation.js';\nimport type { ChildOperation, SpawnOperation, SwarmOperation } from './operations.js';\n\nconst NeverAbortSignal = AbortSignal.any([]);\n\ninterface ChildAdmission {\n readonly child: ChildTaskInput;\n readonly submission: NonNullable<Awaited<ReturnType<UnitRuntime['submission']>>>;\n}\n\ninterface ChildLifecycleCoordinatorOptions {\n readonly catalog: ChildAgentCatalog;\n readonly maxActiveChildrenPerParent?: number;\n readonly host: ChildAgentHost;\n readonly observation: ChildObservationCoordinator;\n readonly createId: () => string;\n readonly now: () => Date;\n}\n\n/** Admission is durable before observation; Unit recovery owns execution and close cleanup. */\nexport class ChildLifecycleCoordinator {\n readonly #options: ChildLifecycleCoordinatorOptions;\n constructor(options: ChildLifecycleCoordinatorOptions) {\n this.#options = options;\n }\n\n async spawn(operation: SpawnOperation): Promise<SpawnAgentOutput> {\n const { child } = await this.#admitChild(operation);\n return {\n agent: await this.#options.observation.snapshotById(child.parentSessionId, child.agentId),\n };\n }\n\n /**\n * Durable admission only; the child Run settles on its own and reports back. `admitted`\n * runs once the child is committed, before the waits that a cancellation can interrupt.\n */\n async #admitChild(\n operation: SpawnOperation,\n admitted?: (admission: ChildAdmission) => void\n ): Promise<ChildAdmission> {\n const signal = operation.context.signal ?? NeverAbortSignal;\n signal.throwIfAborted();\n const parent = this.#parent(operation.parentSessionId);\n if (parent.depth !== 0)\n throw new ChildAgentError('child_depth_exceeded', 'Direct children cannot spawn agents');\n const identity = this.#modelIdentity(parent, operation.request.model);\n const model = await this.#selectModel(identity);\n const existing = (await this.#options.catalog.read(operation.parentSessionId)).children.find(\n (child) => child.spawnEffectAttemptId === operation.context.effectAttemptId\n );\n const display = existing ?? operation.request;\n const child: ChildTaskInput & { initialSubmissionId: string } = {\n agentId: existing?.agentId ?? this.#options.createId(),\n childSessionId: existing?.childSessionId ?? this.#options.createId(),\n ...(display.name === undefined ? {} : { name: display.name.trim() }),\n ...(display.description === undefined ? {} : { description: display.description.trim() }),\n parentSessionId: operation.parentSessionId,\n parentRunId: operation.context.runId,\n spawnToolCallId: operation.context.toolCallId,\n spawnEffectAttemptId: operation.context.effectAttemptId,\n depth: 1,\n providerId: model.providerId,\n modelId: model.modelId,\n executionPolicy: parent.executionPolicy(operation.context.runId),\n ordinaryToolNames: existing?.ordinaryToolNames ?? [...(await parent.ordinaryToolNames())],\n contextMode: 'fresh',\n initialMode: 'background',\n initialCompletionDelivery: operation.request.completionDelivery ?? 'auto',\n createdAt: existing?.createdAt ?? this.#options.now().toISOString(),\n initialSubmissionId: `child-spawn-${operation.context.effectAttemptId}`,\n };\n const unit = this.#options.host.unit(operation.parentSessionId);\n // A retried attempt keeps the committed metadata: createSession requires it to match.\n const metadata =\n unit.sessions().find((session) => session.sessionId === child.childSessionId)?.metadata ??\n (await this.#options.host.childMetadata(child));\n await unit.prepareSessions(\n existing === undefined\n ? [operation.parentSessionId]\n : [operation.parentSessionId, child.childSessionId]\n );\n signal.throwIfAborted();\n await unit.group((group) =>\n group.tasks((tx) =>\n stageChildAgent(tx, {\n child,\n metadata,\n input: {\n kind: 'user-message',\n deliveryId: child.initialSubmissionId,\n prompt: operation.request.prompt,\n source: {\n kind: 'node-agent.parent-spawn',\n data: {\n parentSessionId: child.parentSessionId,\n parentRunId: child.parentRunId,\n toolCallId: child.spawnToolCallId,\n effectAttemptId: child.spawnEffectAttemptId,\n agentId: child.agentId,\n },\n },\n },\n })\n )\n );\n const submission = await unit.submission(child.initialSubmissionId);\n if (submission === undefined) throw new Error('Child initial input is missing');\n admitted?.({ child, submission });\n await unit.resume();\n await raceSignal(unit.notifyAvailable(child.childSessionId), signal);\n const recovery = unit\n .recovery()\n .decisions.find((entry) => entry.sessionId === child.childSessionId);\n if (recovery?.status === 'faulted')\n throw new ChildAgentError(\n 'child_provision_failed',\n recovery.error?.message ?? 'Child environment could not be acquired'\n );\n signal.throwIfAborted();\n // The Tool result must name the child Run, so wait for acceptance; settlement stays with the child.\n await submission.placed(signal);\n signal.throwIfAborted();\n return { child, submission };\n }\n async swarm(operation: SwarmOperation): Promise<SwarmAgentOutput> {\n const signal = operation.context.signal ?? NeverAbortSignal;\n // Swarm is the one gather: it admits concurrently and waits for every admitted Run.\n const tasks = await Effect.runPromise(\n Effect.forEach(\n operation.request.tasks,\n (task, index) =>\n Effect.promise(async (): Promise<SwarmTaskOutput> => {\n let admission: ChildAdmission | undefined;\n try {\n const { child, submission } = await this.#admitChild(\n {\n parentSessionId: operation.parentSessionId,\n request: {\n prompt: task.prompt,\n name: task.name,\n description: task.description,\n model: operation.request.model,\n completionDelivery: 'manual',\n },\n context: {\n ...operation.context,\n signal,\n effectAttemptId: `${operation.context.effectAttemptId}.${index}`,\n },\n },\n (admitted) => {\n admission = admitted;\n }\n );\n await submission.settled(signal);\n const agent = await this.#options.observation.snapshotById(\n child.parentSessionId,\n child.agentId\n );\n return agent.state === 'completed'\n ? { taskId: task.taskId, status: 'completed', agent }\n : { taskId: task.taskId, status: 'failed', agent };\n } catch (cause) {\n // A task that never settled leaves a live child behind; stop it whatever ended the gather.\n if (admission !== undefined) await this.#stopChild(admission, 'Swarm task cancelled');\n if (signal.aborted) {\n const cancellation =\n signal.reason instanceof ChildAgentError\n ? { code: signal.reason.code, message: signal.reason.message }\n : { code: 'agent_operation_cancelled', message: 'Swarm task cancelled' };\n return { taskId: task.taskId, status: 'cancelled', error: cancellation };\n }\n const error =\n cause instanceof ChildAgentError\n ? { code: cause.code, message: cause.message }\n : { code: 'agent_operation_failed', message: 'Swarm task failed' };\n return { taskId: task.taskId, status: 'failed', error };\n }\n }),\n { concurrency: this.#options.maxActiveChildrenPerParent ?? 'unbounded' }\n )\n );\n return { tasks };\n }\n\n /**\n * Withdraws the initial input if it was not placed yet, otherwise aborts the Run it placed.\n * An unloaded child has no execution in this process; only loaded Runs can be aborted.\n */\n async #stopChild({ child, submission }: ChildAdmission, reason: string): Promise<void> {\n const withdrawn = await submission\n .withdraw({ reason, commandId: `stop:${submission.submissionId}` })\n .catch(() => false);\n if (withdrawn) return;\n const runId = (await submission.status().catch(() => undefined))?.placed?.runId;\n const session = this.#options.host.loaded(child.childSessionId);\n if (runId === undefined || session === undefined) return;\n await session.abortRun(runId, reason).catch(() => undefined);\n // \"Stopped\" means the Run settled, not that cancellation was requested.\n await waitForChildRun(session, runId).catch(() => undefined);\n }\n\n async closeChild(\n operation: ChildOperation & { readonly agentId: string }\n ): Promise<CloseAgentOutput> {\n return this.closeChildForHost(\n operation.parentSessionId,\n operation.agentId,\n operation.context.signal\n );\n }\n\n async closeChildForHost(\n parentSessionId: string,\n agentId: string,\n signal?: AbortSignal,\n reason = 'Child agent closed by parent'\n ): Promise<CloseAgentOutput> {\n signal?.throwIfAborted();\n const record = await this.#options.catalog.record(parentSessionId, agentId);\n if (!record.closed) {\n const unit = this.#options.host.unit(parentSessionId);\n await unit.group((group) =>\n group.tasks((tx) =>\n stageChildClose(tx, record.anchorId, reason, `close:${record.anchorId}`)\n )\n );\n await unit.resume();\n await unit.notifyAvailable(record.childSessionId);\n const decision = unit\n .recovery()\n .decisions.find((entry) => entry.sessionId === record.childSessionId);\n if (decision?.status === 'faulted') throw decision.error;\n if (!unit.sessions().find((entry) => entry.sessionId === record.childSessionId)?.closed)\n throw new Error('Child close is waiting for Host cleanup');\n }\n const snapshot = await this.#options.observation.snapshotById(parentSessionId, agentId);\n if (snapshot.state !== 'closed') throw new Error('Closed child projection is inconsistent');\n return { agent: { ...snapshot, state: 'closed' } };\n }\n\n /** False when no child anchor of this parent owns the Session. */\n async closeBySession(\n parentSessionId: string,\n childSessionId: string,\n signal?: AbortSignal\n ): Promise<boolean> {\n const record = (await this.#options.catalog.read(parentSessionId)).children.find(\n (child) => child.childSessionId === childSessionId\n );\n if (record === undefined) return false;\n await this.closeChildForHost(record.parentSessionId, record.agentId, signal);\n return true;\n }\n\n releaseParent(parentSessionId: string): Promise<void> {\n return this.#options.host.releaseChildren(parentSessionId);\n }\n\n #parent(sessionId: string): ChildAgentParent {\n const parent = this.#options.host.parent(sessionId);\n if (parent === undefined)\n throw new ChildAgentError('child_not_found', 'Parent Session is not loaded');\n return parent;\n }\n #modelIdentity(\n parent: ChildAgentParent,\n selector?: string\n ): { readonly providerId: string; readonly modelId: string } {\n const selected = selector === undefined ? undefined : decodeModelSelector(selector);\n if (selector !== undefined && selected === undefined) {\n throw new ChildAgentError('model_unavailable', 'Child model selector is invalid');\n }\n return {\n providerId: selected?.providerId ?? parent.providerId,\n modelId: selected?.modelId ?? parent.modelId,\n };\n }\n\n async #selectModel(identity: {\n readonly providerId: string;\n readonly modelId: string;\n }): Promise<AvailableAgentModel> {\n const available = await this.#options.host.availableModels();\n const model = available.find(\n (candidate) =>\n candidate.providerId === identity.providerId && candidate.modelId === identity.modelId\n );\n if (model === undefined) {\n throw new ChildAgentError('model_unavailable', 'Requested child model is unavailable');\n }\n return model;\n }\n}\n\n/** Commit before waiting for a child Run or Tool result. A failed receipt cannot undo admission. */\nexport function stageChildAgent(\n tx: UnitTx,\n request: {\n readonly child: ChildTaskInput & { readonly initialSubmissionId: string };\n readonly metadata: JsonValue;\n readonly input: Parameters<UnitTx['submit']>[1];\n }\n): string {\n const { child } = request;\n if (request.input.deliveryId !== child.initialSubmissionId)\n throw new Error('Child initial Submission identity does not match');\n tx.createSession({\n sessionId: child.childSessionId,\n parentSessionId: child.parentSessionId,\n key: `child:${child.spawnEffectAttemptId}`,\n metadata: request.metadata,\n });\n const anchorId = stageChildAnchor(tx, child);\n stageChildInput(tx, child, anchorId, request.input, { initial: true });\n return anchorId;\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { check, decode } from '@sorbetai/schema';\nimport { JsonValueSchema, type UnitRuntime } from '@sorbetai/runtime';\nimport type { WaitTargetSource } from '../contracts.js';\nimport { ChildTelemetry } from './telemetry.js';\nimport type { ChildAgentObservationPort } from './telemetry-port.js';\nimport * as ManagedRuntime from 'effect/ManagedRuntime';\n\nimport {\n type CloseAgentOutput,\n type ListAgentsOutput,\n type ListTeamPeersOutput,\n type SendInputOutput,\n type SendInputRequest,\n type SendTeamMessageOutput,\n type SendTeamMessageRequest,\n type SpawnAgentOutput,\n type SwarmAgentOutput,\n} from './contracts.js';\nimport { ChildControlClient } from './control/client.js';\nimport { ChildControl } from './control/service.js';\nimport { ChildDeliveryCoordinator } from './delivery.js';\nimport type { ChildAgentHost } from './host.js';\nimport { ChildLifecycleCoordinator } from './lifecycle.js';\nimport type { ChildAgentCatalog } from './catalog.js';\nimport { ChildObservationCoordinator } from './observation.js';\nimport type { ChildOperation, SpawnOperation, SwarmOperation } from './operations.js';\n\nconst RunTarget = s.obj({ runId: s.str() }, { open: false });\nconst ChildCompletionSource = s.obj(\n {\n kind: s.lit('node-agent.child-completion'),\n data: s.obj({ childRunId: s.str() }, { open: true }),\n },\n { open: true }\n);\n\nexport class ChildAgentManager {\n readonly #telemetry: ChildTelemetry;\n readonly #catalog: ChildAgentCatalog;\n readonly #observationPort: ChildAgentObservationPort | undefined;\n readonly #runtime = ManagedRuntime.make(ChildControl.layer);\n readonly #control = new ChildControlClient(this.#runtime);\n readonly #observation: ChildObservationCoordinator;\n readonly #delivery: ChildDeliveryCoordinator;\n readonly #lifecycle: ChildLifecycleCoordinator;\n #closing: Promise<void> | undefined;\n #shutdown: Promise<void> | undefined;\n\n constructor(options: {\n readonly catalog: ChildAgentCatalog;\n readonly host: ChildAgentHost;\n /**\n * Swarm admission concurrency, unbounded by default. Run placement is bounded\n * separately by the Unit's `policies.concurrency.childRunsPerParent`.\n */\n readonly maxActiveChildrenPerParent?: number;\n readonly createId: () => string;\n readonly now: () => Date;\n readonly observation?: ChildAgentObservationPort;\n }) {\n this.#catalog = options.catalog;\n this.#telemetry = new ChildTelemetry(options.catalog, options.observation);\n this.#observationPort = options.observation;\n this.#observation = new ChildObservationCoordinator({\n control: this.#control,\n catalog: options.catalog,\n host: options.host,\n });\n this.#delivery = new ChildDeliveryCoordinator({\n control: this.#control,\n catalog: options.catalog,\n host: options.host,\n observation: this.#observation,\n });\n this.#lifecycle = new ChildLifecycleCoordinator({\n catalog: options.catalog,\n maxActiveChildrenPerParent: options.maxActiveChildrenPerParent,\n host: options.host,\n observation: this.#observation,\n createId: options.createId,\n now: options.now,\n });\n }\n\n spawn(operation: SpawnOperation): Promise<SpawnAgentOutput> {\n return this.#runOperation('spawn', operation, (controlled) =>\n this.#lifecycle.spawn(controlled)\n );\n }\n\n stateOwner(parentSessionId: string) {\n return this.#observation.stateOwner(parentSessionId);\n }\n\n getResult(\n operation: ChildOperation & {\n readonly agentId: string;\n readonly runId: string;\n readonly offset?: number;\n readonly limit?: number;\n }\n ) {\n return this.#runOperation('getResult', operation, (controlled) =>\n this.#observation.getResult(controlled)\n );\n }\n\n listResults(operation: ChildOperation & { readonly after?: number; readonly limit?: number }) {\n return this.#runOperation('listResults', operation, (controlled) =>\n this.#observation.listResults(controlled)\n );\n }\n\n swarm(operation: SwarmOperation): Promise<SwarmAgentOutput> {\n return this.#runOperation('swarm', operation, (controlled) =>\n this.#lifecycle.swarm(controlled)\n );\n }\n\n send(\n operation: ChildOperation & { readonly request: SendInputRequest }\n ): Promise<SendInputOutput> {\n return this.#runOperation('send', operation, (controlled) => this.#delivery.send(controlled));\n }\n\n listTeamPeers(\n operation: ChildOperation & { readonly senderAgentId: string }\n ): Promise<ListTeamPeersOutput> {\n return this.#runOperation('listTeamPeers', operation, (controlled) =>\n this.#delivery.listTeamPeers(controlled)\n );\n }\n\n sendTeamMessage(\n operation: ChildOperation & {\n readonly senderAgentId: string;\n readonly request: SendTeamMessageRequest;\n }\n ): Promise<SendTeamMessageOutput> {\n return this.#runOperation('sendTeamMessage', operation, (controlled) =>\n this.#delivery.sendTeamMessage(controlled)\n );\n }\n\n listAgents(\n operation: ChildOperation & { readonly request: { readonly includeClosed?: boolean } }\n ): Promise<ListAgentsOutput> {\n return this.#runOperation('listAgents', operation, (controlled) =>\n this.#observation.listAgents(controlled)\n );\n }\n\n listAgentsForHost(parentSessionId: string, includeClosed = true): Promise<ListAgentsOutput> {\n return this.#observation.listAgentsForHost(parentSessionId, includeClosed);\n }\n\n closeChild(operation: ChildOperation & { readonly agentId: string }): Promise<CloseAgentOutput> {\n return this.#runOperation('closeChild', operation, (controlled) =>\n this.#lifecycle.closeChild(controlled)\n );\n }\n\n closeChildForHost(\n parentSessionId: string,\n agentId: string,\n signal?: AbortSignal,\n reason?: string\n ): Promise<CloseAgentOutput> {\n return this.#control.admitClose(parentSessionId, 'closeChildForHost', (controlSignal) =>\n this.#lifecycle.closeChildForHost(\n parentSessionId,\n agentId,\n signal === undefined ? controlSignal : AbortSignal.any([signal, controlSignal]),\n reason\n )\n );\n }\n\n /** Lets the durable `wait` Tool wait for child Runs of the Session that owns them. */\n waitTargets(): WaitTargetSource {\n return {\n resolve: async (sessionId, target) => {\n if (!check(RunTarget, target)) return undefined;\n const member = await this.#observation.waitMember(sessionId, target.runId);\n return member === undefined\n ? { kind: 'refused', reason: `No child Run ${target.runId} belongs to this Session` }\n : { kind: 'member', member };\n },\n describe: async (sessionId, target) => {\n if (!check(RunTarget, target)) return {};\n const snapshot = await this.#observation.describeRun(sessionId, target.runId);\n return snapshot === undefined\n ? { state: 'missing' }\n : decode(s.map(JsonValueSchema), snapshot);\n },\n notification: (input) =>\n input.kind === 'context-event' && check(ChildCompletionSource, input.source)\n ? { runId: input.source.data.childRunId }\n : undefined,\n };\n }\n\n trackUnit(unit: UnitRuntime): void {\n this.#catalog.track(unit, this.#observationPort !== undefined);\n this.#telemetry.track(unit);\n }\n\n activateParent(parentSessionId: string): Promise<void> {\n return this.#control.activateParent(parentSessionId);\n }\n\n async releaseParent(parentSessionId: string): Promise<void> {\n await this.#control.interruptParent(parentSessionId);\n await this.#lifecycle.releaseParent(parentSessionId);\n }\n\n closeBySession(parentSessionId: string, childSessionId: string): Promise<boolean> {\n return this.#control.admit(undefined, 'closeBySession', (signal) =>\n this.#lifecycle.closeBySession(parentSessionId, childSessionId, signal)\n );\n }\n\n shutdown(parentSessionIds: readonly string[]): Promise<void> {\n this.#shutdown ??= this.#control\n .close(parentSessionIds, (parentSessionId) => this.releaseParent(parentSessionId))\n .catch((cause) => {\n this.#shutdown = undefined;\n throw cause;\n });\n this.#closing ??= this.#shutdown\n .then(() => this.#telemetry.close())\n .then(() => this.#control.dispose())\n .catch((cause) => {\n this.#closing = undefined;\n throw cause;\n });\n return this.#closing;\n }\n\n #runOperation<Operation extends ChildOperation, Result>(\n operationName: string,\n operation: Operation,\n run: (operation: Operation) => Promise<Result>\n ): Promise<Result> {\n return this.#control.admit(operation.parentSessionId, operationName, (controlSignal) =>\n run({\n ...operation,\n context: {\n ...operation.context,\n signal:\n operation.context.signal === undefined\n ? controlSignal\n : AbortSignal.any([operation.context.signal, controlSignal]),\n },\n })\n );\n }\n}\n","import * as s from '@earendil-works/pi-schema';\nimport { decode } from '@sorbetai/schema';\nimport type { JournalCursor, UnitReader, UnitRuntime } from '@sorbetai/runtime';\n\nimport { ChildAgentError } from './contracts.js';\nimport { ChildProjection, type ChildAgentEntry } from './projection.js';\nimport type { ChildDeliveryPage } from './telemetry-port.js';\n\nexport type { ChildAgentEntry } from './projection.js';\n\ninterface OwnedProjection {\n readonly unit: UnitRuntime;\n readonly observeAfter: number;\n projection: ChildProjection;\n cursor?: JournalCursor;\n sequence: number;\n pending: Promise<void>;\n}\n\n/** Cold reads pin a committed prefix; owned reads incrementally reuse that writer's index. */\nexport class ChildAgentCatalog {\n readonly #owned = new Map<string, OwnedProjection>();\n\n constructor(readonly openReader: (parentSessionId: string) => Promise<UnitReader>) {}\n\n track(unit: UnitRuntime, observe: boolean): void {\n if (this.#owned.get(unit.unitId)?.unit === unit) return;\n const observeAfter = observe\n ? unit.workSummary().observedUnitSequence\n : Number.POSITIVE_INFINITY;\n const state: OwnedProjection = {\n unit,\n observeAfter,\n projection: new ChildProjection(unit.unitId, observeAfter),\n sequence: 0,\n pending: Promise.resolve(),\n };\n this.#owned.set(unit.unitId, state);\n void unit.closed.then(() => {\n if (this.#owned.get(unit.unitId) === state) this.#owned.delete(unit.unitId);\n });\n }\n\n async record(parentSessionId: string, agentId: string): Promise<ChildAgentEntry> {\n const record = (await this.read(parentSessionId)).children.find(\n (child) => child.agentId === agentId\n );\n if (record === undefined)\n throw new ChildAgentError('child_not_found', 'Child agent was not found');\n return record;\n }\n\n read(parentSessionId: string, afterSequence = Number.POSITIVE_INFINITY) {\n const owned = this.#owned.get(parentSessionId);\n if (owned === undefined) return this.#readCold(parentSessionId, afterSequence);\n const work = owned.pending.then(async () => {\n const tail = owned.unit.workSummary().observedUnitSequence;\n try {\n while (owned.sequence < tail) {\n // Bound each page to this read's prefix even if the writer commits during I/O.\n const page = await owned.unit.readHistory({\n after: owned.cursor,\n limit: Math.min(256, tail - owned.sequence),\n });\n for (const record of page.records) owned.projection.apply(record);\n owned.sequence = page.records.at(-1)?.unitSequence ?? tail;\n owned.cursor = page.cursor;\n }\n return owned.projection.snapshot(tail, afterSequence);\n } catch (cause) {\n owned.projection = new ChildProjection(parentSessionId, owned.observeAfter);\n owned.sequence = 0;\n owned.cursor = undefined;\n throw cause;\n }\n });\n owned.pending = work.then(\n () => {},\n () => {}\n );\n return work;\n }\n\n async #readCold(parentSessionId: string, afterSequence: number) {\n const reader = await this.openReader(parentSessionId);\n const projection = new ChildProjection(parentSessionId, afterSequence);\n const tail = reader.tail;\n let sequence = 0;\n let cursor: JournalCursor | undefined;\n try {\n while (sequence < tail) {\n const page = await reader.read({ after: cursor, limit: Math.min(256, tail - sequence) });\n for (const record of page.records) projection.apply(record);\n cursor = page.cursor;\n sequence = page.records.at(-1)?.unitSequence ?? tail;\n }\n return projection.snapshot(tail, afterSequence);\n } finally {\n await reader.close();\n }\n }\n\n async inspectDeliveries(\n parentSessionId: string,\n options: { readonly afterOrderingKey?: number; readonly limit?: number } = {}\n ): Promise<ChildDeliveryPage> {\n const limit = decode(s.int({ minimum: 1, maximum: 256 }), options.limit ?? 64);\n const after = decode(s.int({ minimum: 0 }), options.afterOrderingKey ?? 0);\n const available = (await this.read(parentSessionId)).deliveries.filter(\n (delivery) => delivery.orderingKey > after\n );\n const selected = available.slice(0, limit);\n return {\n parentSessionId,\n deliveries: selected,\n nextOrderingKey: available.length > limit ? selected.at(-1)?.orderingKey : undefined,\n };\n }\n}\n","import * as s from '@earendil-works/pi-schema';\nimport toError from 'ensure-error';\nimport { parseToolParameters, type ContextualTool } from '@sorbetai/runtime';\n\nimport type { AvailableAgentModel } from './models.js';\nimport type { ChildAgentManager } from './manager.js';\nimport {\n childToolExecutionError,\n ChildAgentDescriptionSchema,\n ChildAgentNameSchema,\n type ChildAgentSnapshot,\n type CloseAgentOutput,\n type ListAgentsOutput,\n type SendInputOutput,\n type SpawnAgentOutput,\n type SwarmAgentOutput,\n} from './contracts.js';\n\nconst NON_EMPTY_STRING_MIN_LENGTH = 1;\nconst SAFE_ID_PATTERN = '^[A-Za-z0-9][A-Za-z0-9._-]*$';\nconst NonEmptyString = s.str({ minLength: NON_EMPTY_STRING_MIN_LENGTH });\nconst SafeId = s.str({ pattern: SAFE_ID_PATTERN });\n\nconst AgentActionSchema = s.union([\n s.obj({ action: s.lit('list_models') }, { open: false }),\n s.obj(\n {\n action: s.lit('get_result'),\n agentId: NonEmptyString,\n runId: NonEmptyString,\n offset: s.opt(s.int({ minimum: 0 })),\n limit: s.opt(s.int({ minimum: 1, maximum: 30_000 })),\n },\n { open: false }\n ),\n s.obj(\n {\n action: s.lit('list_results'),\n after: s.opt(s.int({ minimum: 0 })),\n limit: s.opt(s.int({ minimum: 1, maximum: 64 })),\n },\n { open: false }\n ),\n s.obj(\n {\n action: s.lit('spawn'),\n prompt: NonEmptyString,\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n model: s.opt(NonEmptyString),\n completionDelivery: s.opt(s.union([s.lit('auto'), s.lit('manual')])),\n },\n { open: false }\n ),\n s.obj(\n {\n action: s.lit('swarm'),\n tasks: s.arr(\n s.obj(\n {\n taskId: SafeId,\n prompt: NonEmptyString,\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n },\n { open: false }\n ),\n { minItems: 1 }\n ),\n model: s.opt(NonEmptyString),\n },\n { open: false }\n ),\n s.obj(\n {\n action: s.lit('send_input'),\n agentId: NonEmptyString,\n prompt: NonEmptyString,\n interrupt: s.opt(s.bool()),\n },\n { open: false }\n ),\n s.obj({ action: s.lit('list'), includeClosed: s.opt(s.bool()) }, { open: false }),\n s.obj({ action: s.lit('close'), agentId: NonEmptyString }, { open: false }),\n]);\ntype AgentAction = s.Static<typeof AgentActionSchema>;\n\nfunction parseAgentAction(action: AgentAction): AgentAction {\n if (action.action === 'swarm') {\n const taskIds = new Set(action.tasks.map(({ taskId }) => taskId));\n if (taskIds.size !== action.tasks.length)\n throw new TypeError('Swarm taskId values must be unique');\n }\n return action;\n}\n\n// Keep the Provider schema compatible with APIs that reject anyOf/const. Pi calls\n// prepareArguments before permission and Effect admission to enforce the exact union.\nconst AgentToolParametersSchema = s.obj(\n {\n action: {\n type: 'string',\n enum: [\n 'list_models',\n 'spawn',\n 'swarm',\n 'send_input',\n 'list',\n 'close',\n 'get_result',\n 'list_results',\n ],\n description: 'The model query or child-agent operation to perform.',\n } as s.Schema<AgentAction>,\n prompt: s.opt(\n s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Required input for spawn and send_input.',\n })\n ),\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n tasks: s.opt(\n s.arr(\n s.obj(\n {\n taskId: s.str({\n pattern: SAFE_ID_PATTERN,\n description: 'Stable caller-chosen identity for this Swarm task.',\n }),\n prompt: s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Complete input for this child.',\n }),\n name: s.opt(ChildAgentNameSchema),\n description: s.opt(ChildAgentDescriptionSchema),\n },\n { open: false }\n ),\n { minItems: 1, description: 'Required by swarm. Tasks wait for parent child capacity.' }\n )\n ),\n model: s.opt(\n s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Optional child model selector for spawn and swarm.',\n })\n ),\n completionDelivery: s.opt({\n type: 'string',\n enum: ['auto', 'manual'],\n description:\n 'For spawn only; defaults to auto. Completions refresh child_runs and wake this Session unless already included in a parent model request. manual suppresses automatic delivery for this child, including later send_input Runs; retrieve results with get_result.',\n } as s.Schema<'auto' | 'manual'>),\n agentId: s.opt(\n s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Required by send_input, close, and get_result.',\n })\n ),\n runId: s.opt(\n s.str({\n minLength: 1,\n description:\n 'Required by get_result. Identifies one retained child Run, including after close.',\n })\n ),\n after: s.opt(\n s.int({\n minimum: 0,\n description: 'For list_results, return automatic completions after this cursor.',\n })\n ),\n offset: s.opt(\n s.int({\n minimum: 0,\n description:\n 'For get_result, the UTF-16 text offset. Follow response.nextOffset to read the next page.',\n })\n ),\n limit: s.opt(\n s.int({\n minimum: 1,\n maximum: 30_000,\n description:\n 'For get_result, text characters per page (default/max 30000). For list_results, references per page (default 32, max 64).',\n })\n ),\n interrupt: s.opt(\n s.bool({ description: 'For send_input, cancel active work before replacement.' })\n ),\n includeClosed: s.opt(s.bool({ description: 'For list, include permanently closed children.' })),\n },\n { open: false }\n) as s.Schema<AgentAction>;\n\ninterface ListModelsOutput {\n readonly inheritedModel: string;\n readonly models: readonly AvailableAgentModel[];\n}\n\nexport type AgentToolDetails =\n | ({ readonly action: 'get_result' } & { readonly agent: ChildAgentSnapshot })\n | ({ readonly action: 'list_results' } & Awaited<ReturnType<ChildAgentManager['listResults']>>)\n | ({ readonly action: 'list_models' } & ListModelsOutput)\n | ({ readonly action: 'spawn' } & SpawnAgentOutput)\n | ({ readonly action: 'swarm' } & SwarmAgentOutput)\n | ({ readonly action: 'send_input' } & SendInputOutput)\n | ({ readonly action: 'list' } & ListAgentsOutput)\n | ({ readonly action: 'close' } & CloseAgentOutput);\n\n// This Tool owns exact pre-admission validation, action dispatch, and model-visible results.\nexport function createAgentTool(options: {\n readonly parentSessionId: string;\n readonly inheritedModel: string;\n readonly listAvailableModels: () => Promise<readonly AvailableAgentModel[]>;\n readonly manager: ChildAgentManager;\n}): ContextualTool<typeof AgentToolParametersSchema, AgentToolDetails> {\n return {\n name: 'agent',\n label: 'Agent',\n description:\n 'Query models or manage persistent direct child Sessions. Give every spawned child a short, pleasant name and a brief assignment description. Children inherit the parent Run Tool permissions, Sandbox policy, Workspace, and ordinary Tool set. spawn returns after admission with auto delivery by default; completionDelivery manual disables automatic delivery for the lifetime of that child. swarm admits prompts concurrently, waits for all admitted Runs to settle, and returns their results; its children use manual delivery, including later send_input Runs. send_input steers a running child at its next tool boundary or starts a Run when idle; it returns once accepted, without waiting for completion. interrupt cancels the current Run first. For auto children, completions refresh child_runs and wake this Session unless their references already appeared in a committed parent model request; report ongoing work and end your turn instead of polling. Manual children never wake this Session: when the next step needs a result, call the wait Tool with the child runId, then read it with get_result. For auto children, use wait only when the next step needs the result. get_result reads an exact agentId/runId result, including closed children; follow response.nextOffset with offset for remaining text. list_results pages only automatic completion references, excluding manual results. list inspects owned children; close releases execution resources. Every child snapshot reports cumulative committed Pi usage and unsettled request counts. Use list_models before selecting a non-inherited model.',\n parameters: AgentToolParametersSchema,\n prepareArguments: (input) =>\n parseAgentAction(parseToolParameters('agent', AgentActionSchema, input)),\n executionMode: 'parallel',\n execute: async (action, context) => {\n try {\n let details: AgentToolDetails;\n switch (action.action) {\n case 'get_result':\n details = {\n action: 'get_result',\n agent: await options.manager.getResult({\n parentSessionId: options.parentSessionId,\n agentId: action.agentId,\n runId: action.runId,\n offset: action.offset,\n limit: action.limit,\n context,\n }),\n };\n break;\n case 'list_results':\n details = {\n action: 'list_results',\n ...(await options.manager.listResults({\n parentSessionId: options.parentSessionId,\n after: action.after,\n limit: action.limit,\n context,\n })),\n };\n break;\n case 'list_models': {\n context.signal?.throwIfAborted();\n const models = await options.listAvailableModels();\n context.signal?.throwIfAborted();\n details = {\n action: 'list_models',\n inheritedModel: options.inheritedModel,\n models,\n };\n break;\n }\n case 'spawn':\n details = {\n action: 'spawn',\n ...(await options.manager.spawn({\n parentSessionId: options.parentSessionId,\n request: action,\n context,\n })),\n };\n break;\n case 'swarm':\n details = {\n action: 'swarm',\n ...(await options.manager.swarm({\n parentSessionId: options.parentSessionId,\n request: action,\n context,\n })),\n };\n break;\n case 'send_input':\n details = {\n action: 'send_input',\n ...(await options.manager.send({\n parentSessionId: options.parentSessionId,\n request: action,\n context,\n })),\n };\n break;\n case 'list':\n details = {\n action: 'list',\n ...(await options.manager.listAgents({\n parentSessionId: options.parentSessionId,\n request: action,\n context,\n })),\n };\n break;\n case 'close':\n details = {\n action: 'close',\n ...(await options.manager.closeChild({\n parentSessionId: options.parentSessionId,\n agentId: action.agentId,\n context,\n })),\n };\n break;\n }\n return {\n content: [{ type: 'text', text: JSON.stringify(details) }],\n details,\n };\n } catch (cause) {\n throw childToolExecutionError(\n toError(cause),\n 'agent_operation_failed',\n `Agent ${action.action} failed`\n );\n }\n },\n };\n}\n","import * as s from '@earendil-works/pi-schema';\nimport toError from 'ensure-error';\nimport { parseToolParameters, type ContextualTool } from '@sorbetai/runtime';\n\nimport {\n childToolExecutionError,\n type ListTeamPeersOutput,\n type SendTeamMessageOutput,\n} from './contracts.js';\nimport type { ChildAgentManager } from './manager.js';\n\nconst NON_EMPTY_STRING_MIN_LENGTH = 1;\nconst SAFE_ID_PATTERN = '^[A-Za-z0-9][A-Za-z0-9._-]*$';\nconst NonEmptyString = s.str({ minLength: NON_EMPTY_STRING_MIN_LENGTH });\nconst SafeId = s.str({ pattern: SAFE_ID_PATTERN });\n\nconst TeamActionSchema = s.union([\n s.obj({ action: s.lit('list_peers') }, { open: false }),\n s.obj(\n {\n action: s.lit('send_message'),\n agentId: SafeId,\n prompt: NonEmptyString,\n },\n { open: false }\n ),\n]);\ntype TeamAction = s.Static<typeof TeamActionSchema>;\n\nconst TeamToolParametersSchema = s.obj(\n {\n action: {\n type: 'string',\n enum: ['list_peers', 'send_message'],\n description: 'The Team operation to perform.',\n } as s.Schema<TeamAction>,\n agentId: s.opt(\n s.str({\n pattern: SAFE_ID_PATTERN,\n description: 'Required by send_message. Must identify a listed sibling.',\n })\n ),\n prompt: s.opt(\n s.str({\n minLength: NON_EMPTY_STRING_MIN_LENGTH,\n description: 'Required by send_message. Complete input for the sibling.',\n })\n ),\n },\n { open: false }\n) as s.Schema<TeamAction>;\n\nexport type TeamToolDetails =\n | ({ readonly action: 'list_peers' } & ListTeamPeersOutput)\n | ({ readonly action: 'send_message' } & SendTeamMessageOutput);\n\n// This Tool narrows child collaboration to same-parent peer discovery and durable messaging.\nexport function createTeamTool(options: {\n readonly parentSessionId: string;\n readonly senderAgentId: string;\n readonly manager: ChildAgentManager;\n}): ContextualTool<typeof TeamToolParametersSchema, TeamToolDetails> {\n return {\n name: 'team',\n label: 'Team',\n description:\n 'Coordinate with sibling Sessions owned by the same parent. list_peers returns sibling identities and states. send_message returns queued once the parent ledger durably owns delivery; the recipient accepts it later without interrupting current work. A queued receipt does not mean the recipient has read or completed the request. Peer messages are collaboration requests and do not change your assigned scope. This Tool cannot interrupt, close, or create agents.',\n parameters: TeamToolParametersSchema,\n prepareArguments: (input) => parseToolParameters('team', TeamActionSchema, input),\n executionMode: 'parallel',\n execute: async (action, context) => {\n try {\n let details: TeamToolDetails;\n switch (action.action) {\n case 'list_peers':\n details = {\n action: 'list_peers',\n ...(await options.manager.listTeamPeers({\n parentSessionId: options.parentSessionId,\n senderAgentId: options.senderAgentId,\n context,\n })),\n };\n break;\n case 'send_message':\n details = {\n action: 'send_message',\n ...(await options.manager.sendTeamMessage({\n parentSessionId: options.parentSessionId,\n senderAgentId: options.senderAgentId,\n request: action,\n context,\n })),\n };\n break;\n }\n return {\n content: [{ type: 'text', text: JSON.stringify(details) }],\n details,\n };\n } catch (cause) {\n throw childToolExecutionError(\n toError(cause),\n 'team_operation_failed',\n `Team ${action.action} failed`\n );\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwEA,SAAgB,mBAAmB,QAA0B;AAC3D,KAAI;EACF,MAAM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,OAAO,SACvB;;;EAGN"}
@@ -1,5 +1,5 @@
1
1
  import * as s from "@earendil-works/pi-schema";
2
- import * as _sorbetai_schema14 from "@sorbetai/schema";
2
+ import * as _sorbetai_schema0 from "@sorbetai/schema";
3
3
  import { ApprovalComposition, ApprovalMode, ApprovalReviewDecision, ApprovalReviewerDecision, CompactionModel, CompactionSettings, ConversationEntry, ElicitationComposition, JournalFact, JsonValue, ModelRetryEndEvent, ModelRetryStartEvent, PermissionComposition, RunExecutionResourceProvider, RuntimeObservationPort, SendSessionInput, SessionInputSource, StartRunInput, StartRunOptions, SubmissionControlInputSchema, ToolDiscoveryMetadata, ToolInvocationContext, ToolPermissionPolicy, ToolPermissionRequest, ToolSearchOptions, UnitModelContext, UnitStore, UnitTx, WaitMember } from "@sorbetai/runtime";
4
4
  import { AssistantMessage, ContextManager, ContextSource, Message, ModelRequestSettings, NamedStateOwner, ToolCall, ToolDeclaration } from "@sorbetai/context";
5
5
  import { PluginModelProvider } from "@sorbetai/plugins/model";
@@ -67,7 +67,7 @@ declare const ToolResultSchema: s.Schema<{
67
67
  })[];
68
68
  isError: boolean;
69
69
  terminate?: boolean | undefined;
70
- structuredContent?: string | number | boolean | _sorbetai_schema14.JsonArray | _sorbetai_schema14.JsonObject | null | undefined;
70
+ structuredContent?: string | number | boolean | _sorbetai_schema0.JsonArray | _sorbetai_schema0.JsonObject | null | undefined;
71
71
  usage?: {
72
72
  input: number;
73
73
  output: number;
@@ -93,7 +93,7 @@ declare const ToolResultSchema: s.Schema<{
93
93
  };
94
94
  estimatedTextTokens: number;
95
95
  } | undefined;
96
- details?: string | number | boolean | _sorbetai_schema14.JsonArray | _sorbetai_schema14.JsonObject | null | undefined;
96
+ details?: string | number | boolean | _sorbetai_schema0.JsonArray | _sorbetai_schema0.JsonObject | null | undefined;
97
97
  }>;
98
98
  type ToolResult = s.Static<typeof ToolResultSchema>;
99
99
  interface DurableToolContext extends Omit<ToolInvocationContext, 'executeTool'> {
@@ -270,4 +270,4 @@ interface OpenDurableUnitOptions {
270
270
  interface OpenDurableSessionOptions extends DurableSessionOptions, OpenDurableUnitOptions {}
271
271
  //#endregion
272
272
  export { WaitTargetSource as _, DurableRunEnvironment as a, DurableToolContext as c, ModelRequest as d, ModelTransport as f, WaitTarget as g, ToolResult as h, DurableInput as i, ModelDelta as l, OpenDurableUnitOptions as m, ApprovalDecision as n, DurableSessionOptions as o, OpenDurableSessionOptions as p, DurableDisplayEntry as r, DurableTool as s, AdmissionPolicy as t, ModelIdentity as u };
273
- //# sourceMappingURL=contracts-L7iISO7a.d.ts.map
273
+ //# sourceMappingURL=contracts-ui4Wvp-X.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { _ as WaitTargetSource, a as DurableRunEnvironment, c as DurableToolContext, d as ModelRequest, f as ModelTransport, g as WaitTarget, h as ToolResult, i as DurableInput, l as ModelDelta, m as OpenDurableUnitOptions, n as ApprovalDecision, o as DurableSessionOptions, p as OpenDurableSessionOptions, r as DurableDisplayEntry, s as DurableTool, u as ModelIdentity } from "./contracts-L7iISO7a.js";
2
- import { i as DurableRun, n as DurableUnit, r as DurableUnitSession, t as DurableSession } from "./unit-DO2c0Lvm.js";
1
+ import { _ as WaitTargetSource, a as DurableRunEnvironment, c as DurableToolContext, d as ModelRequest, f as ModelTransport, g as WaitTarget, h as ToolResult, i as DurableInput, l as ModelDelta, m as OpenDurableUnitOptions, n as ApprovalDecision, o as DurableSessionOptions, p as OpenDurableSessionOptions, r as DurableDisplayEntry, s as DurableTool, u as ModelIdentity } from "./contracts-ui4Wvp-X.js";
2
+ import { i as DurableRun, n as DurableUnit, r as DurableUnitSession, t as DurableSession } from "./unit-CzXj3f0q.js";
3
3
  export { type ApprovalDecision, type DurableDisplayEntry, type DurableInput, type DurableRun, type DurableRunEnvironment, DurableSession, type DurableSessionOptions, type DurableTool, type DurableToolContext, DurableUnit, type DurableUnitSession, type ModelDelta, type ModelIdentity, type ModelRequest, type ModelTransport, type OpenDurableSessionOptions, type OpenDurableUnitOptions, type ToolResult, type WaitTarget, type WaitTargetSource };
package/dist/pi.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { a as DurableRunEnvironment, f as ModelTransport, o as DurableSessionOptions, r as DurableDisplayEntry } from "./contracts-L7iISO7a.js";
2
- import { t as DurableSession } from "./unit-DO2c0Lvm.js";
3
- import * as _sorbetai_schema0 from "@sorbetai/schema";
1
+ import { a as DurableRunEnvironment, f as ModelTransport, o as DurableSessionOptions, r as DurableDisplayEntry } from "./contracts-ui4Wvp-X.js";
2
+ import { t as DurableSession } from "./unit-CzXj3f0q.js";
3
+ import * as _sorbetai_schema5 from "@sorbetai/schema";
4
4
  import * as _sorbetai_runtime0 from "@sorbetai/runtime";
5
5
  import { AppendPluginRecord, ApprovalComposition, ApprovalReviewer, CompactionSettings, CompleteModelInput, CompleteModelOptions, ContextualTool, ContinuationReplayPlan, DiscoverableTool, DurableSubmission, ElicitationComposition, InvokeToolInput, InvokeToolOptions, JournalCursor, JournalReadOptions, JournalSubscription, ModelRetryPolicy, PermissionComposition, PluginRecord, PluginRecordOwner, ProjectedRequestContext, ResumeInterruptedRunOptions, RunCancellationReceipt, RunInputPlacementReceipt, RunTerminalOutcome, RunView, RuntimeObservationPort, SendSessionInput, SendSessionInputOptions, SessionInputAcceptedReceipt, SessionInputSubmission, SessionInspection, SessionInspectionOptions, SorbetRun, StartContinuationInput, StartRunInput, StartRunOptions, ToolOutputFileStore, ToolPermissionPolicy, ToolSearchOptions, UnitModelContext, UnitRuntime } from "@sorbetai/runtime";
6
6
  import { ContextManager, ContextSource, ModelRequestSettings, NamedStateOwner } from "@sorbetai/context";
@@ -172,7 +172,7 @@ declare class SorbetSession {
172
172
  type: "toolCall";
173
173
  id: string;
174
174
  name: string;
175
- arguments: Record<string, _sorbetai_schema0.JsonValue>;
175
+ arguments: Record<string, _sorbetai_schema5.JsonValue>;
176
176
  thoughtSignature?: string | undefined;
177
177
  argumentsError?: string | undefined;
178
178
  })[];
@@ -209,7 +209,7 @@ declare class SorbetSession {
209
209
  stack?: string | undefined;
210
210
  code?: string | number | undefined;
211
211
  } | undefined;
212
- details?: Record<string, _sorbetai_schema0.JsonValue> | undefined;
212
+ details?: Record<string, _sorbetai_schema5.JsonValue> | undefined;
213
213
  }[] | undefined;
214
214
  deferred?: {
215
215
  provider: string;
@@ -218,7 +218,7 @@ declare class SorbetSession {
218
218
  id: string;
219
219
  expiresAt?: number | undefined;
220
220
  pollAfterMs?: number | undefined;
221
- data?: string | number | boolean | _sorbetai_schema0.JsonArray | _sorbetai_schema0.JsonObject | null | undefined;
221
+ data?: string | number | boolean | _sorbetai_schema5.JsonArray | _sorbetai_schema5.JsonObject | null | undefined;
222
222
  } | undefined;
223
223
  errorMessage?: string | undefined;
224
224
  rawStopReason?: string | undefined;
@@ -241,7 +241,7 @@ declare class SorbetSession {
241
241
  })[];
242
242
  isError: boolean;
243
243
  timestamp: number;
244
- details?: string | number | boolean | _sorbetai_schema0.JsonArray | _sorbetai_schema0.JsonObject | null | undefined;
244
+ details?: string | number | boolean | _sorbetai_schema5.JsonArray | _sorbetai_schema5.JsonObject | null | undefined;
245
245
  usage?: {
246
246
  input: number;
247
247
  output: number;
@@ -278,9 +278,9 @@ declare class SorbetSession {
278
278
  displayEntries(): Promise<readonly DurableDisplayEntry[]>;
279
279
  write(input: Parameters<DurableSession['write']>[0]): Promise<DurableSubmission>;
280
280
  reset(input: Parameters<DurableSession['reset']>[0]): Promise<DurableSubmission>;
281
- tasks(): readonly _sorbetai_runtime0.TaskRecord<_sorbetai_schema0.JsonValue, Record<string, _sorbetai_schema0.JsonValue> & {
281
+ tasks(): readonly _sorbetai_runtime0.TaskRecord<_sorbetai_schema5.JsonValue, Record<string, _sorbetai_schema5.JsonValue> & {
282
282
  phase: string;
283
- }, _sorbetai_schema0.JsonValue>[];
283
+ }, _sorbetai_schema5.JsonValue>[];
284
284
  retryTask(taskId: string, commandId: string): Promise<void>;
285
285
  getUsage(): Promise<_sorbetai_runtime0.SessionUsageSnapshot>;
286
286
  setThinkingLevel(level: Parameters<DurableSession['setThinkingLevel']>[0]): void;
@@ -288,7 +288,7 @@ declare class SorbetSession {
288
288
  listPermissionGrants(): Promise<readonly Readonly<{
289
289
  grantId: string;
290
290
  toolName: string;
291
- parameters: string | number | boolean | _sorbetai_schema0.JsonArray | _sorbetai_schema0.JsonObject | null;
291
+ parameters: string | number | boolean | _sorbetai_schema5.JsonArray | _sorbetai_schema5.JsonObject | null;
292
292
  sourceToolCallId: string;
293
293
  grantedAt: string;
294
294
  sourceRunId?: string | undefined;
@@ -305,7 +305,7 @@ declare class SorbetSession {
305
305
  listBehaviors(): Promise<readonly _sorbetai_runtime0.SessionBehaviorSnapshot[]>;
306
306
  commandBehavior(...args: Parameters<DurableSession['commandBehavior']>): Promise<{
307
307
  active: boolean;
308
- contextState?: string | number | boolean | _sorbetai_schema0.JsonArray | _sorbetai_schema0.JsonObject | null | undefined;
308
+ contextState?: string | number | boolean | _sorbetai_schema5.JsonArray | _sorbetai_schema5.JsonObject | null | undefined;
309
309
  constraints?: {
310
310
  toolNames: string[];
311
311
  workspace?: "read-only" | undefined;
@@ -331,7 +331,7 @@ declare class SorbetSession {
331
331
  }>;
332
332
  reviewBehavior(...args: Parameters<DurableSession['reviewBehavior']>): Promise<{
333
333
  active: boolean;
334
- contextState?: string | number | boolean | _sorbetai_schema0.JsonArray | _sorbetai_schema0.JsonObject | null | undefined;
334
+ contextState?: string | number | boolean | _sorbetai_schema5.JsonArray | _sorbetai_schema5.JsonObject | null | undefined;
335
335
  constraints?: {
336
336
  toolNames: string[];
337
337
  workspace?: "read-only" | undefined;
@@ -1,4 +1,4 @@
1
- import { i as DurableInput, m as OpenDurableUnitOptions, n as ApprovalDecision, o as DurableSessionOptions, p as OpenDurableSessionOptions, r as DurableDisplayEntry, t as AdmissionPolicy } from "./contracts-L7iISO7a.js";
1
+ import { i as DurableInput, m as OpenDurableUnitOptions, n as ApprovalDecision, o as DurableSessionOptions, p as OpenDurableSessionOptions, r as DurableDisplayEntry, t as AdmissionPolicy } from "./contracts-ui4Wvp-X.js";
2
2
  import * as _sorbetai_schema23 from "@sorbetai/schema";
3
3
  import * as _sorbetai_runtime15 from "@sorbetai/runtime";
4
4
  import { AppendPluginRecord, ApprovalReviewRequest, CompactionResult, ContinuationReplayPlan, DurableSubmission, JournalFact, PluginRecord, PluginRecordOwner, ResumeInterruptedRunOptions, SendSessionInputOptions, SessionBehaviors, SessionHistoryProjection, SessionUsageProjection, StartContinuationInput, StartRunInput, StartRunOptions, TaskRecord, UnitRuntime, UserPrompt } from "@sorbetai/runtime";
@@ -251,4 +251,4 @@ declare const DurableSession: {
251
251
  };
252
252
  //#endregion
253
253
  export { DurableRun as i, DurableUnit as n, DurableUnitSession as r, DurableSession as t };
254
- //# sourceMappingURL=unit-DO2c0Lvm.d.ts.map
254
+ //# sourceMappingURL=unit-CzXj3f0q.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sorbetai/durable",
3
- "version": "0.1.0-alpha.16",
3
+ "version": "0.1.0-alpha.17",
4
4
  "license": "MIT",
5
5
  "description": "Task-driven durable Run execution for Sorbet",
6
6
  "type": "module",
@@ -27,7 +27,7 @@
27
27
  "tsdown": "0.15.12",
28
28
  "tsx": "^4.23.15",
29
29
  "vitest": "^3.2.4",
30
- "@sorbetai/goal": "0.1.0-alpha.16"
30
+ "@sorbetai/goal": "0.1.0-alpha.17"
31
31
  },
32
32
  "dependencies": {
33
33
  "@earendil-works/pi-ai": "1.5.0",
@@ -36,11 +36,11 @@
36
36
  "es-toolkit": "^1.53.1",
37
37
  "race-signal": "2.0.2",
38
38
  "@earendil-works/pi-schema": "1.5.0",
39
- "@sorbetai/artifacts": "0.1.0-alpha.16",
40
- "@sorbetai/plugins": "0.1.0-alpha.16",
41
- "@sorbetai/schema": "0.1.0-alpha.16",
42
- "@sorbetai/context": "0.1.0-alpha.16",
43
- "@sorbetai/runtime": "0.1.0-alpha.16"
39
+ "@sorbetai/runtime": "0.1.0-alpha.17",
40
+ "@sorbetai/schema": "0.1.0-alpha.17",
41
+ "@sorbetai/artifacts": "0.1.0-alpha.17",
42
+ "@sorbetai/context": "0.1.0-alpha.17",
43
+ "@sorbetai/plugins": "0.1.0-alpha.17"
44
44
  },
45
45
  "repository": {
46
46
  "type": "git",