@mastra/factory 0.28.0-alpha.13 → 0.28.0-alpha.14
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.
- package/README.md +31 -18
- package/dist/environment/build-runner.d.ts +13 -2
- package/dist/environment/build-runner.d.ts.map +1 -1
- package/dist/environment/build-runner.js +42 -0
- package/dist/environment/build-runner.js.map +1 -1
- package/dist/environment/build-workflow.d.ts +6 -4
- package/dist/environment/build-workflow.d.ts.map +1 -1
- package/dist/environment/build-workflow.js +70 -66
- package/dist/environment/build-workflow.js.map +1 -1
- package/dist/environment/build.d.ts +19 -4
- package/dist/environment/build.d.ts.map +1 -1
- package/dist/environment/build.js +70 -14
- package/dist/environment/build.js.map +1 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +21 -21
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/sandbox-release.d.ts +12 -0
- package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
- package/dist/integrations/github/sandbox-release.js +16 -1
- package/dist/integrations/github/sandbox-release.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +5 -0
- package/dist/routes/board-snapshot.d.ts.map +1 -1
- package/dist/routes/board-snapshot.js +12 -1
- package/dist/routes/board-snapshot.js.map +1 -1
- package/dist/routes/contracts.d.ts +66 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +41 -1
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +5 -0
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/sandbox-envs.d.ts +2 -0
- package/dist/routes/sandbox-envs.d.ts.map +1 -1
- package/dist/routes/sandbox-envs.js +3 -0
- package/dist/routes/sandbox-envs.js.map +1 -1
- package/dist/routes/source-control-settings.d.ts +2 -0
- package/dist/routes/source-control-settings.d.ts.map +1 -1
- package/dist/routes/source-control-settings.js +5 -0
- package/dist/routes/source-control-settings.js.map +1 -1
- package/dist/routes/surface.d.ts +2 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +2 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-item-activity.d.ts +11 -0
- package/dist/routes/work-item-activity.d.ts.map +1 -0
- package/dist/routes/work-item-activity.js +25 -0
- package/dist/routes/work-item-activity.js.map +1 -0
- package/dist/routes/work-item-starters.d.ts +29 -0
- package/dist/routes/work-item-starters.d.ts.map +1 -0
- package/dist/routes/work-item-starters.js +169 -0
- package/dist/routes/work-item-starters.js.map +1 -0
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +59 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/transition-service.d.ts +20 -2
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +40 -18
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/sandbox/context-sandboxes.d.ts +70 -0
- package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
- package/dist/sandbox/context-sandboxes.js +120 -0
- package/dist/sandbox/context-sandboxes.js.map +1 -0
- package/dist/sandbox/session-retirement.d.ts +11 -4
- package/dist/sandbox/session-retirement.d.ts.map +1 -1
- package/dist/sandbox/session-retirement.js +39 -13
- package/dist/sandbox/session-retirement.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +8 -2
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +21 -4
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/tools/annotations.d.ts.map +1 -1
- package/dist/tools/annotations.js +4 -0
- package/dist/tools/annotations.js.map +1 -1
- package/dist/tools/audit-events-tool.d.ts +29 -0
- package/dist/tools/audit-events-tool.d.ts.map +1 -0
- package/dist/tools/audit-events-tool.js +180 -0
- package/dist/tools/audit-events-tool.js.map +1 -0
- package/dist/tools/index.d.ts +2 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +2 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/permissions.d.ts.map +1 -1
- package/dist/tools/permissions.js +1 -0
- package/dist/tools/permissions.js.map +1 -1
- package/package.json +9 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transition-service.js","names":[],"sources":["../../src/rules/transition-service.ts"],"sourcesContent":["import { DEFAULT_BOARD_ID, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { autoApprovedExitTool, exitToolSucceeded } from '../boards/phase-automation.js';\nimport { phaseRunDecision } from '../boards/phase-runner.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { boardFlow, boardForWorkItem, hasPullRequest, pullRequestCardRejection } from '../boards/semantics.js';\nimport { boardTransitionPolicyResultSchema, immutablePolicySnapshot } from '../boards/transition-policy.js';\nimport type { AuditActorProfileInput, AuditActorType, AuditContext } from '../storage/domains/audit/base.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport { isAgentActor } from '../storage/domains/work-items/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleActor,\n FactoryRuleBoard,\n FactoryRuleCausalEntry,\n FactoryRuleRejectionCode,\n FactoryRuleStage,\n FactoryStageRuleContext,\n FactoryTransitionResult,\n FactoryTransitionResultRejected,\n} from './types.js';\nimport { factoryRuleSourceForWorkItem, workItemSource } from './types.js';\nimport {\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n assertFactoryDecisionTarget,\n validateFactoryRuleDecision,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\nconst MAX_REJECTION_REASON = 512;\n/** Longest a committed transition waits for terminal resource cleanup. Cleanup\n * reattaches remote sandboxes, so a hung provider call must not leave the\n * already-committed transition request pending; past this bound the cleanup\n * keeps running in the background as pure best-effort. */\nconst TERMINAL_CLEANUP_TIMEOUT_MS = 30_000;\n\nexport interface FactoryTransitionRequest {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** Installed board id; the service rejects boards that are not installed. */\n board: string;\n stage: FactoryRuleStage;\n expectedRevision: number;\n actor: FactoryRuleActor;\n actorProfile?: AuditActorProfileInput;\n /** Where a browser request came from; rules and agents carry none. */\n context?: AuditContext;\n ingress: { type: 'human' | 'agent' | 'toolResult' | 'github' | 'rule'; identity: string; transitionId?: string };\n cause: string;\n causalChain?: readonly FactoryRuleCausalEntry[];\n /** Internal materialization path: start the destination phase's runner even when already at that stage. */\n initialEntry?: boolean;\n /** Starts the stage's runner again when the item already holds that stage, to restart work the entry invalidated. */\n reenter?: boolean;\n /** Internal proof that this move consumes an approved `submit_plan` result. */\n planApproved?: true;\n /** Internal: the tool whose successful result this move consumes (a tool-result rule's move). */\n completedTool?: string;\n /**\n * Internal: an intake route moves the card on a status event. A route is admin-authored, so it\n * may name any phase on the card's board regardless of the board's next phases, working ones\n * included. The phase's `autoStart` and the dispatcher's approval check decide whether its run starts.\n */\n eventRoute?: { routeId: string };\n}\n\nexport interface FactoryTransitionServiceOptions {\n configVersion: string;\n storage: WorkItemsStorage;\n /** A fixed registry, or the per-project boards; each transition loads its project's boards. */\n boards?: BoardRegistry | ProjectBoardSource;\n /** Every commit, accepted or rejected, lands here as `stage_moved` / `transition_rejected` under the request's actor. */\n audit?: AuditRecorder;\n timeoutMs?: number;\n /**\n * Called after a transition commits into a phase the board declares\n * terminal — the point where the item's sessions stop receiving runs, so\n * resources they hold (e.g. sandboxes) can be released for reuse. Awaited,\n * but failures are swallowed: releasing resources must never break or roll\n * back the committed transition.\n */\n onTerminalStage?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n stage: FactoryRuleStage;\n revision: number;\n /** The actor that committed this terminal transition. Lets cleanup leave\n * the seat that drove its own transition (an agent tool call) untouched. */\n actor: FactoryRuleActor;\n }) => Promise<void> | void;\n /**\n * Called after a transition commits a stage change, e.g. to tell the item's\n * followers. Not awaited, and failures are logged: a notification must never\n * fail or delay the committed transition.\n */\n onTransitionCommitted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n fromStage: string | undefined;\n toStage: string;\n }) => Promise<void> | void;\n /** Upper bound on how long a committed transition waits for\n * `onTerminalStage` before returning (default 30s). The cleanup continues\n * in the background past the bound. */\n terminalCleanupTimeoutMs?: number;\n /**\n * Called after a person moves a Work card from Intake or Triage into Planning or\n * Building, which approves the work. Fire-and-forget: failures are swallowed, the committed transition never\n * depends on it.\n */\n onAccepted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n item: Card;\n }) => Promise<void> | void;\n}\n\nfunction rejection(\n transitionId: string,\n itemId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n): FactoryTransitionResult {\n return { status: 'rejected', transitionId, itemId, code, reason: reason.slice(0, MAX_REJECTION_REASON) };\n}\n\nfunction actorId(actor: FactoryRuleActor): string {\n switch (actor.type) {\n case 'human':\n case 'system':\n return actor.id;\n case 'agent':\n return `agent:${actor.bindingId}`;\n case 'github':\n return `github:${actor.login}`;\n case 'gitlab':\n return `gitlab:${actor.username}`;\n }\n}\n\n// The dispatcher executes an agent-approved decision as a human actor so its consent carries; the trail still names the agent.\nexport function auditActorOf(actor: FactoryRuleActor): { actorId: string; actorType: AuditActorType } {\n const id = actorId(actor);\n switch (actor.type) {\n case 'github':\n case 'gitlab':\n return { actorId: id, actorType: 'human' };\n case 'human':\n return { actorId: id, actorType: isAgentActor(id) ? 'agent' : 'human' };\n default:\n return { actorId: id, actorType: actor.type };\n }\n}\n\nfunction isStale(result: FactoryTransitionResult): result is FactoryTransitionResultRejected {\n return result.status === 'rejected' && result.code === 'stale';\n}\n\n/** Tell the caller where the card is now, so a model doesn't read \"stale\" as \"already moved\". */\nfunction staleRejection(result: FactoryTransitionResultRejected, current: Card): FactoryTransitionResult {\n const stage = currentStage(current.stages) ?? current.stages.join(', ');\n return rejection(\n result.transitionId,\n result.itemId,\n 'stale',\n `The card changed (now revision ${current.revision}, in ${stage}). Retry with expectedRevision ${current.revision} if the move still applies.`,\n );\n}\n\nexport function currentStage(stages: readonly string[]): FactoryRuleStage | undefined {\n return stages.length === 1 ? stages[0] : undefined;\n}\n\ninterface TransitionConsentOptions {\n autonomy?: 'arm' | 'disarm';\n consentedBy?: string;\n /** A person moved a card into its board's build seat from before it (see {@link acceptsWork}): that move approves the work. */\n accepted?: boolean;\n}\n\n/**\n * Whether moving a card from `from` to `to` hands it to the board's builder for the first time: `to`\n * runs in the seat of the board's build phase ({@link boardFlow}), and `from` is a resting phase or a\n * working phase of another seat that is no review (Work: Intake or Triage into Planning or Building).\n */\nfunction acceptsWork(board: InstalledBoard, from: string, to: string): boolean {\n const buildRole = boardFlow(board).buildRole;\n if (!buildRole || board.roleForPhase(to) !== buildRole) return false;\n const fromPhase = board.phases[from];\n if (!fromPhase || fromPhase.kind === 'terminal') return false;\n if (fromPhase.kind === 'resting') return true;\n const fromRole = fromPhase.runner.context;\n return fromRole !== buildRole && fromRole !== REVIEW_CONTEXT;\n}\n\n// Entering a resting lane disarms whoever rests it; only a person's move into a working lane arms.\nfunction transitionConsent(working: boolean, humanMove: boolean): 'arm' | 'disarm' | undefined {\n if (!working) return 'disarm';\n return humanMove ? 'arm' : undefined;\n}\n\n// An event arriving as data (GitHub, sweeps) never pre-approves the runs its transition queues.\nfunction bearsConsent(actor: FactoryRuleActor): boolean {\n return actor.type === 'human' || actor.type === 'agent';\n}\n\n// Rides the transition's own revision-checked commit, so a stale or rejected commit flips nothing.\nfunction consentEffect(\n request: FactoryTransitionRequest,\n working: boolean,\n humanMove: boolean,\n): TransitionConsentOptions {\n // A provider event (a reopen, a close) is not a person's say-so: whatever a person armed before\n // no longer stands once a route moves the card.\n if (request.eventRoute) return { autonomy: 'disarm' };\n const autonomy = transitionConsent(working, humanMove);\n return bearsConsent(request.actor) ? { autonomy, consentedBy: actorId(request.actor) } : { autonomy };\n}\n\ntype RunStartDecision = Extract<FactoryCommitDecision, { type: 'invokeSkill' | 'sendMessage' }>;\n\nfunction startsRun(decision: FactoryCommitDecision): decision is RunStartDecision {\n return decision.type === 'invokeSkill' || (decision.type === 'sendMessage' && decision.prepareBinding === true);\n}\n\n// Answering a recorded run start, or the role's own mid-run agent, with a run would start a second one.\n// A run that starts after its own agent's move is queued onto that agent's run instead.\nfunction runAlreadyUnderway(request: FactoryTransitionRequest, decision: RunStartDecision): boolean {\n if (request.cause === 'run_start') return true;\n if (decision.type === 'invokeSkill' && decision.startsAfterOwnMove === true) return false;\n return request.actor.type === 'agent' && request.actor.role === decision.role;\n}\n\nfunction stageTransitionMessage(fromStage: FactoryRuleStage, toStage: FactoryRuleStage): string {\n return `This work was moved from the ${fromStage} stage to the ${toStage} stage.`;\n}\n\nfunction isHumanTransition(request: FactoryTransitionRequest): boolean {\n return request.actor.type === 'human' && request.ingress.type === 'human';\n}\n\nfunction ruleFailure(error: unknown): { code: FactoryRuleRejectionCode; reason: string } {\n return {\n code: 'rule_error',\n reason: error instanceof Error ? `Factory rule failed: ${error.message}` : 'Factory rule failed.',\n };\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), timeoutMs);\n });\n try {\n return await Promise.race([operation, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport class FactoryTransitionService {\n readonly #configVersion: string;\n readonly #boards: ProjectBoardSource;\n readonly #storage: WorkItemsStorage;\n readonly #timeoutMs: number;\n readonly #onTerminalStage: FactoryTransitionServiceOptions['onTerminalStage'];\n readonly #terminalCleanupTimeoutMs: number;\n readonly #onAccepted: FactoryTransitionServiceOptions['onAccepted'];\n readonly #onTransitionCommitted: FactoryTransitionServiceOptions['onTransitionCommitted'];\n readonly #audit: AuditRecorder | undefined;\n\n constructor(options: FactoryTransitionServiceOptions) {\n this.#configVersion = options.configVersion;\n this.#boards = toBoardSource(options.boards);\n this.#storage = options.storage;\n this.#audit = options.audit;\n this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;\n this.#onTerminalStage = options.onTerminalStage;\n this.#onAccepted = options.onAccepted;\n this.#onTransitionCommitted = options.onTransitionCommitted;\n this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;\n }\n\n get configVersion(): string {\n return this.#configVersion;\n }\n\n async transition(request: FactoryTransitionRequest): Promise<FactoryTransitionResult> {\n const replay = await this.#storage.getTransitionResultByIngress(\n request.orgId,\n request.factoryProjectId,\n request.ingress.identity,\n );\n if (replay) return replay as unknown as FactoryTransitionResult;\n\n const transitionId = request.ingress.transitionId ?? globalThis.crypto.randomUUID();\n const item = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (!item) {\n const rejection = await this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'Work item not found.',\n );\n await this.#recordTransition(request, undefined, rejection);\n return rejection;\n }\n let result = await this.#evaluateAndCommit(request, transitionId, item);\n if (isStale(result)) {\n const current = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (current) result = staleRejection(result, current);\n }\n await this.#recordTransition(request, item, result);\n this.#notifyCommitted(request, item, result);\n return result;\n }\n\n #notifyCommitted(request: FactoryTransitionRequest, item: Card, result: FactoryTransitionResult): void {\n const onTransitionCommitted = this.#onTransitionCommitted;\n if (!onTransitionCommitted || result.status !== 'accepted') return;\n // Board-neutral: `currentStage` only knows the built-in rule stages.\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (result.stage === fromStage) return;\n // Inside the chain so a synchronous throw is isolated the same way an async rejection is.\n void Promise.resolve()\n .then(() =>\n onTransitionCommitted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: item.id,\n fromStage,\n toStage: result.stage,\n }),\n )\n .catch(error => {\n console.warn(`[factory] stage notification failed for work item ${item.id}:`, error);\n });\n }\n\n /** A rejection can outlive its work item: the row still names the id the caller asked for. */\n async #recordTransition(\n request: FactoryTransitionRequest,\n item: Card | undefined,\n result: FactoryTransitionResult,\n ): Promise<void> {\n if (!this.#audit) return;\n // Board-neutral, like the stage notification: `currentStage` only knows the\n // built-in rule stages and would drop custom-board phases.\n const from = item && item.stages.length === 1 ? item.stages[0] : undefined;\n if (result.status === 'accepted' && result.stage === from && !request.reenter) return;\n const outcome =\n result.status === 'accepted'\n ? { action: 'factory.work_item.stage_moved' as const, to: result.stage, revision: result.revision }\n : {\n action: 'factory.work_item.transition_rejected' as const,\n to: request.stage,\n code: result.code,\n reason: result.reason,\n };\n const { action, ...detail } = outcome;\n await this.#audit\n .record({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n ...auditActorOf(request.actor),\n actorProfile: request.actorProfile,\n ...(request.context ? { context: request.context } : {}),\n action,\n idempotencyKey: result.transitionId,\n targets: [{ type: 'work_item', id: item?.id ?? request.workItemId, ...(item ? { name: item.title } : {}) }],\n metadata: {\n transitionId: result.transitionId,\n ingressType: request.ingress.type,\n cause: request.cause,\n configVersion: this.#configVersion,\n ...(from ? { from } : {}),\n ...(request.reenter ? { reenter: true } : {}),\n ...detail,\n },\n })\n .catch(error => {\n console.warn(`[factory] audit failed for transition ${result.transitionId}:`, error);\n });\n }\n\n async #evaluateAndCommit(\n request: FactoryTransitionRequest,\n transitionId: string,\n item: Card,\n ): Promise<FactoryTransitionResult> {\n const boards = await this.#boards.load(request);\n if (request.causalChain && request.causalChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n return this.#commitRejection(\n request,\n transitionId,\n 'causal_depth_exceeded',\n 'Factory rule causal depth exceeded.',\n );\n }\n const itemSource = workItemSource(item.externalSource);\n const source = factoryRuleSourceForWorkItem(itemSource);\n const isPullRequest = source === 'pullRequest' || source === 'gitlabPullRequest';\n // Rows filed before boards were persisted belong to the default board.\n if (item.board === null && !boards.has(DEFAULT_BOARD_ID)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'This legacy work item has no assigned board. Assign an installed board and phase through the work-item PATCH endpoint before transitioning it.',\n );\n }\n const itemBoard = boardForWorkItem(item);\n if (request.board !== itemBoard) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The work item belongs to board \"${itemBoard}\", not \"${request.board}\".`,\n );\n }\n const board = boards.get(request.board);\n if (!board) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `Board \"${request.board}\" is not installed.`,\n );\n }\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!fromStage || !Object.prototype.hasOwnProperty.call(board.phases, fromStage)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not have one canonical phase on the requested board.',\n );\n }\n // The board's own reason comes first: its phase graph alone only says the move is not\n // declared, which leaves an agent moving an issue card to PR review guessing why.\n const cardShapeRejection = pullRequestCardRejection(\n board,\n {\n standalonePullRequest: isPullRequest,\n hasPullRequest: hasPullRequest({ workItem: item.workItem, source: itemSource }),\n },\n request.stage,\n );\n if (cardShapeRejection) {\n return this.#commitRejection(request, transitionId, 'invalid_transition', cardShapeRejection);\n }\n if (\n !Object.prototype.hasOwnProperty.call(board.phases, request.stage) ||\n (!request.eventRoute && !board.allowsTransition(fromStage, request.stage))\n ) {\n const nextStages = [...new Set((board.transitions[fromStage] ?? []).map(transition => transition.to))];\n const nextStagesReason =\n nextStages.length > 0\n ? `Next stages declared from ${fromStage}: ${nextStages.join(', ')}.`\n : `No next stage is declared from ${fromStage}.`;\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The ${board.name} board does not allow moving from ${fromStage} to ${request.stage}. ${nextStagesReason}`,\n );\n }\n\n // The coordinator's own self-move at run start would otherwise inject a second run's kickoff.\n const humanMove = request.actor.type === 'human' && fromStage !== request.stage && request.cause !== 'run_start';\n // The board, not the phase name, says whether a seat is engaged on either side of this move.\n const entersWorking = board.isWorking(request.stage);\n const seatRole = board.roleForPhase(request.stage);\n\n const contextBase = {\n tenant: { orgId: request.orgId, projectId: request.factoryProjectId },\n actor: request.actor,\n ingress: { type: request.ingress.type, id: request.ingress.identity },\n cause: request.cause,\n causalChain: request.causalChain ?? [],\n configVersion: this.#configVersion,\n item: {\n id: item.id,\n source: itemSource,\n sourceKey: item.externalSource\n ? `${item.externalSource.integrationId}:${item.externalSource.type}:${item.externalSource.externalId}`\n : null,\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: [...item.stages],\n workItem: item.workItem,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board: request.board,\n itemRevision: item.revision,\n source,\n fromStage,\n toStage: request.stage,\n } satisfies Omit<FactoryStageRuleContext, 'stage'>;\n\n let evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[]; intents: TransitionConsentOptions }\n | { outcome: 'rejected'; code: string; reason: string };\n try {\n evaluation = await withRuleTimeout(\n (async () => {\n // Plans are approved without a person only where the card's phase auto-approves submit_plan.\n const plansAutoApproved = autoApprovedExitTool(boards, item) === 'submit_plan';\n // A phase with an exit tool holds the card until the tool succeeds (for submit_plan, with\n // an approved plan; autoApprove only decides whether it approves itself). Then the agent,\n // or the board's own rule for the tool, moves the card. A person can move it any time.\n const fromPhase = board.phases[fromStage];\n const exitTool = fromPhase?.kind === 'working' ? fromPhase.exitTool : undefined;\n if (\n request.actor.type !== 'human' &&\n !request.eventRoute &&\n exitTool &&\n fromStage !== request.stage &&\n entersWorking &&\n !(exitTool.id === 'submit_plan' ? request.planApproved === true : request.completedTool === exitTool.id) &&\n !exitToolSucceeded(item, fromStage, exitTool.id)\n ) {\n return {\n outcome: 'rejected' as const,\n code: 'approval_required',\n reason:\n exitTool.id === 'submit_plan'\n ? `${fromPhase!.name} ends when submit_plan comes back with an approved plan; until then the card stays here. Call submit_plan and wait for a person to approve the plan (or for it to be approved automatically), then move the card into ${board.phases[request.stage]?.name ?? request.stage} with factory_transition_work_item.`\n : `${fromPhase!.name} ends when ${exitTool.id} succeeds; until then the card stays here. A person can also move it from the Factory board or a chat they are signed in to.`,\n };\n }\n const policy = boardTransitionPolicyResultSchema.parse(\n await board.transitionPolicy?.(\n immutablePolicySnapshot({\n ...contextBase,\n item: { ...contextBase.item, triageType: item.triageType },\n initialEntry: request.initialEntry ?? false,\n reenter: request.reenter ?? false,\n isHumanTransition: isHumanTransition(request),\n plansAutoApproved,\n planApproved: request.planApproved === true,\n requestedTriageType: undefined,\n }),\n ),\n );\n if (policy?.type === 'reject') {\n return { outcome: 'rejected' as const, code: policy.code, reason: policy.reason };\n }\n const run = phaseRunDecision(board, request.stage, contextBase, {\n initialEntry: request.initialEntry,\n reenter: request.reenter,\n });\n const validated = validateFactoryRuleDecisions(run ? [run] : [], contextBase.causalChain.length).filter(\n decision => {\n assertFactoryDecisionTarget(decision, boards, itemBoard);\n return !(startsRun(decision) && runAlreadyUnderway(request, decision));\n },\n );\n if (humanMove) {\n const message = stageTransitionMessage(fromStage, request.stage);\n const skill = validated.find(decision => decision.type === 'invokeSkill');\n if (skill) {\n skill.precedingMessage = message;\n } else {\n validated.unshift({\n type: 'sendMessage',\n idempotencyKey: `factory-stage:${transitionId}`,\n message,\n priority: 'urgent',\n idleBehavior: 'wake',\n // Parking a card says stop: no seat is right by construction, so\n // the notice goes to whichever session is live — or nobody.\n ...(entersWorking && seatRole !== undefined ? { role: seatRole, prepareBinding: true } : {}),\n });\n }\n }\n return {\n outcome: 'accepted' as const,\n intents: {\n accepted: isHumanTransition(request) && acceptsWork(board, fromStage, request.stage),\n },\n decisions: validateFactoryRuleDecisions(validated) as unknown as Record<string, unknown>[],\n };\n })(),\n this.#timeoutMs,\n );\n } catch (error) {\n const failed =\n error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT'\n ? { code: 'timeout' as const, reason: 'Factory rule evaluation timed out.' }\n : ruleFailure(error);\n evaluation = { outcome: 'rejected', ...failed };\n }\n return this.#commit(\n request,\n transitionId,\n evaluation,\n evaluation.outcome === 'accepted'\n ? { ...consentEffect(request, entersWorking, humanMove), ...evaluation.intents }\n : {},\n boards,\n );\n }\n\n async #commitRejection(\n request: FactoryTransitionRequest,\n transitionId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n ): Promise<FactoryTransitionResult> {\n return this.#commit(\n request,\n transitionId,\n { outcome: 'rejected', code, reason: reason.slice(0, MAX_REJECTION_REASON) },\n {},\n undefined,\n );\n }\n\n async #commit(\n request: FactoryTransitionRequest,\n transitionId: string,\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string },\n options: TransitionConsentOptions,\n // The registry the move was evaluated against; rejected moves never release resources.\n boards: BoardRegistry | undefined,\n ): Promise<FactoryTransitionResult> {\n const committed = await this.#storage.commitTransition({\n autonomy: options.autonomy,\n consentedBy: options.consentedBy,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n expectedRevision: request.expectedRevision,\n destinationStage: request.stage,\n actorId: actorId(request.actor),\n ingress: { identity: request.ingress.identity, triggerType: request.ingress.type, transitionId },\n configVersion: this.#configVersion,\n causalChain: [...(request.causalChain ?? [])],\n evaluation,\n });\n if (committed.status === 'missing') {\n return rejection(transitionId, request.workItemId, 'invalid_transition', 'Work item not found.');\n }\n const result = committed.result as unknown as FactoryTransitionResult;\n if (\n this.#onAccepted &&\n options.accepted &&\n committed.status === 'committed' &&\n result.status === 'accepted' &&\n committed.item\n ) {\n const item = committed.item;\n const onAccepted = this.#onAccepted;\n // Invoke inside the chain so a synchronous throw is isolated the same way an async rejection is.\n void Promise.resolve()\n .then(() =>\n onAccepted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n item,\n }),\n )\n .catch(error => {\n console.warn(`[factory] acceptance hook failed for work item ${request.workItemId}:`, error);\n });\n }\n // Only an installed board's declaration releases resources; an unknown board or phase never does.\n if (\n this.#onTerminalStage &&\n result.status === 'accepted' &&\n boards?.get(request.board)?.isTerminal(result.stage) === true\n ) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const cleanup = Promise.resolve(\n this.#onTerminalStage({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n stage: result.stage,\n revision: result.revision,\n actor: request.actor,\n }),\n );\n // A late rejection after the timeout wins the race must not surface\n // as an unhandled rejection.\n cleanup.catch(() => {});\n await Promise.race([\n cleanup,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, this.#terminalCleanupTimeoutMs);\n }),\n ]);\n } catch {\n // Resource release is best-effort — never fail a committed transition.\n } finally {\n clearTimeout(timer);\n }\n }\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;;;;;AAK7B,MAAM,8BAA8B;AAuFpC,SAAS,UACP,cACA,QACA,MACA,QACyB;CACzB,OAAO;EAAE,QAAQ;EAAY;EAAc;EAAQ;EAAM,QAAQ,OAAO,MAAM,GAAG,oBAAoB;CAAE;AACzG;AAEA,SAAS,QAAQ,OAAiC;CAChD,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO,MAAM;EACf,KAAK,SACH,OAAO,SAAS,MAAM;EACxB,KAAK,UACH,OAAO,UAAU,MAAM;EACzB,KAAK,UACH,OAAO,UAAU,MAAM;CAC3B;AACF;AAGA,SAAgB,aAAa,OAAyE;CACpG,MAAM,KAAK,QAAQ,KAAK;CACxB,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO;GAAE,SAAS;GAAI,WAAW;EAAQ;EAC3C,KAAK,SACH,OAAO;GAAE,SAAS;GAAI,WAAW,aAAa,EAAE,IAAI,UAAU;EAAQ;EACxE,SACE,OAAO;GAAE,SAAS;GAAI,WAAW,MAAM;EAAK;CAChD;AACF;AAEA,SAAS,QAAQ,Q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AAQ;IACf,kBAAkB,QAAQ;IAC1B,YAAY,QAAQ;IACpB;GACF,CAAC,CACH,CAAC,CACA,OAAM,UAAS;IACd,QAAQ,KAAK,kDAAkD,QAAQ,WAAW,IAAI,KAAK;GAC7F,CAAC;EACL;EAEA,IACE,KAAK,oBACL,OAAO,WAAW,cAClB,QAAQ,IAAI,QAAQ,KAAK,CAAC,EAAE,WAAW,OAAO,KAAK,MAAM,MACzD;GACA,IAAI;GACJ,IAAI;IACF,MAAM,UAAU,QAAQ,QACtB,KAAK,iBAAiB;KACpB,OAAO,QAAQ;KACf,kBAAkB,QAAQ;KAC1B,YAAY,QAAQ;KACpB,OAAO,OAAO;KACd,UAAU,OAAO;KACjB,OAAO,QAAQ;IACjB,CAAC,CACH;IAGA,QAAQ,YAAY,CAAC,CAAC;IACtB,MAAM,QAAQ,KAAK,CACjB,SACA,IAAI,SAAc,YAAW;KAC3B,QAAQ,WAAW,SAAS,KAAK,yBAAyB;IAC5D,CAAC,CACH,CAAC;GACH,QAAQ,CAER,UAAU;IACR,aAAa,KAAK;GACpB;EACF;EACA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"transition-service.js","names":[],"sources":["../../src/rules/transition-service.ts"],"sourcesContent":["import { DEFAULT_BOARD_ID, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { autoApprovedExitTool, exitToolSucceeded } from '../boards/phase-automation.js';\nimport { phaseRunDecision } from '../boards/phase-runner.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { boardFlow, boardForWorkItem, hasPullRequest, pullRequestCardRejection } from '../boards/semantics.js';\nimport { boardTransitionPolicyResultSchema, immutablePolicySnapshot } from '../boards/transition-policy.js';\nimport type { AuditActorProfileInput, AuditActorType, AuditContext } from '../storage/domains/audit/base.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport { isAgentActor } from '../storage/domains/work-items/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleActor,\n FactoryRuleBoard,\n FactoryRuleCausalEntry,\n FactoryRuleRejectionCode,\n FactoryRuleStage,\n FactoryStageRuleContext,\n FactoryTransitionResult,\n FactoryTransitionResultRejected,\n} from './types.js';\nimport { factoryRuleSourceForWorkItem, workItemSource } from './types.js';\nimport {\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n assertFactoryDecisionTarget,\n validateFactoryRuleDecision,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\nconst MAX_REJECTION_REASON = 512;\n/** Longest a committed transition waits for terminal resource cleanup. Cleanup\n * reattaches remote sandboxes, so a hung provider call must not leave the\n * already-committed transition request pending; past this bound the cleanup\n * keeps running in the background as pure best-effort. */\nconst TERMINAL_CLEANUP_TIMEOUT_MS = 30_000;\n\nexport interface FactoryTransitionRequest {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** Installed board id; the service rejects boards that are not installed. */\n board: string;\n stage: FactoryRuleStage;\n expectedRevision: number;\n actor: FactoryRuleActor;\n actorProfile?: AuditActorProfileInput;\n /** Where a browser request came from; rules and agents carry none. */\n context?: AuditContext;\n ingress: { type: 'human' | 'agent' | 'toolResult' | 'github' | 'rule'; identity: string; transitionId?: string };\n cause: string;\n causalChain?: readonly FactoryRuleCausalEntry[];\n /** Internal materialization path: start the destination phase's runner even when already at that stage. */\n initialEntry?: boolean;\n /** Starts the stage's runner again when the item already holds that stage, to restart work the entry invalidated. */\n reenter?: boolean;\n /** Internal proof that this move consumes an approved `submit_plan` result. */\n planApproved?: true;\n /** Internal: the tool whose successful result this move consumes (a tool-result rule's move). */\n completedTool?: string;\n /**\n * Internal: an intake route moves the card on a status event. A route is admin-authored, so it\n * may name any phase on the card's board regardless of the board's next phases, working ones\n * included. The phase's `autoStart` and the dispatcher's approval check decide whether its run starts.\n */\n eventRoute?: { routeId: string };\n}\n\nexport interface FactoryTransitionServiceOptions {\n configVersion: string;\n storage: WorkItemsStorage;\n /** A fixed registry, or the per-project boards; each transition loads its project's boards. */\n boards?: BoardRegistry | ProjectBoardSource;\n /** Every commit, accepted or rejected, lands here as `stage_moved` / `transition_rejected` under the request's actor. */\n audit?: AuditRecorder;\n timeoutMs?: number;\n /**\n * Called after a transition commits into a phase the board declares\n * terminal — the point where the item's sessions stop receiving runs, so\n * resources they hold (e.g. sandboxes) can be released for reuse. Awaited,\n * but failures are swallowed: releasing resources must never break or roll\n * back the committed transition.\n */\n onTerminalStage?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n stage: FactoryRuleStage;\n revision: number;\n /** The actor that committed this terminal transition. Lets cleanup leave\n * the seat that drove its own transition (an agent tool call) untouched. */\n actor: FactoryRuleActor;\n }) => Promise<void> | void;\n /**\n * Called after a transition commits a stage change, e.g. to tell the item's\n * followers. Not awaited, and failures are logged: a notification must never\n * fail or delay the committed transition.\n */\n onTransitionCommitted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n fromStage: string | undefined;\n toStage: string;\n }) => Promise<void> | void;\n /**\n * Called after a transition commits out of the last phase that runs in a\n * context: the new phase runs in another context (or none) and is not\n * terminal, e.g. Triage → Planning. The context's session gets no more\n * runs until the card comes back, so its sandbox can stop. Awaited under\n * the same bound as `onTerminalStage`, and failures are swallowed.\n */\n onContextLeft?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** The context the card left. */\n context: string;\n /** The context the new phase runs in, if it runs one. */\n toContext: string | undefined;\n revision: number;\n actor: FactoryRuleActor;\n }) => Promise<void> | void;\n /** Upper bound on how long a committed transition waits for\n * `onTerminalStage` or `onContextLeft` before returning (default 30s). The\n * cleanup continues in the background past the bound. */\n terminalCleanupTimeoutMs?: number;\n /**\n * Called after a person moves a Work card from Intake or Triage into Planning or\n * Building, which approves the work. Fire-and-forget: failures are swallowed, the committed transition never\n * depends on it.\n */\n onAccepted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n item: Card;\n }) => Promise<void> | void;\n}\n\nfunction rejection(\n transitionId: string,\n itemId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n): FactoryTransitionResult {\n return { status: 'rejected', transitionId, itemId, code, reason: reason.slice(0, MAX_REJECTION_REASON) };\n}\n\nfunction actorId(actor: FactoryRuleActor): string {\n switch (actor.type) {\n case 'human':\n case 'system':\n return actor.id;\n case 'agent':\n return `agent:${actor.bindingId}`;\n case 'github':\n return `github:${actor.login}`;\n case 'gitlab':\n return `gitlab:${actor.username}`;\n }\n}\n\n// The dispatcher executes an agent-approved decision as a human actor so its consent carries; the trail still names the agent.\nexport function auditActorOf(actor: FactoryRuleActor): { actorId: string; actorType: AuditActorType } {\n const id = actorId(actor);\n switch (actor.type) {\n case 'github':\n case 'gitlab':\n return { actorId: id, actorType: 'human' };\n case 'human':\n return { actorId: id, actorType: isAgentActor(id) ? 'agent' : 'human' };\n default:\n return { actorId: id, actorType: actor.type };\n }\n}\n\nfunction isStale(result: FactoryTransitionResult): result is FactoryTransitionResultRejected {\n return result.status === 'rejected' && result.code === 'stale';\n}\n\n/** Tell the caller where the card is now, so a model doesn't read \"stale\" as \"already moved\". */\nfunction staleRejection(result: FactoryTransitionResultRejected, current: Card): FactoryTransitionResult {\n const stage = currentStage(current.stages) ?? current.stages.join(', ');\n return rejection(\n result.transitionId,\n result.itemId,\n 'stale',\n `The card changed (now revision ${current.revision}, in ${stage}). Retry with expectedRevision ${current.revision} if the move still applies.`,\n );\n}\n\nexport function currentStage(stages: readonly string[]): FactoryRuleStage | undefined {\n return stages.length === 1 ? stages[0] : undefined;\n}\n\ninterface TransitionConsentOptions {\n autonomy?: 'arm' | 'disarm';\n consentedBy?: string;\n /** A person moved a card into its board's build seat from before it (see {@link acceptsWork}): that move approves the work. */\n accepted?: boolean;\n}\n\n/**\n * Whether moving a card from `from` to `to` hands it to the board's builder for the first time: `to`\n * runs in the seat of the board's build phase ({@link boardFlow}), and `from` is a resting phase or a\n * working phase of another seat that is no review (Work: Intake or Triage into Planning or Building).\n */\nfunction acceptsWork(board: InstalledBoard, from: string, to: string): boolean {\n const buildRole = boardFlow(board).buildRole;\n if (!buildRole || board.roleForPhase(to) !== buildRole) return false;\n const fromPhase = board.phases[from];\n if (!fromPhase || fromPhase.kind === 'terminal') return false;\n if (fromPhase.kind === 'resting') return true;\n const fromRole = fromPhase.runner.context;\n return fromRole !== buildRole && fromRole !== REVIEW_CONTEXT;\n}\n\n// Entering a resting lane disarms whoever rests it; only a person's move into a working lane arms.\nfunction transitionConsent(working: boolean, humanMove: boolean): 'arm' | 'disarm' | undefined {\n if (!working) return 'disarm';\n return humanMove ? 'arm' : undefined;\n}\n\n// An event arriving as data (GitHub, sweeps) never pre-approves the runs its transition queues.\nfunction bearsConsent(actor: FactoryRuleActor): boolean {\n return actor.type === 'human' || actor.type === 'agent';\n}\n\n// Rides the transition's own revision-checked commit, so a stale or rejected commit flips nothing.\nfunction consentEffect(\n request: FactoryTransitionRequest,\n working: boolean,\n humanMove: boolean,\n): TransitionConsentOptions {\n // A provider event (a reopen, a close) is not a person's say-so: whatever a person armed before\n // no longer stands once a route moves the card.\n if (request.eventRoute) return { autonomy: 'disarm' };\n const autonomy = transitionConsent(working, humanMove);\n return bearsConsent(request.actor) ? { autonomy, consentedBy: actorId(request.actor) } : { autonomy };\n}\n\ntype RunStartDecision = Extract<FactoryCommitDecision, { type: 'invokeSkill' | 'sendMessage' }>;\n\nfunction startsRun(decision: FactoryCommitDecision): decision is RunStartDecision {\n return decision.type === 'invokeSkill' || (decision.type === 'sendMessage' && decision.prepareBinding === true);\n}\n\n// Answering a recorded run start, or the role's own mid-run agent, with a run would start a second one.\n// A run that starts after its own agent's move is queued onto that agent's run instead.\nfunction runAlreadyUnderway(request: FactoryTransitionRequest, decision: RunStartDecision): boolean {\n if (request.cause === 'run_start') return true;\n if (decision.type === 'invokeSkill' && decision.startsAfterOwnMove === true) return false;\n return request.actor.type === 'agent' && request.actor.role === decision.role;\n}\n\nfunction stageTransitionMessage(fromStage: FactoryRuleStage, toStage: FactoryRuleStage): string {\n return `This work was moved from the ${fromStage} stage to the ${toStage} stage.`;\n}\n\nfunction isHumanTransition(request: FactoryTransitionRequest): boolean {\n return request.actor.type === 'human' && request.ingress.type === 'human';\n}\n\nfunction ruleFailure(error: unknown): { code: FactoryRuleRejectionCode; reason: string } {\n return {\n code: 'rule_error',\n reason: error instanceof Error ? `Factory rule failed: ${error.message}` : 'Factory rule failed.',\n };\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), timeoutMs);\n });\n try {\n return await Promise.race([operation, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nexport class FactoryTransitionService {\n readonly #configVersion: string;\n readonly #boards: ProjectBoardSource;\n readonly #storage: WorkItemsStorage;\n readonly #timeoutMs: number;\n readonly #onTerminalStage: FactoryTransitionServiceOptions['onTerminalStage'];\n readonly #onContextLeft: FactoryTransitionServiceOptions['onContextLeft'];\n readonly #terminalCleanupTimeoutMs: number;\n readonly #onAccepted: FactoryTransitionServiceOptions['onAccepted'];\n readonly #onTransitionCommitted: FactoryTransitionServiceOptions['onTransitionCommitted'];\n readonly #audit: AuditRecorder | undefined;\n\n constructor(options: FactoryTransitionServiceOptions) {\n this.#configVersion = options.configVersion;\n this.#boards = toBoardSource(options.boards);\n this.#storage = options.storage;\n this.#audit = options.audit;\n this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;\n this.#onTerminalStage = options.onTerminalStage;\n this.#onContextLeft = options.onContextLeft;\n this.#onAccepted = options.onAccepted;\n this.#onTransitionCommitted = options.onTransitionCommitted;\n this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;\n }\n\n get configVersion(): string {\n return this.#configVersion;\n }\n\n async transition(request: FactoryTransitionRequest): Promise<FactoryTransitionResult> {\n const replay = await this.#storage.getTransitionResultByIngress(\n request.orgId,\n request.factoryProjectId,\n request.ingress.identity,\n );\n if (replay) return replay as unknown as FactoryTransitionResult;\n\n const transitionId = request.ingress.transitionId ?? globalThis.crypto.randomUUID();\n const item = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (!item) {\n const rejection = await this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'Work item not found.',\n );\n await this.#recordTransition(request, undefined, rejection);\n return rejection;\n }\n let result = await this.#evaluateAndCommit(request, transitionId, item);\n if (isStale(result)) {\n const current = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (current) result = staleRejection(result, current);\n }\n await this.#recordTransition(request, item, result);\n this.#notifyCommitted(request, item, result);\n return result;\n }\n\n #notifyCommitted(request: FactoryTransitionRequest, item: Card, result: FactoryTransitionResult): void {\n const onTransitionCommitted = this.#onTransitionCommitted;\n if (!onTransitionCommitted || result.status !== 'accepted') return;\n // Board-neutral: `currentStage` only knows the built-in rule stages.\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (result.stage === fromStage) return;\n // Inside the chain so a synchronous throw is isolated the same way an async rejection is.\n void Promise.resolve()\n .then(() =>\n onTransitionCommitted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: item.id,\n fromStage,\n toStage: result.stage,\n }),\n )\n .catch(error => {\n console.warn(`[factory] stage notification failed for work item ${item.id}:`, error);\n });\n }\n\n /** A rejection can outlive its work item: the row still names the id the caller asked for. */\n async #recordTransition(\n request: FactoryTransitionRequest,\n item: Card | undefined,\n result: FactoryTransitionResult,\n ): Promise<void> {\n if (!this.#audit) return;\n // Board-neutral, like the stage notification: `currentStage` only knows the\n // built-in rule stages and would drop custom-board phases.\n const from = item && item.stages.length === 1 ? item.stages[0] : undefined;\n if (result.status === 'accepted' && result.stage === from && !request.reenter) return;\n const outcome =\n result.status === 'accepted'\n ? { action: 'factory.work_item.stage_moved' as const, to: result.stage, revision: result.revision }\n : {\n action: 'factory.work_item.transition_rejected' as const,\n to: request.stage,\n code: result.code,\n reason: result.reason,\n };\n const { action, ...detail } = outcome;\n await this.#audit\n .record({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n ...auditActorOf(request.actor),\n actorProfile: request.actorProfile,\n ...(request.context ? { context: request.context } : {}),\n action,\n idempotencyKey: result.transitionId,\n targets: [{ type: 'work_item', id: item?.id ?? request.workItemId, ...(item ? { name: item.title } : {}) }],\n metadata: {\n transitionId: result.transitionId,\n ingressType: request.ingress.type,\n cause: request.cause,\n configVersion: this.#configVersion,\n ...(from ? { from } : {}),\n ...(request.reenter ? { reenter: true } : {}),\n ...detail,\n },\n })\n .catch(error => {\n console.warn(`[factory] audit failed for transition ${result.transitionId}:`, error);\n });\n }\n\n async #evaluateAndCommit(\n request: FactoryTransitionRequest,\n transitionId: string,\n item: Card,\n ): Promise<FactoryTransitionResult> {\n const boards = await this.#boards.load(request);\n if (request.causalChain && request.causalChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n return this.#commitRejection(\n request,\n transitionId,\n 'causal_depth_exceeded',\n 'Factory rule causal depth exceeded.',\n );\n }\n const itemSource = workItemSource(item.externalSource);\n const source = factoryRuleSourceForWorkItem(itemSource);\n const isPullRequest = source === 'pullRequest' || source === 'gitlabPullRequest';\n // Rows filed before boards were persisted belong to the default board.\n if (item.board === null && !boards.has(DEFAULT_BOARD_ID)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'This legacy work item has no assigned board. Assign an installed board and phase through the work-item PATCH endpoint before transitioning it.',\n );\n }\n const itemBoard = boardForWorkItem(item);\n if (request.board !== itemBoard) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The work item belongs to board \"${itemBoard}\", not \"${request.board}\".`,\n );\n }\n const board = boards.get(request.board);\n if (!board) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `Board \"${request.board}\" is not installed.`,\n );\n }\n const fromStage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!fromStage || !Object.prototype.hasOwnProperty.call(board.phases, fromStage)) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not have one canonical phase on the requested board.',\n );\n }\n // The board's own reason comes first: its phase graph alone only says the move is not\n // declared, which leaves an agent moving an issue card to PR review guessing why.\n const cardShapeRejection = pullRequestCardRejection(\n board,\n {\n standalonePullRequest: isPullRequest,\n hasPullRequest: hasPullRequest({ workItem: item.workItem, source: itemSource }),\n },\n request.stage,\n );\n if (cardShapeRejection) {\n return this.#commitRejection(request, transitionId, 'invalid_transition', cardShapeRejection);\n }\n if (\n !Object.prototype.hasOwnProperty.call(board.phases, request.stage) ||\n (!request.eventRoute && !board.allowsTransition(fromStage, request.stage))\n ) {\n const nextStages = [...new Set((board.transitions[fromStage] ?? []).map(transition => transition.to))];\n const nextStagesReason =\n nextStages.length > 0\n ? `Next stages declared from ${fromStage}: ${nextStages.join(', ')}.`\n : `No next stage is declared from ${fromStage}.`;\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n `The ${board.name} board does not allow moving from ${fromStage} to ${request.stage}. ${nextStagesReason}`,\n );\n }\n\n // The coordinator's own self-move at run start would otherwise inject a second run's kickoff.\n const humanMove = request.actor.type === 'human' && fromStage !== request.stage && request.cause !== 'run_start';\n // The board, not the phase name, says whether a seat is engaged on either side of this move.\n const entersWorking = board.isWorking(request.stage);\n const seatRole = board.roleForPhase(request.stage);\n\n const contextBase = {\n tenant: { orgId: request.orgId, projectId: request.factoryProjectId },\n actor: request.actor,\n ingress: { type: request.ingress.type, id: request.ingress.identity },\n cause: request.cause,\n causalChain: request.causalChain ?? [],\n configVersion: this.#configVersion,\n item: {\n id: item.id,\n source: itemSource,\n sourceKey: item.externalSource\n ? `${item.externalSource.integrationId}:${item.externalSource.type}:${item.externalSource.externalId}`\n : null,\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: [...item.stages],\n workItem: item.workItem,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board: request.board,\n itemRevision: item.revision,\n source,\n fromStage,\n toStage: request.stage,\n } satisfies Omit<FactoryStageRuleContext, 'stage'>;\n\n let evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[]; intents: TransitionConsentOptions }\n | { outcome: 'rejected'; code: string; reason: string };\n try {\n evaluation = await withRuleTimeout(\n (async () => {\n // Plans are approved without a person only where the card's phase auto-approves submit_plan.\n const plansAutoApproved = autoApprovedExitTool(boards, item) === 'submit_plan';\n // A phase with an exit tool holds the card until the tool succeeds (for submit_plan, with\n // an approved plan; autoApprove only decides whether it approves itself). Then the agent,\n // or the board's own rule for the tool, moves the card. A person can move it any time.\n const fromPhase = board.phases[fromStage];\n const exitTool = fromPhase?.kind === 'working' ? fromPhase.exitTool : undefined;\n if (\n request.actor.type !== 'human' &&\n !request.eventRoute &&\n exitTool &&\n fromStage !== request.stage &&\n entersWorking &&\n !(exitTool.id === 'submit_plan' ? request.planApproved === true : request.completedTool === exitTool.id) &&\n !exitToolSucceeded(item, fromStage, exitTool.id)\n ) {\n return {\n outcome: 'rejected' as const,\n code: 'approval_required',\n reason:\n exitTool.id === 'submit_plan'\n ? `${fromPhase!.name} ends when submit_plan comes back with an approved plan; until then the card stays here. Call submit_plan and wait for a person to approve the plan (or for it to be approved automatically), then move the card into ${board.phases[request.stage]?.name ?? request.stage} with factory_transition_work_item.`\n : `${fromPhase!.name} ends when ${exitTool.id} succeeds; until then the card stays here. A person can also move it from the Factory board or a chat they are signed in to.`,\n };\n }\n const policy = boardTransitionPolicyResultSchema.parse(\n await board.transitionPolicy?.(\n immutablePolicySnapshot({\n ...contextBase,\n item: { ...contextBase.item, triageType: item.triageType },\n initialEntry: request.initialEntry ?? false,\n reenter: request.reenter ?? false,\n isHumanTransition: isHumanTransition(request),\n plansAutoApproved,\n planApproved: request.planApproved === true,\n requestedTriageType: undefined,\n }),\n ),\n );\n if (policy?.type === 'reject') {\n return { outcome: 'rejected' as const, code: policy.code, reason: policy.reason };\n }\n const run = phaseRunDecision(board, request.stage, contextBase, {\n initialEntry: request.initialEntry,\n reenter: request.reenter,\n });\n const validated = validateFactoryRuleDecisions(run ? [run] : [], contextBase.causalChain.length).filter(\n decision => {\n assertFactoryDecisionTarget(decision, boards, itemBoard);\n return !(startsRun(decision) && runAlreadyUnderway(request, decision));\n },\n );\n if (humanMove) {\n const message = stageTransitionMessage(fromStage, request.stage);\n const skill = validated.find(decision => decision.type === 'invokeSkill');\n if (skill) {\n skill.precedingMessage = message;\n } else {\n validated.unshift({\n type: 'sendMessage',\n idempotencyKey: `factory-stage:${transitionId}`,\n message,\n priority: 'urgent',\n idleBehavior: 'wake',\n // Parking a card says stop: no seat is right by construction, so\n // the notice goes to whichever session is live — or nobody.\n ...(entersWorking && seatRole !== undefined ? { role: seatRole, prepareBinding: true } : {}),\n });\n }\n }\n return {\n outcome: 'accepted' as const,\n intents: {\n accepted: isHumanTransition(request) && acceptsWork(board, fromStage, request.stage),\n },\n decisions: validateFactoryRuleDecisions(validated) as unknown as Record<string, unknown>[],\n };\n })(),\n this.#timeoutMs,\n );\n } catch (error) {\n const failed =\n error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT'\n ? { code: 'timeout' as const, reason: 'Factory rule evaluation timed out.' }\n : ruleFailure(error);\n evaluation = { outcome: 'rejected', ...failed };\n }\n return this.#commit(\n request,\n transitionId,\n evaluation,\n evaluation.outcome === 'accepted'\n ? { ...consentEffect(request, entersWorking, humanMove), ...evaluation.intents }\n : {},\n boards,\n fromStage,\n );\n }\n\n async #commitRejection(\n request: FactoryTransitionRequest,\n transitionId: string,\n code: FactoryRuleRejectionCode,\n reason: string,\n ): Promise<FactoryTransitionResult> {\n return this.#commit(\n request,\n transitionId,\n { outcome: 'rejected', code, reason: reason.slice(0, MAX_REJECTION_REASON) },\n {},\n undefined,\n );\n }\n\n async #commit(\n request: FactoryTransitionRequest,\n transitionId: string,\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string },\n options: TransitionConsentOptions,\n // The registry the move was evaluated against; rejected moves never release resources.\n boards: BoardRegistry | undefined,\n fromStage?: string,\n ): Promise<FactoryTransitionResult> {\n const committed = await this.#storage.commitTransition({\n autonomy: options.autonomy,\n consentedBy: options.consentedBy,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n expectedRevision: request.expectedRevision,\n destinationStage: request.stage,\n actorId: actorId(request.actor),\n ingress: { identity: request.ingress.identity, triggerType: request.ingress.type, transitionId },\n configVersion: this.#configVersion,\n causalChain: [...(request.causalChain ?? [])],\n evaluation,\n });\n if (committed.status === 'missing') {\n return rejection(transitionId, request.workItemId, 'invalid_transition', 'Work item not found.');\n }\n const result = committed.result as unknown as FactoryTransitionResult;\n if (\n this.#onAccepted &&\n options.accepted &&\n committed.status === 'committed' &&\n result.status === 'accepted' &&\n committed.item\n ) {\n const item = committed.item;\n const onAccepted = this.#onAccepted;\n // Invoke inside the chain so a synchronous throw is isolated the same way an async rejection is.\n void Promise.resolve()\n .then(() =>\n onAccepted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n item,\n }),\n )\n .catch(error => {\n console.warn(`[factory] acceptance hook failed for work item ${request.workItemId}:`, error);\n });\n }\n // Only an installed board's declaration releases resources; an unknown board or phase never does.\n const board = result.status === 'accepted' ? boards?.get(request.board) : undefined;\n if (board && result.status === 'accepted') {\n const hooks = {\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n revision: result.revision,\n actor: request.actor,\n };\n if (board.isTerminal(result.stage)) {\n const onTerminalStage = this.#onTerminalStage;\n if (onTerminalStage) await this.#bounded(() => onTerminalStage({ ...hooks, stage: result.stage }));\n } else if (fromStage !== undefined && this.#onContextLeft) {\n const context = board.roleForPhase(fromStage);\n const toContext = board.roleForPhase(result.stage);\n const onContextLeft = this.#onContextLeft;\n if (context !== undefined && context !== toContext) {\n await this.#bounded(() => onContextLeft({ ...hooks, context, toContext }));\n }\n }\n }\n return result;\n }\n\n /** Run a resource-release hook, waiting at most the cleanup bound; it never fails the committed transition. */\n async #bounded(release: () => Promise<void> | void): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const cleanup = Promise.resolve().then(release);\n // A late rejection after the timeout wins the race must not surface\n // as an unhandled rejection.\n cleanup.catch(() => {});\n await Promise.race([\n cleanup,\n new Promise<void>(resolve => {\n timer = setTimeout(resolve, this.#terminalCleanupTimeoutMs);\n }),\n ]);\n } catch {\n // Resource release is best-effort — never fail a committed transition.\n } finally {\n clearTimeout(timer);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;;;;;AAK7B,MAAM,8BAA8B;AAyGpC,SAAS,UACP,cACA,QACA,MACA,QACyB;CACzB,OAAO;EAAE,QAAQ;EAAY;EAAc;EAAQ;EAAM,QAAQ,OAAO,MAAM,GAAG,oBAAoB;CAAE;AACzG;AAEA,SAAS,QAAQ,OAAiC;CAChD,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO,MAAM;EACf,KAAK,SACH,OAAO,SAAS,MAAM;EACxB,KAAK,UACH,OAAO,UAAU,MAAM;EACzB,KAAK,UACH,OAAO,UAAU,MAAM;CAC3B;AACF;AAGA,SAAgB,aAAa,OAAyE;CACpG,MAAM,KAAK,QAAQ,KAAK;CACxB,QAAQ,MAAM,MAAd;EACE,KAAK;EACL,KAAK,UACH,OAAO;GAAE,SAAS;GAAI,WAAW;EAAQ;EAC3C,KAAK,SACH,OAAO;GAAE,SAAS;GAAI,WAAW,aAAa,EAAE,IAAI,UAAU;EAAQ;EACx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AC;EACH,QAAQ,CAER,UAAU;GACR,aAAa,KAAK;EACpB;CACF;AACF"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { AgentControllerEvent } from '@mastra/core/agent-controller';
|
|
2
|
+
import type { ProjectBoardSource } from '../boards/project-boards.js';
|
|
3
|
+
import type { BoardRegistry } from '../boards/registry.js';
|
|
4
|
+
import type { SourceControlSessionLookup } from '../session/factory-session.js';
|
|
5
|
+
import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
6
|
+
import type { SessionRetirementCoordinator } from './session-retirement.js';
|
|
7
|
+
type WarningLogger = (message: string, details: Record<string, unknown>) => void;
|
|
8
|
+
export interface ContextSandboxStopsOptions {
|
|
9
|
+
workItems: Pick<WorkItemsStorage, 'get'>;
|
|
10
|
+
boards: BoardRegistry | ProjectBoardSource;
|
|
11
|
+
sessions: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;
|
|
12
|
+
retirement: Pick<SessionRetirementCoordinator, 'stopSessionSandbox'>;
|
|
13
|
+
/**
|
|
14
|
+
* The run in flight on the session in this process, with a promise that
|
|
15
|
+
* settles when it ends, or `null` when none is. A run holds its sandbox until it ends: the agent whose own
|
|
16
|
+
* tool call left the context is still returning from it, and a person may
|
|
17
|
+
* be mid-conversation in the session.
|
|
18
|
+
*/
|
|
19
|
+
runInFlight: (sessionId: string) => Promise<{
|
|
20
|
+
ended: Promise<void>;
|
|
21
|
+
} | null>;
|
|
22
|
+
warn?: WarningLogger;
|
|
23
|
+
}
|
|
24
|
+
export interface ContextLeftArgs {
|
|
25
|
+
orgId: string;
|
|
26
|
+
factoryProjectId: string;
|
|
27
|
+
workItemId: string;
|
|
28
|
+
/** The context the card left. */
|
|
29
|
+
context: string;
|
|
30
|
+
/** Revision the move committed at. */
|
|
31
|
+
revision: number;
|
|
32
|
+
}
|
|
33
|
+
/** What the run-in-flight check reads from a controller session. */
|
|
34
|
+
export interface RunWatchSession {
|
|
35
|
+
readonly stream: {
|
|
36
|
+
isActive(): boolean;
|
|
37
|
+
};
|
|
38
|
+
subscribe(listener: (event: AgentControllerEvent) => void): () => void;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The run in flight on a session this process holds, ending at its
|
|
42
|
+
* `agent_end`. Subscribes before reading `isActive()`, so a run that ends in
|
|
43
|
+
* between still settles `ended`.
|
|
44
|
+
*/
|
|
45
|
+
export declare function controllerRunInFlight(getSession: (sessionId: string) => Promise<RunWatchSession | undefined>): ContextSandboxStopsOptions['runInFlight'];
|
|
46
|
+
/**
|
|
47
|
+
* Stop the sandbox of the context a card just left (Triage → Planning stops
|
|
48
|
+
* the triage session's sandbox). The session row, its files and its refs
|
|
49
|
+
* stay, so a card that comes back resumes the same sandbox.
|
|
50
|
+
*
|
|
51
|
+
* A session with a run in flight is stopped when that run ends; the run is
|
|
52
|
+
* not awaited here, since it may be the very tool call waiting on this
|
|
53
|
+
* transition. Best-effort throughout: failures are logged, never thrown.
|
|
54
|
+
*/
|
|
55
|
+
export declare function createContextSandboxStops(options: ContextSandboxStopsOptions): (args: ContextLeftArgs) => Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Retire every session a finished card holds: each sandbox is stopped, not
|
|
58
|
+
* destroyed, by identity when this process never attached to it, so a card
|
|
59
|
+
* finished on another replica still stops its sandboxes.
|
|
60
|
+
*/
|
|
61
|
+
export declare function createTerminalSandboxStops(options: {
|
|
62
|
+
workItems: Pick<WorkItemsStorage, 'get'>;
|
|
63
|
+
sessions: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;
|
|
64
|
+
retirement: Pick<SessionRetirementCoordinator, 'retireSession'>;
|
|
65
|
+
}): ({ orgId, workItemId }: {
|
|
66
|
+
orgId: string;
|
|
67
|
+
workItemId: string;
|
|
68
|
+
}) => Promise<void>;
|
|
69
|
+
export {};
|
|
70
|
+
//# sourceMappingURL=context-sandboxes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-sandbox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pE,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,EAAE;QAAE,QAAQ,IAAI,OAAO,CAAA;KAAE,CAAC;IACzC,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,UAAU,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,GACtE,0BAA0B,CAAC,aAAa,CAAC,CAgB3C;AAMD;;;;;;;;GAQG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,0BAA0B,UAwBvD,eAAe,KAAG,OAAO,CAAC,IAAI,CAAC,CAqBpD;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE;IAClD,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,KAAK,CAAC,CAAC;IACzC,QAAQ,EAAE,IAAI,CAAC,0BAA0B,EAAE,6BAA6B,CAAC,CAAC;IAC1E,UAAU,EAAE,IAAI,CAAC,4BAA4B,EAAE,eAAe,CAAC,CAAC;CACjE,2BACsC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,KAAG,OAAO,CAAC,IAAI,CAAC,CAY3F"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { toBoardSource } from "../boards/project-boards.js";
|
|
2
|
+
import { boardForWorkItem } from "../boards/semantics.js";
|
|
3
|
+
// src/sandbox/context-sandboxes.ts
|
|
4
|
+
/**
|
|
5
|
+
* The run in flight on a session this process holds, ending at its
|
|
6
|
+
* `agent_end`. Subscribes before reading `isActive()`, so a run that ends in
|
|
7
|
+
* between still settles `ended`.
|
|
8
|
+
*/
|
|
9
|
+
function controllerRunInFlight(getSession) {
|
|
10
|
+
return async (sessionId) => {
|
|
11
|
+
const session = await getSession(sessionId);
|
|
12
|
+
if (!session) return null;
|
|
13
|
+
let unsubscribe = () => {};
|
|
14
|
+
const ended = new Promise((resolve) => {
|
|
15
|
+
unsubscribe = session.subscribe((event) => {
|
|
16
|
+
if (event.type === "agent_end") resolve();
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
if (!session.stream.isActive()) {
|
|
20
|
+
unsubscribe();
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
return { ended: ended.finally(unsubscribe) };
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function sessionIdOf(item, context) {
|
|
27
|
+
return item.sessions[context]?.sessionId;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Stop the sandbox of the context a card just left (Triage → Planning stops
|
|
31
|
+
* the triage session's sandbox). The session row, its files and its refs
|
|
32
|
+
* stay, so a card that comes back resumes the same sandbox.
|
|
33
|
+
*
|
|
34
|
+
* A session with a run in flight is stopped when that run ends; the run is
|
|
35
|
+
* not awaited here, since it may be the very tool call waiting on this
|
|
36
|
+
* transition. Best-effort throughout: failures are logged, never thrown.
|
|
37
|
+
*/
|
|
38
|
+
function createContextSandboxStops(options) {
|
|
39
|
+
const warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));
|
|
40
|
+
const boards = toBoardSource(options.boards);
|
|
41
|
+
/** The left context's session, unless the card is back in that context or holds the session under its new one. */
|
|
42
|
+
const leftSession = async (args, expectedRevision) => {
|
|
43
|
+
const item = await options.workItems.get({
|
|
44
|
+
orgId: args.orgId,
|
|
45
|
+
id: args.workItemId
|
|
46
|
+
});
|
|
47
|
+
if (!item) return void 0;
|
|
48
|
+
if (expectedRevision !== void 0 && item.revision !== expectedRevision) return void 0;
|
|
49
|
+
const sessionId = sessionIdOf(item, args.context);
|
|
50
|
+
if (!sessionId) return void 0;
|
|
51
|
+
const stage = item.stages.length === 1 ? item.stages[0] : void 0;
|
|
52
|
+
const registry = await boards.load({
|
|
53
|
+
orgId: args.orgId,
|
|
54
|
+
factoryProjectId: args.factoryProjectId
|
|
55
|
+
});
|
|
56
|
+
const current = stage === void 0 ? void 0 : registry.get(boardForWorkItem(item))?.roleForPhase(stage);
|
|
57
|
+
if (current !== void 0 && sessionIdOf(item, current) === sessionId) return void 0;
|
|
58
|
+
return sessionId;
|
|
59
|
+
};
|
|
60
|
+
const stop = async (args, sessionId) => {
|
|
61
|
+
const sourceControl = await options.sessions.getSourceControlBySessionId(sessionId);
|
|
62
|
+
if (!sourceControl) return;
|
|
63
|
+
await options.retirement.stopSessionSandbox({
|
|
64
|
+
sourceControl,
|
|
65
|
+
orgId: args.orgId,
|
|
66
|
+
sessionId
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
return async (args) => {
|
|
70
|
+
try {
|
|
71
|
+
const sessionId = await leftSession(args, args.revision);
|
|
72
|
+
if (!sessionId) return;
|
|
73
|
+
const run = await options.runInFlight(sessionId);
|
|
74
|
+
if (!run) {
|
|
75
|
+
await stop(args, sessionId);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
run.ended.then(async () => {
|
|
79
|
+
if (await leftSession(args) === sessionId) await stop(args, sessionId);
|
|
80
|
+
}).catch((error) => warn("Factory context sandbox stop failed", {
|
|
81
|
+
...args,
|
|
82
|
+
sessionId,
|
|
83
|
+
error: String(error)
|
|
84
|
+
}));
|
|
85
|
+
} catch (error) {
|
|
86
|
+
warn("Factory context sandbox stop failed", {
|
|
87
|
+
...args,
|
|
88
|
+
error: String(error)
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Retire every session a finished card holds: each sandbox is stopped, not
|
|
95
|
+
* destroyed, by identity when this process never attached to it, so a card
|
|
96
|
+
* finished on another replica still stops its sandboxes.
|
|
97
|
+
*/
|
|
98
|
+
function createTerminalSandboxStops(options) {
|
|
99
|
+
return async ({ orgId, workItemId }) => {
|
|
100
|
+
const item = await options.workItems.get({
|
|
101
|
+
orgId,
|
|
102
|
+
id: workItemId
|
|
103
|
+
});
|
|
104
|
+
if (!item) return;
|
|
105
|
+
const sessionIds = [...new Set(Object.values(item.sessions).map((session) => session.sessionId))];
|
|
106
|
+
await Promise.all(sessionIds.map(async (sessionId) => {
|
|
107
|
+
const sourceControl = await options.sessions.getSourceControlBySessionId(sessionId);
|
|
108
|
+
if (!sourceControl) return;
|
|
109
|
+
await options.retirement.retireSession({
|
|
110
|
+
sourceControl,
|
|
111
|
+
orgId,
|
|
112
|
+
sessionId,
|
|
113
|
+
deleteSession: false
|
|
114
|
+
});
|
|
115
|
+
}));
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
export { controllerRunInFlight, createContextSandboxStops, createTerminalSandboxStops };
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=context-sandboxes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-sandboxes.js","names":[],"sources":["../../src/sandbox/context-sandboxes.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport { boardForWorkItem } from '../boards/semantics.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { SessionRetirementCoordinator } from './session-retirement.js';\n\ntype WarningLogger = (message: string, details: Record<string, unknown>) => void;\n\nexport interface ContextSandboxStopsOptions {\n workItems: Pick<WorkItemsStorage, 'get'>;\n boards: BoardRegistry | ProjectBoardSource;\n sessions: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;\n retirement: Pick<SessionRetirementCoordinator, 'stopSessionSandbox'>;\n /**\n * The run in flight on the session in this process, with a promise that\n * settles when it ends, or `null` when none is. A run holds its sandbox until it ends: the agent whose own\n * tool call left the context is still returning from it, and a person may\n * be mid-conversation in the session.\n */\n runInFlight: (sessionId: string) => Promise<{ ended: Promise<void> } | null>;\n warn?: WarningLogger;\n}\n\nexport interface ContextLeftArgs {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n /** The context the card left. */\n context: string;\n /** Revision the move committed at. */\n revision: number;\n}\n\n/** What the run-in-flight check reads from a controller session. */\nexport interface RunWatchSession {\n readonly stream: { isActive(): boolean };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\n/**\n * The run in flight on a session this process holds, ending at its\n * `agent_end`. Subscribes before reading `isActive()`, so a run that ends in\n * between still settles `ended`.\n */\nexport function controllerRunInFlight(\n getSession: (sessionId: string) => Promise<RunWatchSession | undefined>,\n): ContextSandboxStopsOptions['runInFlight'] {\n return async sessionId => {\n const session = await getSession(sessionId);\n if (!session) return null;\n let unsubscribe = () => {};\n const ended = new Promise<void>(resolve => {\n unsubscribe = session.subscribe(event => {\n if (event.type === 'agent_end') resolve();\n });\n });\n if (!session.stream.isActive()) {\n unsubscribe();\n return null;\n }\n return { ended: ended.finally(unsubscribe) };\n };\n}\n\nfunction sessionIdOf(item: Card, context: string): string | undefined {\n return item.sessions[context]?.sessionId;\n}\n\n/**\n * Stop the sandbox of the context a card just left (Triage → Planning stops\n * the triage session's sandbox). The session row, its files and its refs\n * stay, so a card that comes back resumes the same sandbox.\n *\n * A session with a run in flight is stopped when that run ends; the run is\n * not awaited here, since it may be the very tool call waiting on this\n * transition. Best-effort throughout: failures are logged, never thrown.\n */\nexport function createContextSandboxStops(options: ContextSandboxStopsOptions) {\n const warn = options.warn ?? ((message, details) => console.warn(`[Mastra Factory] ${message}`, details));\n const boards = toBoardSource(options.boards);\n\n /** The left context's session, unless the card is back in that context or holds the session under its new one. */\n const leftSession = async (args: ContextLeftArgs, expectedRevision?: number): Promise<string | undefined> => {\n const item = await options.workItems.get({ orgId: args.orgId, id: args.workItemId });\n if (!item) return undefined;\n if (expectedRevision !== undefined && item.revision !== expectedRevision) return undefined;\n const sessionId = sessionIdOf(item, args.context);\n if (!sessionId) return undefined;\n const stage = item.stages.length === 1 ? item.stages[0] : undefined;\n const registry = await boards.load({ orgId: args.orgId, factoryProjectId: args.factoryProjectId });\n const current = stage === undefined ? undefined : registry.get(boardForWorkItem(item))?.roleForPhase(stage);\n if (current !== undefined && sessionIdOf(item, current) === sessionId) return undefined;\n return sessionId;\n };\n\n const stop = async (args: ContextLeftArgs, sessionId: string): Promise<void> => {\n const sourceControl = await options.sessions.getSourceControlBySessionId(sessionId);\n if (!sourceControl) return;\n await options.retirement.stopSessionSandbox({ sourceControl, orgId: args.orgId, sessionId });\n };\n\n return async (args: ContextLeftArgs): Promise<void> => {\n try {\n // Like terminal cleanup: a card re-entered before this ran keeps its sandbox.\n const sessionId = await leftSession(args, args.revision);\n if (!sessionId) return;\n const run = await options.runInFlight(sessionId);\n if (!run) {\n await stop(args, sessionId);\n return;\n }\n // The revision may move on while the run ends (an attached pull\n // request bumps it), so only coming back to the context keeps the sandbox.\n void run.ended\n .then(async () => {\n if ((await leftSession(args)) === sessionId) await stop(args, sessionId);\n })\n .catch(error => warn('Factory context sandbox stop failed', { ...args, sessionId, error: String(error) }));\n } catch (error) {\n warn('Factory context sandbox stop failed', { ...args, error: String(error) });\n }\n };\n}\n\n/**\n * Retire every session a finished card holds: each sandbox is stopped, not\n * destroyed, by identity when this process never attached to it, so a card\n * finished on another replica still stops its sandboxes.\n */\nexport function createTerminalSandboxStops(options: {\n workItems: Pick<WorkItemsStorage, 'get'>;\n sessions: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;\n retirement: Pick<SessionRetirementCoordinator, 'retireSession'>;\n}) {\n return async ({ orgId, workItemId }: { orgId: string; workItemId: string }): Promise<void> => {\n const item = await options.workItems.get({ orgId, id: workItemId });\n if (!item) return;\n const sessionIds = [...new Set(Object.values(item.sessions).map(session => session.sessionId))];\n await Promise.all(\n sessionIds.map(async sessionId => {\n const sourceControl = await options.sessions.getSourceControlBySessionId(sessionId);\n if (!sourceControl) return;\n await options.retirement.retireSession({ source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,SAAS,4BAA4B,SAAS;GAClF,IAAI,CAAC,eAAe;GACpB,MAAM,QAAQ,WAAW,cAAc;IAAE;IAAe;IAAO;IAAW,eAAe;GAAM,CAAC;EAClG,CAAC,CACH;CACF;AACF"}
|
|
@@ -35,10 +35,9 @@ export interface RetireSessionInput {
|
|
|
35
35
|
* Sandbox identity is the session id: retirement stops (or, for deleted
|
|
36
36
|
* sessions, destroys) the sandbox this process holds in the session memo.
|
|
37
37
|
* Sessions opened on another replica (or before a restart) have no memo entry
|
|
38
|
-
* here:
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
* deletion must never orphan one.
|
|
38
|
+
* here: a materialized one is stopped (or, when deleted, destroyed) by
|
|
39
|
+
* identity through the configured sandbox. Providers such as E2B keep paused
|
|
40
|
+
* VMs forever, so the row's deletion must never orphan one.
|
|
42
41
|
*/
|
|
43
42
|
export declare class SessionRetirementCoordinator {
|
|
44
43
|
#private;
|
|
@@ -63,6 +62,14 @@ export declare class SessionRetirementCoordinator {
|
|
|
63
62
|
* `not-here` means this process holds no instance for the session.
|
|
64
63
|
*/
|
|
65
64
|
resetSessionSandbox(input: RecreateSessionSandboxInput): Promise<'reset' | 'not-found' | 'not-here'>;
|
|
65
|
+
/**
|
|
66
|
+
* Stop a session's sandbox and keep everything else: the row, its files and
|
|
67
|
+
* its work-item refs, so the session's next start resumes the same sandbox.
|
|
68
|
+
* Unlike retirement no teardown command runs, because a resume does not
|
|
69
|
+
* run setup again. Reaches the VM by identity when this process never
|
|
70
|
+
* attached to it.
|
|
71
|
+
*/
|
|
72
|
+
stopSessionSandbox(input: Omit<RetireSessionInput, 'deleteSession' | 'workItems'>): Promise<void>;
|
|
66
73
|
retireWorkItemSessions(options: {
|
|
67
74
|
workItems: Pick<WorkItemsStorage, 'get'>;
|
|
68
75
|
sourceControl: SourceControlStorageHandle;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-retirement.d.ts","sourceRoot":"","sources":["../../src/sandbox/session-retirement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAoB,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"session-retirement.d.ts","sourceRoot":"","sources":["../../src/sandbox/session-retirement.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAoB,MAAM,wBAAwB,CAAC;AAS/E,OAAO,KAAK,EAGV,0BAA0B,EAC3B,MAAM,2CAA2C,CAAC;AACnD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAI9E,KAAK,aAAa,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;AAEjF,MAAM,WAAW,mCAAmC;IAClD,iBAAiB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAChE;;;;OAIG;IACH,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,IAAI,CAAC,EAAE,aAAa,CAAC;IACrB,4FAA4F;IAC5F,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,2BAA2B;IAC1C,aAAa,EAAE,0BAA0B,CAAC;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;CACnB;AAgBD,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,0BAA0B,CAAC;IAC1C,8EAA8E;IAC9E,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,wBAAwB,CAAC,CAAC;IAC7D,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,OAAO,CAAC;CACxB;AAQD;;;;;;;;;;;GAWG;AACH,qBAAa,4BAA4B;;IAOvC,YAAY,OAAO,GAAE,mCAAwC,EAK5D;IAEK,aAAa,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAE5D;IAED;;;;;;OAMG;IACG,sBAAsB,CAAC,KAAK,EAAE,2BAA2B,GAAG,OAAO,CAAC,WAAW,GAAG,WAAW,CAAC,CAEnG;IAED;;;;;;;;;OASG;IACG,mBAAmB,CAAC,KAAK,EAAE,2BAA2B,GAAG,OAAO,CAAC,OAAO,GAAG,WAAW,GAAG,UAAU,CAAC,CAEzG;IAED;;;;;;OAMG;IACG,kBAAkB,CAAC,KAAK,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,GAAG,WAAW,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAWtG;IAaK,sBAAsB,CAAC,OAAO,EAAE;QACpC,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,KAAK,CAAC,CAAC;QACzC,aAAa,EAAE,0BAA0B,CAAC;QAC1C,KAAK,EAAE,MAAM,CAAC;QACd,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,IAAI,CAAC,CAchB;IAEK,+BAA+B,CAAC,OAAO,EAAE;QAC7C,aAAa,EAAE,0BAA0B,CAAC;QAC1C,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,wBAAwB,CAAC,CAAC;QAC7D,KAAK,EAAE,MAAM,CAAC;QACd,mBAAmB,EAAE,MAAM,CAAC;KAC7B,GAAG,OAAO,CAAC,IAAI,CAAC,CAehB;CAgRF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { destroyDetachedSessionSandbox, releaseSessionSandbox } from "../integrations/github/sandbox-release.js";
|
|
1
|
+
import { destroyDetachedSessionSandbox, releaseSessionSandbox, stopDetachedSessionSandbox } from "../integrations/github/sandbox-release.js";
|
|
2
2
|
import { DEFAULT_COMMAND_TIMEOUT_MS, runTeardownCommand } from "../integrations/github/sandbox.js";
|
|
3
3
|
import { peekSessionEnvironmentTeardown } from "../session/environment-state-processor.js";
|
|
4
4
|
import { requireExec } from "./materialization.js";
|
|
@@ -29,10 +29,9 @@ function boundedError(error) {
|
|
|
29
29
|
* Sandbox identity is the session id: retirement stops (or, for deleted
|
|
30
30
|
* sessions, destroys) the sandbox this process holds in the session memo.
|
|
31
31
|
* Sessions opened on another replica (or before a restart) have no memo entry
|
|
32
|
-
* here:
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
* deletion must never orphan one.
|
|
32
|
+
* here: a materialized one is stopped (or, when deleted, destroyed) by
|
|
33
|
+
* identity through the configured sandbox. Providers such as E2B keep paused
|
|
34
|
+
* VMs forever, so the row's deletion must never orphan one.
|
|
36
35
|
*/
|
|
37
36
|
var SessionRetirementCoordinator = class {
|
|
38
37
|
#invalidateSession;
|
|
@@ -72,6 +71,28 @@ var SessionRetirementCoordinator = class {
|
|
|
72
71
|
async resetSessionSandbox(input) {
|
|
73
72
|
return this.#withSessionLock(input.sessionId, () => this.#resetSessionSandbox(input));
|
|
74
73
|
}
|
|
74
|
+
/**
|
|
75
|
+
* Stop a session's sandbox and keep everything else: the row, its files and
|
|
76
|
+
* its work-item refs, so the session's next start resumes the same sandbox.
|
|
77
|
+
* Unlike retirement no teardown command runs, because a resume does not
|
|
78
|
+
* run setup again. Reaches the VM by identity when this process never
|
|
79
|
+
* attached to it.
|
|
80
|
+
*/
|
|
81
|
+
async stopSessionSandbox(input) {
|
|
82
|
+
await this.#withSessionLock(input.sessionId, async () => {
|
|
83
|
+
const session = await input.sourceControl.sessions.getBySessionId(input.sessionId);
|
|
84
|
+
if (!session || session.orgId !== input.orgId) return;
|
|
85
|
+
try {
|
|
86
|
+
if (peekSessionSandbox(session.id)) await releaseSessionSandbox({ sessionId: session.id });
|
|
87
|
+
else await this.#releaseDetachedSandbox({
|
|
88
|
+
...input,
|
|
89
|
+
deleteSession: false
|
|
90
|
+
}, session);
|
|
91
|
+
} finally {
|
|
92
|
+
await this.#invalidate(session);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
}
|
|
75
96
|
async #withSessionLock(sessionId, run) {
|
|
76
97
|
const current = (this.#locks.get(sessionId) ?? Promise.resolve()).catch(() => {}).then(run);
|
|
77
98
|
this.#locks.set(sessionId, current);
|
|
@@ -124,7 +145,7 @@ var SessionRetirementCoordinator = class {
|
|
|
124
145
|
async #teardownSessionSandbox(input, session) {
|
|
125
146
|
const entry = peekSessionSandbox(session.id);
|
|
126
147
|
if (!entry) {
|
|
127
|
-
await this.#
|
|
148
|
+
await this.#releaseDetachedSandbox(input, session);
|
|
128
149
|
return;
|
|
129
150
|
}
|
|
130
151
|
const environmentTeardown = peekSessionEnvironmentTeardown(session.sessionId);
|
|
@@ -170,19 +191,24 @@ var SessionRetirementCoordinator = class {
|
|
|
170
191
|
await this.#releaseSandbox(input, session);
|
|
171
192
|
}
|
|
172
193
|
/**
|
|
173
|
-
*
|
|
174
|
-
* for sessions that materialized (a
|
|
175
|
-
* started, no teardown command runs —
|
|
194
|
+
* Stop (or, for a deleted session, destroy) a session's VM that this
|
|
195
|
+
* process never attached to. Only for sessions that materialized (a
|
|
196
|
+
* persisted `sandboxId`): nothing is started, no teardown command runs —
|
|
197
|
+
* the provider pauses or kills by identity.
|
|
176
198
|
*/
|
|
177
|
-
async #
|
|
178
|
-
if (!
|
|
199
|
+
async #releaseDetachedSandbox(input, session) {
|
|
200
|
+
if (!session.sandboxId || !this.#sandbox) return;
|
|
179
201
|
try {
|
|
180
|
-
await destroyDetachedSessionSandbox({
|
|
202
|
+
if (input.deleteSession) await destroyDetachedSessionSandbox({
|
|
203
|
+
sandbox: this.#sandbox,
|
|
204
|
+
session
|
|
205
|
+
});
|
|
206
|
+
else await stopDetachedSessionSandbox({
|
|
181
207
|
sandbox: this.#sandbox,
|
|
182
208
|
session
|
|
183
209
|
});
|
|
184
210
|
} catch (error) {
|
|
185
|
-
this.#warn(
|
|
211
|
+
this.#warn(`Factory detached session sandbox ${input.deleteSession ? "destroy" : "stop"} failed`, {
|
|
186
212
|
orgId: session.orgId,
|
|
187
213
|
sessionId: session.sessionId,
|
|
188
214
|
projectRepositoryId: session.projectRepositoryId,
|