@mastra/factory 0.12.0-alpha.9 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -10
- package/dist/factory.d.ts +8 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +4 -3
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/integrations/github/acceptance-labels.d.ts +17 -0
- package/dist/integrations/github/acceptance-labels.d.ts.map +1 -0
- package/dist/integrations/github/acceptance-labels.js +55 -0
- package/dist/integrations/github/acceptance-labels.js.map +1 -0
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +47 -10
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +2 -2
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +10 -13
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +74 -65
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/settle-or-abort.d.ts +7 -0
- package/dist/integrations/github/settle-or-abort.d.ts.map +1 -0
- package/dist/integrations/github/settle-or-abort.js +25 -0
- package/dist/integrations/github/settle-or-abort.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +3 -3
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +37 -5
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/packages/_internals/workspace/dist/index.js +35 -0
- package/dist/packages/_internals/workspace/dist/index.js.map +1 -0
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +6 -0
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/oauth.d.ts +3 -0
- package/dist/routes/oauth.d.ts.map +1 -1
- package/dist/routes/oauth.js +10 -2
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/om-seed.d.ts +22 -0
- package/dist/routes/om-seed.d.ts.map +1 -0
- package/dist/routes/om-seed.js +40 -0
- package/dist/routes/om-seed.js.map +1 -0
- package/dist/routes/surface.d.ts +1 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +4 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +7 -0
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/defaults.d.ts.map +1 -1
- package/dist/rules/defaults.js +3 -0
- package/dist/rules/defaults.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +16 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/tools.d.ts.map +1 -1
- package/dist/rules/tools.js +1 -23
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +12 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +28 -3
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/sandbox/session-sandbox.d.ts +22 -8
- package/dist/sandbox/session-sandbox.d.ts.map +1 -1
- package/dist/sandbox/session-sandbox.js +36 -37
- package/dist/sandbox/session-sandbox.js.map +1 -1
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/memory-settings-hydration.d.ts +3 -3
- package/dist/session/memory-settings-hydration.js +3 -3
- package/dist/session/memory-settings-hydration.js.map +1 -1
- package/dist/session/org-seed.d.ts +5 -5
- package/dist/session/org-seed.js +2 -2
- package/dist/session/org-seed.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +8 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +10 -1
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/workspace.d.ts +8 -0
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +21 -6
- package/dist/workspace.js.map +1 -1
- package/package.json +11 -10
- package/dist/session/checkpoint-capture.d.ts +0 -18
- package/dist/session/checkpoint-capture.d.ts.map +0 -1
- package/dist/session/checkpoint-capture.js +0 -27
- package/dist/session/checkpoint-capture.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transition-service.js","names":["#rules","#storage","#timeoutMs","#onTerminalStage","#terminalCleanupTimeoutMs","#commitRejection","#commit"],"sources":["../../src/rules/transition-service.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { resolveFactoryStageRules } from './resolve.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleActor,\n FactoryRuleBoard,\n FactoryRuleCausalEntry,\n FactoryRuleRejectionCode,\n FactoryRuleStage,\n FactoryTriageType,\n FactoryRules,\n FactoryStageRuleContext,\n FactoryTransitionResult,\n} from './types.js';\nimport {\n externallyAuthoredWorkItem,\n factoryRuleSourceForWorkItem,\n isFactoryRuleStage,\n isWorkingFactoryRuleStage,\n workItemSource,\n} from './types.js';\nimport {\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n validateFactoryRuleDecision,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\nconst MAX_REJECTION_REASON = 512;\nconst TERMINAL_STAGES: ReadonlySet<FactoryRuleStage> = new Set(['done', 'canceled']);\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 board: FactoryRuleBoard;\n stage: FactoryRuleStage;\n expectedRevision: number;\n actor: FactoryRuleActor;\n ingress: { type: 'human' | 'agent' | 'toolResult' | 'github' | 'rule'; identity: string; transitionId?: string };\n cause: string;\n causalChain?: readonly FactoryRuleCausalEntry[];\n /** Internal materialization path: evaluate only the destination onEnter leaf even when already at that stage. */\n initialEntry?: boolean;\n /** Re-runs the stage's entry rules when the item already holds that stage, to restart work the entry invalidated. */\n reenter?: boolean;\n /** Structured verdict required from a bound triage-agent terminal request. */\n triageType?: FactoryTriageType;\n}\n\nexport interface FactoryTransitionServiceOptions {\n rules: FactoryRules;\n storage: WorkItemsStorage;\n timeoutMs?: number;\n /**\n * Called after a transition commits into a terminal stage (`done` /\n * `canceled`) — 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 }) => 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\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 }\n}\n\nexport function currentStage(stages: readonly string[]): FactoryRuleStage | undefined {\n if (stages.length !== 1) return undefined;\n const stage = stages[0];\n return isFactoryRuleStage(stage) ? stage : undefined;\n}\n\nexport function roleForStage(board: FactoryRuleBoard, stage: FactoryRuleStage): string {\n if (board === 'review') return 'review';\n if (stage === 'triage') return 'triage';\n if (stage === 'planning') return 'plan';\n return 'work';\n}\n\ninterface TransitionConsentOptions {\n autonomy?: 'arm' | 'disarm';\n consentedBy?: string;\n}\n\n// Entering a resting lane disarms whoever rests it; only a person's drag into a working lane arms.\nfunction transitionConsent(stage: FactoryRuleStage, humanBoardDrag: boolean): 'arm' | 'disarm' | undefined {\n if (!isWorkingFactoryRuleStage(stage)) return 'disarm';\n return humanBoardDrag ? '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(request: FactoryTransitionRequest, humanBoardDrag: boolean): TransitionConsentOptions {\n const autonomy = transitionConsent(request.stage, humanBoardDrag);\n if (autonomy === undefined) return {};\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.\nfunction runAlreadyUnderway(request: FactoryTransitionRequest, decision: RunStartDecision): boolean {\n if (request.cause === 'run_start') return true;\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 isTriageAgent(actor: FactoryRuleActor): actor is Extract<FactoryRuleActor, { type: 'agent' }> {\n return actor.type === 'agent' && actor.role === 'triage';\n}\n\nfunction isHumanTransition(request: FactoryTransitionRequest): boolean {\n return request.actor.type === 'human' && request.ingress.type === 'human';\n}\n\nfunction requiresHumanApproval(triageType: FactoryTriageType | null | undefined): boolean {\n return triageType !== undefined && triageType !== null && triageType !== 'bug';\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 #rules: FactoryRules;\n readonly #storage: WorkItemsStorage;\n readonly #timeoutMs: number;\n readonly #onTerminalStage: FactoryTransitionServiceOptions['onTerminalStage'];\n readonly #terminalCleanupTimeoutMs: number;\n\n constructor(options: FactoryTransitionServiceOptions) {\n this.#rules = options.rules;\n this.#storage = options.storage;\n this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;\n this.#onTerminalStage = options.onTerminalStage;\n this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;\n }\n\n get ruleSetVersion(): string {\n return this.#rules.version;\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 ?? randomUUID();\n const item = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (!item) {\n return this.#commitRejection(request, transitionId, 'invalid_transition', 'Work item not found.');\n }\n\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 if ((request.board === 'review') !== (source === 'pullRequest')) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not belong to the requested board.',\n );\n }\n const fromStage = currentStage(item.stages);\n if (!fromStage) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not have one canonical Factory stage.',\n );\n }\n\n if (isTriageAgent(request.actor) && request.triageType === undefined) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'Triage transitions must report a structured triage classification.',\n );\n }\n if (item.triageType && request.triageType && item.triageType !== request.triageType) {\n return this.#commitRejection(\n request,\n transitionId,\n 'forbidden',\n 'The persisted triage classification cannot be changed by a later transition.',\n );\n }\n const triageType = item.triageType ?? request.triageType;\n if (\n requiresHumanApproval(triageType) &&\n (request.stage === 'planning' || request.stage === 'execute') &&\n !isHumanTransition(request)\n ) {\n return this.#commitRejection(\n request,\n transitionId,\n 'approval_required',\n 'A maintainer must move this non-bug work item into Planning or Execute from the Factory UI.',\n );\n }\n\n // The card's own content can steer a bound agent; on a card authored\n // outside the write-access circle, leaving rest takes a person's gesture.\n if (\n request.actor.type === 'agent' &&\n !isWorkingFactoryRuleStage(fromStage) &&\n isWorkingFactoryRuleStage(request.stage) &&\n externallyAuthoredWorkItem(item)\n ) {\n return this.#commitRejection(\n request,\n transitionId,\n 'approval_required',\n 'This card comes from outside the write-access circle; a person must resume it from the Factory board.',\n );\n }\n\n const humanBoardDrag =\n request.actor.type === 'human' && request.cause === 'board_drag' && fromStage !== 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 ruleSetVersion: this.#rules.version,\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 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>[] }\n | { outcome: 'rejected'; code: string; reason: string };\n try {\n evaluation = await withRuleTimeout(\n (async () => {\n const decisions: FactoryCommitDecision[] = [];\n for (const rule of resolveFactoryStageRules(this.#rules, {\n board: request.board,\n source,\n fromStage,\n toStage: request.stage,\n initialEntry: request.initialEntry,\n reenter: request.reenter,\n })) {\n const context: FactoryStageRuleContext = Object.freeze({\n ...contextBase,\n stage: rule.phase === 'exit' ? fromStage : request.stage,\n });\n const raw = await rule.handler(context);\n if (raw === undefined) continue;\n const decision = validateFactoryRuleDecision(raw, context.causalChain.length);\n if (decision.type === 'reject') {\n return { outcome: 'rejected' as const, code: decision.code, reason: decision.reason };\n }\n if (startsRun(decision) && runAlreadyUnderway(request, decision)) continue;\n decisions.push(decision);\n }\n const validated = validateFactoryRuleDecisions(decisions);\n if (humanBoardDrag) {\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 ...(isWorkingFactoryRuleStage(request.stage)\n ? { role: roleForStage(request.board, request.stage), prepareBinding: true }\n : {}),\n });\n }\n }\n return {\n outcome: 'accepted' as const,\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' ? consentEffect(request, humanBoardDrag) : {},\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(request, transitionId, { outcome: 'rejected', code, reason });\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 ): 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 ruleSetVersion: this.#rules.version,\n causalChain: [...(request.causalChain ?? [])],\n evaluation,\n ...(isTriageAgent(request.actor) && request.triageType ? { triageType: request.triageType } : {}),\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 (this.#onTerminalStage && result.status === 'accepted' && TERMINAL_STAGES.has(result.stage)) {\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 }),\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 f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AQ,QAAQ;IAAU,aAAa,QAAQ,QAAQ;IAAM;GAAa;GAC/F,gBAAgB,KAAKD,OAAO;GAC5B,aAAa,CAAC,GAAI,QAAQ,eAAe,CAAC,CAAE;GAC5C;GACA,GAAI,cAAc,QAAQ,KAAK,KAAK,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;EACjG,CAAC;EACD,IAAI,UAAU,WAAW,WACvB,OAAO,UAAU,cAAc,QAAQ,YAAY,sBAAsB,sBAAsB;EAEjG,MAAM,SAAS,UAAU;EACzB,IAAI,KAAKG,oBAAoB,OAAO,WAAW,cAAc,gBAAgB,IAAI,OAAO,KAAK,GAAG;GAC9F,IAAI;GACJ,IAAI;IACF,MAAM,UAAU,QAAQ,QACtB,KAAKA,iBAAiB;KACpB,OAAO,QAAQ;KACf,kBAAkB,QAAQ;KAC1B,YAAY,QAAQ;KACpB,OAAO,OAAO;IAChB,CAAC,CACH;IAGA,QAAQ,YAAY,CAAC,CAAC;IACtB,MAAM,QAAQ,KAAK,CACjB,SACA,IAAI,SAAc,YAAW;KAC3B,QAAQ,WAAW,SAAS,KAAKC,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":["#rules","#storage","#timeoutMs","#onTerminalStage","#terminalCleanupTimeoutMs","#onAccepted","#commitRejection","#commit"],"sources":["../../src/rules/transition-service.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { WorkItemRow, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { resolveFactoryStageRules } from './resolve.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleActor,\n FactoryRuleBoard,\n FactoryRuleCausalEntry,\n FactoryRuleRejectionCode,\n FactoryRuleStage,\n FactoryTriageType,\n FactoryRules,\n FactoryStageRuleContext,\n FactoryTransitionResult,\n} from './types.js';\nimport {\n externallyAuthoredWorkItem,\n factoryRuleSourceForWorkItem,\n isFactoryRuleStage,\n isWorkingFactoryRuleStage,\n workItemSource,\n} from './types.js';\nimport {\n MAX_FACTORY_RULE_CAUSAL_DEPTH,\n validateFactoryRuleDecision,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\nconst MAX_REJECTION_REASON = 512;\nconst TERMINAL_STAGES: ReadonlySet<FactoryRuleStage> = new Set(['done', 'canceled']);\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 board: FactoryRuleBoard;\n stage: FactoryRuleStage;\n expectedRevision: number;\n actor: FactoryRuleActor;\n ingress: { type: 'human' | 'agent' | 'toolResult' | 'github' | 'rule'; identity: string; transitionId?: string };\n cause: string;\n causalChain?: readonly FactoryRuleCausalEntry[];\n /** Internal materialization path: evaluate only the destination onEnter leaf even when already at that stage. */\n initialEntry?: boolean;\n /** Re-runs the stage's entry rules when the item already holds that stage, to restart work the entry invalidated. */\n reenter?: boolean;\n /** Structured verdict required from a bound triage-agent terminal request. */\n triageType?: FactoryTriageType;\n}\n\nexport interface FactoryTransitionServiceOptions {\n rules: FactoryRules;\n storage: WorkItemsStorage;\n timeoutMs?: number;\n /**\n * Called after a transition commits into a terminal stage (`done` /\n * `canceled`) — 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 }) => 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 transition first records a person's acceptance of a\n * non-bug item (see `WorkItemRow.acceptedAt`). Fire-and-forget: failures\n * are swallowed, the committed transition never depends on it.\n */\n onAccepted?: (args: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n item: WorkItemRow;\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 }\n}\n\nexport function currentStage(stages: readonly string[]): FactoryRuleStage | undefined {\n if (stages.length !== 1) return undefined;\n const stage = stages[0];\n return isFactoryRuleStage(stage) ? stage : undefined;\n}\n\nexport function roleForStage(board: FactoryRuleBoard, stage: FactoryRuleStage): string {\n if (board === 'review') return 'review';\n if (stage === 'triage') return 'triage';\n if (stage === 'planning') return 'plan';\n return 'work';\n}\n\ninterface TransitionConsentOptions {\n autonomy?: 'arm' | 'disarm';\n consentedBy?: string;\n accept?: boolean;\n}\n\n// Entering a resting lane disarms whoever rests it; only a person's drag into a working lane arms.\nfunction transitionConsent(stage: FactoryRuleStage, humanBoardDrag: boolean): 'arm' | 'disarm' | undefined {\n if (!isWorkingFactoryRuleStage(stage)) return 'disarm';\n return humanBoardDrag ? '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(request: FactoryTransitionRequest, humanBoardDrag: boolean): TransitionConsentOptions {\n const autonomy = transitionConsent(request.stage, humanBoardDrag);\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.\nfunction runAlreadyUnderway(request: FactoryTransitionRequest, decision: RunStartDecision): boolean {\n if (request.cause === 'run_start') return true;\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 isTriageAgent(actor: FactoryRuleActor): actor is Extract<FactoryRuleActor, { type: 'agent' }> {\n return actor.type === 'agent' && actor.role === 'triage';\n}\n\nfunction isHumanTransition(request: FactoryTransitionRequest): boolean {\n return request.actor.type === 'human' && request.ingress.type === 'human';\n}\n\nfunction requiresHumanApproval(triageType: FactoryTriageType | null | undefined): boolean {\n return triageType !== undefined && triageType !== null && triageType !== 'bug';\n}\n\nfunction isAtRest(stage: FactoryRuleStage): boolean {\n return stage === 'intake' || stage === 'triage';\n}\n\nfunction entersWork(stage: FactoryRuleStage): boolean {\n return stage === 'planning' || stage === 'execute';\n}\n\n// A person moving a card into Planning/Execute is the approval gesture —\n// recorded once, so later agent hops need no second nod. Not limited to moves\n// out of rest: a card accepted before acceptance was recorded still gets its\n// stamp (and its label reconciled) the next time a person moves it forward.\nfunction acceptsItem(request: FactoryTransitionRequest): boolean {\n return isHumanTransition(request) && entersWork(request.stage);\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 #rules: FactoryRules;\n readonly #storage: WorkItemsStorage;\n readonly #timeoutMs: number;\n readonly #onTerminalStage: FactoryTransitionServiceOptions['onTerminalStage'];\n readonly #terminalCleanupTimeoutMs: number;\n readonly #onAccepted: FactoryTransitionServiceOptions['onAccepted'];\n\n constructor(options: FactoryTransitionServiceOptions) {\n this.#rules = options.rules;\n this.#storage = options.storage;\n this.#timeoutMs = options.timeoutMs ?? RULE_TIMEOUT_MS;\n this.#onTerminalStage = options.onTerminalStage;\n this.#onAccepted = options.onAccepted;\n this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;\n }\n\n get ruleSetVersion(): string {\n return this.#rules.version;\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 ?? randomUUID();\n const item = await this.#storage.get({ orgId: request.orgId, id: request.workItemId });\n if (!item) {\n return this.#commitRejection(request, transitionId, 'invalid_transition', 'Work item not found.');\n }\n\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 if ((request.board === 'review') !== (source === 'pullRequest')) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not belong to the requested board.',\n );\n }\n const fromStage = currentStage(item.stages);\n if (!fromStage) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'The work item does not have one canonical Factory stage.',\n );\n }\n\n if (isTriageAgent(request.actor) && request.triageType === undefined) {\n return this.#commitRejection(\n request,\n transitionId,\n 'invalid_transition',\n 'Triage transitions must report a structured triage classification.',\n );\n }\n if (item.triageType && request.triageType && item.triageType !== request.triageType) {\n return this.#commitRejection(\n request,\n transitionId,\n 'forbidden',\n 'The persisted triage classification cannot be changed by a later transition.',\n );\n }\n // The gate stands at the exit of rest. A non-bug card already in\n // Planning/Execute can only have been put there by a person, so an agent\n // carrying it further (plan → build) is not asked for a second nod even\n // when the acceptance stamp predates its recording.\n const triageType = item.triageType ?? request.triageType;\n if (\n requiresHumanApproval(triageType) &&\n entersWork(request.stage) &&\n isAtRest(fromStage) &&\n !isHumanTransition(request) &&\n !item.acceptedAt\n ) {\n return this.#commitRejection(\n request,\n transitionId,\n 'approval_required',\n 'A maintainer must move this non-bug work item into Planning or Execute from the Factory UI.',\n );\n }\n\n // The card's own content can steer a bound agent; on a card authored\n // outside the write-access circle, leaving rest takes a person's gesture.\n if (\n request.actor.type === 'agent' &&\n !isWorkingFactoryRuleStage(fromStage) &&\n isWorkingFactoryRuleStage(request.stage) &&\n externallyAuthoredWorkItem(item)\n ) {\n return this.#commitRejection(\n request,\n transitionId,\n 'approval_required',\n 'This card comes from outside the write-access circle; a person must resume it from the Factory board.',\n );\n }\n\n const humanBoardDrag =\n request.actor.type === 'human' && request.cause === 'board_drag' && fromStage !== 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 ruleSetVersion: this.#rules.version,\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 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>[] }\n | { outcome: 'rejected'; code: string; reason: string };\n try {\n evaluation = await withRuleTimeout(\n (async () => {\n const decisions: FactoryCommitDecision[] = [];\n for (const rule of resolveFactoryStageRules(this.#rules, {\n board: request.board,\n source,\n fromStage,\n toStage: request.stage,\n initialEntry: request.initialEntry,\n reenter: request.reenter,\n })) {\n const context: FactoryStageRuleContext = Object.freeze({\n ...contextBase,\n stage: rule.phase === 'exit' ? fromStage : request.stage,\n });\n const raw = await rule.handler(context);\n if (raw === undefined) continue;\n const decision = validateFactoryRuleDecision(raw, context.causalChain.length);\n if (decision.type === 'reject') {\n return { outcome: 'rejected' as const, code: decision.code, reason: decision.reason };\n }\n if (startsRun(decision) && runAlreadyUnderway(request, decision)) continue;\n decisions.push(decision);\n }\n const validated = validateFactoryRuleDecisions(decisions);\n if (humanBoardDrag) {\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 ...(isWorkingFactoryRuleStage(request.stage)\n ? { role: roleForStage(request.board, request.stage), prepareBinding: true }\n : {}),\n });\n }\n }\n return {\n outcome: 'accepted' as const,\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, humanBoardDrag), accept: acceptsItem(request) && !item.acceptedAt }\n : {},\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(request, transitionId, { outcome: 'rejected', code, reason });\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 ): Promise<FactoryTransitionResult> {\n const committed = await this.#storage.commitTransition({\n autonomy: options.autonomy,\n consentedBy: options.consentedBy,\n ...(options.accept ? { accept: true } : {}),\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 ruleSetVersion: this.#rules.version,\n causalChain: [...(request.causalChain ?? [])],\n evaluation,\n ...(isTriageAgent(request.actor) && request.triageType ? { triageType: request.triageType } : {}),\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.accept &&\n committed.status === 'committed' &&\n result.status === 'accepted' &&\n committed.item?.acceptedAt\n ) {\n const item = committed.item;\n void Promise.resolve(\n this.#onAccepted({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: request.workItemId,\n item,\n }),\n ).catch(error => {\n console.warn(`[factory] acceptance hook failed for work item ${request.workItemId}:`, error);\n });\n }\n if (this.#onTerminalStage && result.status === 'accepted' && TERMINAL_STAGES.has(result.stage)) {\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 }),\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":";;;;;AA6BA,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,kCAAiD,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;AAKnF,MAAM,8BAA8B;AAuDpC,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;CAC3B;AACF;AAEA,SAAgB,aAAa,QAAyD;CACpF,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,MAAM,QAAQ,OAAO;CACrB,OAAO,mBAAmB,KAAK,IAAI,QAAQ,KAAA;AAC7C;AAEA,SAAgB,aAAa,OAAyB,OAAiC;CACrF,IAAI,UAAU,UAAU,OAAO;CAC/B,IAAI,UAAU,UAAU,OAAO;CAC/B,IAAI,UAAU,YAAY,OAAO;CACjC,OAAO;AACT;AASA,SAAS,kBAAkB,OAAyB,gBAAuD;CACzG,IAAI,CAAC,0BAA0B,KAAK,GAAG,OAAO;CAC9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;IACpB;GACF,CAAC,CACH,CAAC,CAAC,OAAM,UAAS;IACf,QAAQ,KAAK,kDAAkD,QAAQ,WAAW,IAAI,KAAK;GAC7F,CAAC;EACH;EACA,IAAI,KAAKF,oBAAoB,OAAO,WAAW,cAAc,gBAAgB,IAAI,OAAO,KAAK,GAAG;GAC9F,IAAI;GACJ,IAAI;IACF,MAAM,UAAU,QAAQ,QACtB,KAAKA,iBAAiB;KACpB,OAAO,QAAQ;KACf,kBAAkB,QAAQ;KAC1B,YAAY,QAAQ;KACpB,OAAO,OAAO;IAChB,CAAC,CACH;IAGA,QAAQ,YAAY,CAAC,CAAC;IACtB,MAAM,QAAQ,KAAK,CACjB,SACA,IAAI,SAAc,YAAW;KAC3B,QAAQ,WAAW,SAAS,KAAKC,yBAAyB;IAC5D,CAAC,CACH,CAAC;GACH,QAAQ,CAER,UAAU;IACR,aAAa,KAAK;GACpB;EACF;EACA,OAAO;CACT;AACF"}
|
|
@@ -52,8 +52,22 @@ export interface FactorySandboxContext {
|
|
|
52
52
|
* ```
|
|
53
53
|
*/
|
|
54
54
|
export type MastraFactorySandboxConfig = (ctx: FactorySandboxContext) => MastraSandbox;
|
|
55
|
-
/**
|
|
56
|
-
|
|
55
|
+
/**
|
|
56
|
+
* What the start hook learned about the setup command before running the
|
|
57
|
+
* session setup, and how to record its completion afterwards.
|
|
58
|
+
*/
|
|
59
|
+
export interface SessionSetupGate {
|
|
60
|
+
/** True when the sandbox already carries a marker for the current setup command. */
|
|
61
|
+
setupDone: boolean;
|
|
62
|
+
/** Write the marker once the setup command succeeded. Best-effort. */
|
|
63
|
+
markSetupDone: () => Promise<void>;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The session's setup work, run against a started sandbox on EVERY start.
|
|
67
|
+
* Materialize and checkout are idempotent and must always run (a warm boot
|
|
68
|
+
* still needs its pull); only the setup command consults `gate`.
|
|
69
|
+
*/
|
|
70
|
+
export type SessionSetupRun = (sandbox: WorkspaceSandbox, workdir: string, gate: SessionSetupGate) => Promise<void>;
|
|
57
71
|
/**
|
|
58
72
|
* Per-process session-id → sandbox instance memo.
|
|
59
73
|
*
|
|
@@ -106,12 +120,12 @@ export declare function recordFailedSetupCommand(sessionId: string, command: str
|
|
|
106
120
|
export declare function hasFailedSetupCommand(sessionId: string, command: string): boolean;
|
|
107
121
|
/**
|
|
108
122
|
* Build the session setup hook, which factory attaches to the constructed
|
|
109
|
-
* sandbox with `setOnStart`. Runs inside the sandbox start
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
* onStart errors as fatal.
|
|
123
|
+
* sandbox with `setOnStart`. Runs inside the sandbox start lifecycle on
|
|
124
|
+
* every start, fresh VM or reconnect: materialize and checkout always run,
|
|
125
|
+
* and the setup command runs unless the sandbox already carries the marker
|
|
126
|
+
* for it (a warm template image, or an earlier successful start). Throwing
|
|
127
|
+
* fails `start()` loudly; core treats onStart errors as fatal.
|
|
114
128
|
*/
|
|
115
|
-
export declare function createSessionSetupHook(run: SessionSetupRun, sessionId: string, repoFullName: string): SandboxStartHook;
|
|
129
|
+
export declare function createSessionSetupHook(run: SessionSetupRun, sessionId: string, repoFullName: string, setupCommand: string | undefined): SandboxStartHook;
|
|
116
130
|
export {};
|
|
117
131
|
//# sourceMappingURL=session-sandbox.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-sandbox.d.ts","sourceRoot":"","sources":["../../src/sandbox/session-sandbox.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"session-sandbox.d.ts","sourceRoot":"","sources":["../../src/sandbox/session-sandbox.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAChG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAI3E;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,gDAAgD;IAChD,SA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,EAAE,MAAM,GAAG,IAAI,CAG3D;AAED,4DAA4D;AAC5D,wBAAgB,+BAA+B,IAAI,IAAI,CAGtD;AAcD,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAEjF;AAED,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAEjF;AAqCD;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,GAAG,EAAE,eAAe,EACpB,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,MAAM,GAAG,SAAS,GAC/B,gBAAgB,CAyBlB"}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { timedPhase } from "../timing.js";
|
|
2
|
+
import { SETUP_MARKER_PATH, setupMarkerContent } from "../packages/_internals/workspace/dist/index.js";
|
|
1
3
|
import { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder } from "./workdir.js";
|
|
4
|
+
import path from "path";
|
|
2
5
|
//#region src/sandbox/session-sandbox.ts
|
|
3
6
|
const sessionSandboxes = /* @__PURE__ */ new Map();
|
|
4
7
|
/**
|
|
@@ -79,50 +82,46 @@ function hasFailedSetupCommand(sessionId, command) {
|
|
|
79
82
|
return failedSetupCommands.get(sessionId) === command;
|
|
80
83
|
}
|
|
81
84
|
/**
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
85
|
+
* The setup completion marker is a convention shared with the repo templates
|
|
86
|
+
* (`@internal/workspace`): `.mastra-sandbox/setup` beside the checkout,
|
|
87
|
+
* containing a digest of the setup commands. Templates write it as their last
|
|
88
|
+
* build step, so a sandbox booted from a warm image already carries it; the
|
|
89
|
+
* start hook writes it after a successful runtime setup. It is a skip cache,
|
|
90
|
+
* not a correctness mechanism: the setup command is assumed idempotent, and a
|
|
91
|
+
* missing or mismatched marker only re-runs it.
|
|
92
|
+
*
|
|
93
|
+
* The working directory is the parent of the repo dir, which is also the
|
|
94
|
+
* template's build cwd, so this is the file the template's marker step wrote.
|
|
87
95
|
*/
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return sandbox.provider === "local" ? `./${SESSION_SETUP_MARKER}` : `$HOME/${SESSION_SETUP_MARKER}`;
|
|
96
|
+
function markerShellPath(workdir) {
|
|
97
|
+
return `${path.posix.dirname(workdir)}/${SETUP_MARKER_PATH}`;
|
|
91
98
|
}
|
|
92
|
-
async function
|
|
93
|
-
|
|
99
|
+
async function markerMatches(sandbox, workdir, content) {
|
|
100
|
+
const marker = markerShellPath(workdir);
|
|
101
|
+
return (await sandbox.executeCommand(`test -d "${workdir}/.git" && test -f "${marker}" && [ "$(cat "${marker}")" = "${content}" ]`)).exitCode === 0;
|
|
94
102
|
}
|
|
95
|
-
async function writeMarker(sandbox) {
|
|
96
|
-
const marker = markerShellPath(
|
|
97
|
-
await sandbox.executeCommand(`mkdir -p "$(dirname "${marker}")" &&
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Run the session setup, marker-guarded: skip when the marker exists (unless
|
|
101
|
-
* the VM is known-fresh), otherwise run and write the marker only on
|
|
102
|
-
* success. Setup failures propagate — no marker is written, so the next
|
|
103
|
-
* attempt re-runs.
|
|
104
|
-
*/
|
|
105
|
-
async function runGuardedSetup(sandbox, run, { skipMarkerProbe, sessionId, repoFullName }) {
|
|
106
|
-
if (!sandbox.executeCommand) throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);
|
|
107
|
-
const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);
|
|
108
|
-
if (!skipMarkerProbe && await markerPresent(sandbox, workdir)) return;
|
|
109
|
-
await run(sandbox, workdir);
|
|
110
|
-
await writeMarker(sandbox);
|
|
103
|
+
async function writeMarker(sandbox, workdir, content) {
|
|
104
|
+
const marker = markerShellPath(workdir);
|
|
105
|
+
await sandbox.executeCommand(`mkdir -p "$(dirname "${marker}")" && printf '%s' '${content}' > "${marker}"`).catch(() => {});
|
|
111
106
|
}
|
|
112
107
|
/**
|
|
113
108
|
* Build the session setup hook, which factory attaches to the constructed
|
|
114
|
-
* sandbox with `setOnStart`. Runs inside the sandbox start
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
* onStart errors as fatal.
|
|
109
|
+
* sandbox with `setOnStart`. Runs inside the sandbox start lifecycle on
|
|
110
|
+
* every start, fresh VM or reconnect: materialize and checkout always run,
|
|
111
|
+
* and the setup command runs unless the sandbox already carries the marker
|
|
112
|
+
* for it (a warm template image, or an earlier successful start). Throwing
|
|
113
|
+
* fails `start()` loudly; core treats onStart errors as fatal.
|
|
119
114
|
*/
|
|
120
|
-
function createSessionSetupHook(run, sessionId, repoFullName) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
115
|
+
function createSessionSetupHook(run, sessionId, repoFullName, setupCommand) {
|
|
116
|
+
const marker = setupCommand?.trim() ? setupMarkerContent(setupCommand) : void 0;
|
|
117
|
+
return async ({ sandbox }) => {
|
|
118
|
+
if (!sandbox.executeCommand) throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);
|
|
119
|
+
const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);
|
|
120
|
+
const setupDone = marker ? await timedPhase("workspace.setup-marker", () => markerMatches(sandbox, workdir, marker)) : true;
|
|
121
|
+
if (marker) process.stderr.write(`[factory:setup] ${setupDone ? "marker matches, skipping setup command" : "no matching marker, setup command will run"} (${markerShellPath(workdir)})\n`);
|
|
122
|
+
await run(sandbox, workdir, {
|
|
123
|
+
setupDone,
|
|
124
|
+
markSetupDone: () => marker ? writeMarker(sandbox, workdir, marker) : Promise.resolve()
|
|
126
125
|
});
|
|
127
126
|
};
|
|
128
127
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-sandbox.js","names":[],"sources":["../../src/sandbox/session-sandbox.ts"],"sourcesContent":["import type { MastraSandbox, SandboxStartHook, WorkspaceSandbox } from '@mastra/core/workspace';\nimport type { RepositoryAccess } from '../capabilities/version-control.js';\nimport { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder } from './workdir.js';\n\n/**\n * Everything factory knows about a session's sandbox needs — the whole\n * contract between factory and the deployer's sandbox callback. Factory owns\n * intent; the provider owns resolving `sessionId` to a runnable VM.\n */\nexport interface FactorySandboxContext {\n /** Stable session id — the sandbox identity. */\n sessionId: string;\n /** owner/name of the repository, when the session is repo-backed. */\n repoFullName?: string;\n /**\n * Configured repo setup command, when present. Part of a repo template's\n * identity: a different setup command produces a different template.\n */\n setupCommand?: string;\n /**\n * Resolves the session repository's clone URL and a fresh short-lived\n * credential for it. Providers use it for authenticated work that runs\n * outside the VM — resolving a private repo's head, or cloning it during\n * a template build. The credential is minted per call (installation\n * tokens expire in ~1h); never an org PAT.\n *\n * `undefined` when the session has no repository, which is how a provider\n * knows to build no repo template. The key is always present so that\n * passing the whole context to a provider helper keeps working when this\n * field changes, instead of silently resolving to \"no repository\".\n */\n getRepositoryAccess: (() => Promise<RepositoryAccess>) | undefined;\n}\n\n/**\n * The deploy's sandbox configuration: construct a session's sandbox from\n * intent. The sandbox identity is the session id; the provider must honor\n * id-keyed getOrCreate on `start()` (reconnect/resume an existing VM for the\n * id, create otherwise). Construction must be cheap and side-effect-free —\n * VMs are provisioned on `start()` only. Local sandboxes should root their\n * `workingDirectory` at a per-session directory (e.g.\n * `join(root, ctx.sessionId)`); the repo checks out as a subdirectory of it.\n *\n * Returns a `MastraSandbox`, not the bare `WorkspaceSandbox` interface:\n * factory relies on the base class for the start lifecycle and the runtime\n * env, so providers extend it rather than reimplementing the contract.\n *\n * Factory attaches its own session setup to the returned sandbox, so the\n * callback never has to wire it up. A callback may still pass its own\n * `onStart`; it runs after factory's setup, against a prepared workspace.\n *\n * @example\n * ```typescript\n * sandbox: ({ sessionId }) => new E2BSandbox({ id: sessionId })\n * ```\n */\nexport type MastraFactorySandboxConfig = (ctx: FactorySandboxContext) => MastraSandbox;\n\n/** The session's setup work, run against a started sandbox. Must be idempotent. */\nexport type SessionSetupRun = (sandbox: WorkspaceSandbox, workdir: string) => Promise<void>;\n\n/**\n * Per-process session-id → sandbox instance memo.\n *\n * The provider contract is id-keyed getOrCreate, but provider find-then-create\n * has a real double-create race across independent instances. Memoizing the\n * instance per session makes the base class's per-instance start coalescing\n * apply process-wide per session — the same single-flight scope the fleet's\n * per-binding coalescing provided. Cross-replica races are accepted (the\n * fleet was also per-replica).\n */\ninterface SessionSandboxEntry {\n sandbox: WorkspaceSandbox;\n /**\n * The session's repo checkout root, recorded for passive readers (fs\n * routes, capture, authz). Local sandboxes derive it at construction;\n * remote sandboxes clone into the VM's own home, so it is undefined until\n * `resolveSessionWorkdir` probes the first started VM — passive readers\n * treat an unresolved workdir as \"nothing materialized\".\n */\n workdir?: string;\n}\n\nconst sessionSandboxes = new Map<string, SessionSandboxEntry>();\n\n/**\n * Get the session's memoized sandbox entry, constructing (and memoizing) it on\n * first access. Construction is cheap and side-effect-free by contract; VMs\n * are provisioned on `start()` only. Local sandboxes get their workdir here;\n * remote workdirs are a runtime fact of the VM, resolved on first start.\n */\nexport function getSessionSandbox(\n sessionId: string,\n repoFullName: string,\n construct: () => WorkspaceSandbox,\n): SessionSandboxEntry {\n const existing = sessionSandboxes.get(sessionId);\n if (existing) return existing;\n const sandbox = construct();\n const local = deriveLocalWorkdir(sandbox, repoFullName);\n const entry: SessionSandboxEntry = { sandbox, ...(local ? { workdir: local } : {}) };\n sessionSandboxes.set(sessionId, entry);\n return entry;\n}\n\n/**\n * Resolve (and memoize on the session entry) the session's repo checkout\n * root. Local sandboxes answer synchronously from their configured\n * `workingDirectory`; remote sandboxes clone into the VM's own default cwd,\n * so the first resolution probes it with one `pwd` — the VM tells us where\n * home is, we never invent a path. Calling this against a stopped sandbox\n * lazily starts it (the probe is a command), so passive readers must peek\n * `entry.workdir` instead.\n */\nexport async function resolveSessionWorkdir(\n sessionId: string,\n sandbox: WorkspaceSandbox,\n repoFullName: string,\n): Promise<string> {\n const entry = sessionSandboxes.get(sessionId);\n if (entry?.workdir && entry.sandbox === sandbox) return entry.workdir;\n const workdir =\n deriveLocalWorkdir(sandbox, repoFullName) ??\n deriveRemoteRepoDir(sandbox, repoFullName) ??\n repoDirUnder(await probeHome(sandbox), repoFullName);\n if (entry && entry.sandbox === sandbox) entry.workdir = workdir;\n return workdir;\n}\n\n/** One `pwd` in the VM's default shell cwd — its home dir, by provider convention. */\nasync function probeHome(sandbox: WorkspaceSandbox): Promise<string> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot resolve its workdir: no executeCommand implementation`);\n }\n const probe = await sandbox.executeCommand('pwd');\n const home = probe.stdout.trim().split('\\n').pop()?.trim() ?? '';\n if (probe.exitCode !== 0 || !home.startsWith('/')) {\n throw new Error(\n `Sandbox '${sandbox.id}' default cwd probe failed (exit ${probe.exitCode}): ${\n probe.stderr.trim() || probe.stdout.trim() || 'empty output'\n }`,\n );\n }\n return home;\n}\n\n/**\n * The session's memoized sandbox (and its workdir) when one was already\n * constructed in this process, else undefined. Never constructs — passive\n * read paths use this so browsing files cannot provision a VM.\n */\nexport function peekSessionSandbox(sessionId: string): SessionSandboxEntry | undefined {\n return sessionSandboxes.get(sessionId);\n}\n\n/** Drop the memoized instance (on stop/destroy/retirement or construction failure). */\nexport function evictSessionSandbox(sessionId: string): void {\n sessionSandboxes.delete(sessionId);\n failedSetupCommands.delete(sessionId);\n}\n\n/** Test-only: reset the process-wide memo between tests. */\nexport function __clearSessionSandboxesForTests(): void {\n sessionSandboxes.clear();\n failedSetupCommands.clear();\n}\n\n/**\n * Setup commands that already failed once for a session. The first failure\n * fails the start loudly — the agent sees the real error in the tool result\n * that triggered it. Recording it lets the next start skip the known-bad\n * command instead of wedging the session behind a permanently failing\n * onStart: clone and checkout still run, and the agent can fix or re-run\n * the setup itself. Keyed by the exact command so an edited setup command\n * runs fresh. In-memory only — a server restart re-runs the (idempotent)\n * setup.\n */\nconst failedSetupCommands = new Map<string, string>();\n\nexport function recordFailedSetupCommand(sessionId: string, command: string): void {\n failedSetupCommands.set(sessionId, command);\n}\n\nexport function hasFailedSetupCommand(sessionId: string, command: string): boolean {\n return failedSetupCommands.get(sessionId) === command;\n}\n\n/**\n * Completion marker for the session setup. Factory owns this end-to-end:\n * the `onStart` hook and the post-start fallback guard the exact same path,\n * so setup never double-runs regardless of which layer executed it. It is a\n * skip cache, not a correctness mechanism — the setup work is idempotent by\n * construction (materialize probes the disk, checkout/setup re-run safely).\n */\nconst SESSION_SETUP_MARKER = '.mastra-factory/bootstrap';\n\nfunction markerShellPath(sandbox: Pick<WorkspaceSandbox, 'provider'>): string {\n // Local sandboxes exec with cwd = the session working directory; remote\n // VMs are one-per-session so $HOME is private to the session.\n return sandbox.provider === 'local' ? `./${SESSION_SETUP_MARKER}` : `$HOME/${SESSION_SETUP_MARKER}`;\n}\n\nasync function markerPresent(sandbox: WorkspaceSandbox, workdir: string): Promise<boolean> {\n // The marker is a skip cache — it sits beside the checkout, not inside it,\n // so it can outlive a removed checkout (e.g. a wiped local session dir or\n // a recovered VM). Trust it only when the checkout it describes exists.\n const probe = await sandbox.executeCommand!(`test -f \"${markerShellPath(sandbox)}\" && test -d \"${workdir}/.git\"`);\n return probe.exitCode === 0;\n}\n\nasync function writeMarker(sandbox: WorkspaceSandbox): Promise<void> {\n // Best-effort: a missing marker only re-runs the idempotent setup later.\n const marker = markerShellPath(sandbox);\n await sandbox.executeCommand!(`mkdir -p \"$(dirname \"${marker}\")\" && touch \"${marker}\"`).catch(() => {});\n}\n\n/**\n * Run the session setup, marker-guarded: skip when the marker exists (unless\n * the VM is known-fresh), otherwise run and write the marker only on\n * success. Setup failures propagate — no marker is written, so the next\n * attempt re-runs.\n */\nasync function runGuardedSetup(\n sandbox: WorkspaceSandbox,\n run: SessionSetupRun,\n { skipMarkerProbe, sessionId, repoFullName }: { skipMarkerProbe: boolean; sessionId: string; repoFullName: string },\n): Promise<void> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);\n }\n // Resolved from the live instance (the hook runs inside `start()`, so the\n // VM is up) and memoized on the session entry for passive readers.\n const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);\n if (!skipMarkerProbe && (await markerPresent(sandbox, workdir))) return;\n await run(sandbox, workdir);\n await writeMarker(sandbox);\n}\n\n/**\n * Build the session setup hook, which factory attaches to the constructed\n * sandbox with `setOnStart`. Runs inside the sandbox start\n * lifecycle: a fresh VM (`outcome: 'created'`) runs setup with no probe; a\n * reconnect probes the marker first, which re-runs setup after a failed or\n * crash-interrupted attempt. Throwing fails `start()` loudly — core treats\n * onStart errors as fatal.\n */\nexport function createSessionSetupHook(\n run: SessionSetupRun,\n sessionId: string,\n repoFullName: string,\n): SandboxStartHook {\n return async ({ sandbox, outcome }) => {\n await runGuardedSetup(sandbox, run, { skipMarkerProbe: outcome === 'created', sessionId, repoFullName });\n };\n}\n"],"mappings":";;AAmFA,MAAM,mCAAmB,IAAI,IAAiC;;;;;;;AAQ9D,SAAgB,kBACd,WACA,cACA,WACqB;CACrB,MAAM,WAAW,iBAAiB,IAAI,SAAS;CAC/C,IAAI,UAAU,OAAO;CACrB,MAAM,UAAU,UAAU;CAC1B,MAAM,QAAQ,mBAAmB,SAAS,YAAY;CACtD,MAAM,QAA6B;EAAE;EAAS,GAAI,QAAQ,EAAE,SAAS,MAAM,IAAI,CAAC;CAAG;CACnF,iBAAiB,IAAI,WAAW,KAAK;CACrC,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,sBACpB,WACA,SACA,cACiB;CACjB,MAAM,QAAQ,iBAAiB,IAAI,SAAS;CAC5C,IAAI,OAAO,WAAW,MAAM,YAAY,SAAS,OAAO,MAAM;CAC9D,MAAM,UACJ,mBAAmB,SAAS,YAAY,K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B,QAAQ,OAAO,EAAA,CACnG,aAAa;AAC5B;AAEA,eAAe,YAAY,SAA0C;CAEnE,MAAM,SAAS,gBAAgB,OAAO;CACtC,MAAM,QAAQ,eAAgB,wBAAwB,OAAO,gBAAgB,OAAO,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC;AACxG;;;;;;;AAQA,eAAe,gBACb,SACA,KACA,EAAE,iBAAiB,WAAW,gBACf;CACf,IAAI,CAAC,QAAQ,gBACX,MAAM,IAAI,MAAM,YAAY,QAAQ,GAAG,iEAAiE;CAI1G,MAAM,UAAU,MAAM,sBAAsB,WAAW,SAAS,YAAY;CAC5E,IAAI,CAAC,mBAAoB,MAAM,cAAc,SAAS,OAAO,GAAI;CACjE,MAAM,IAAI,SAAS,OAAO;CAC1B,MAAM,YAAY,OAAO;AAC3B;;;;;;;;;AAUA,SAAgB,uBACd,KACA,WACA,cACkB;CAClB,OAAO,OAAO,EAAE,SAAS,cAAc;EACrC,MAAM,gBAAgB,SAAS,KAAK;GAAE,iBAAiB,YAAY;GAAW;GAAW;EAAa,CAAC;CACzG;AACF"}
|
|
1
|
+
{"version":3,"file":"session-sandbox.js","names":[],"sources":["../../src/sandbox/session-sandbox.ts"],"sourcesContent":["import path from 'node:path';\nimport { SETUP_MARKER_PATH, setupMarkerContent } from '@internal/workspace';\n\nimport type { MastraSandbox, SandboxStartHook, WorkspaceSandbox } from '@mastra/core/workspace';\nimport type { RepositoryAccess } from '../capabilities/version-control.js';\nimport { timedPhase } from '../timing.js';\nimport { deriveLocalWorkdir, deriveRemoteRepoDir, repoDirUnder } from './workdir.js';\n\n/**\n * Everything factory knows about a session's sandbox needs — the whole\n * contract between factory and the deployer's sandbox callback. Factory owns\n * intent; the provider owns resolving `sessionId` to a runnable VM.\n */\nexport interface FactorySandboxContext {\n /** Stable session id — the sandbox identity. */\n sessionId: string;\n /** owner/name of the repository, when the session is repo-backed. */\n repoFullName?: string;\n /**\n * Configured repo setup command, when present. Part of a repo template's\n * identity: a different setup command produces a different template.\n */\n setupCommand?: string;\n /**\n * Resolves the session repository's clone URL and a fresh short-lived\n * credential for it. Providers use it for authenticated work that runs\n * outside the VM — resolving a private repo's head, or cloning it during\n * a template build. The credential is minted per call (installation\n * tokens expire in ~1h); never an org PAT.\n *\n * `undefined` when the session has no repository, which is how a provider\n * knows to build no repo template. The key is always present so that\n * passing the whole context to a provider helper keeps working when this\n * field changes, instead of silently resolving to \"no repository\".\n */\n getRepositoryAccess: (() => Promise<RepositoryAccess>) | undefined;\n}\n\n/**\n * The deploy's sandbox configuration: construct a session's sandbox from\n * intent. The sandbox identity is the session id; the provider must honor\n * id-keyed getOrCreate on `start()` (reconnect/resume an existing VM for the\n * id, create otherwise). Construction must be cheap and side-effect-free —\n * VMs are provisioned on `start()` only. Local sandboxes should root their\n * `workingDirectory` at a per-session directory (e.g.\n * `join(root, ctx.sessionId)`); the repo checks out as a subdirectory of it.\n *\n * Returns a `MastraSandbox`, not the bare `WorkspaceSandbox` interface:\n * factory relies on the base class for the start lifecycle and the runtime\n * env, so providers extend it rather than reimplementing the contract.\n *\n * Factory attaches its own session setup to the returned sandbox, so the\n * callback never has to wire it up. A callback may still pass its own\n * `onStart`; it runs after factory's setup, against a prepared workspace.\n *\n * @example\n * ```typescript\n * sandbox: ({ sessionId }) => new E2BSandbox({ id: sessionId })\n * ```\n */\nexport type MastraFactorySandboxConfig = (ctx: FactorySandboxContext) => MastraSandbox;\n\n/**\n * What the start hook learned about the setup command before running the\n * session setup, and how to record its completion afterwards.\n */\nexport interface SessionSetupGate {\n /** True when the sandbox already carries a marker for the current setup command. */\n setupDone: boolean;\n /** Write the marker once the setup command succeeded. Best-effort. */\n markSetupDone: () => Promise<void>;\n}\n\n/**\n * The session's setup work, run against a started sandbox on EVERY start.\n * Materialize and checkout are idempotent and must always run (a warm boot\n * still needs its pull); only the setup command consults `gate`.\n */\nexport type SessionSetupRun = (sandbox: WorkspaceSandbox, workdir: string, gate: SessionSetupGate) => Promise<void>;\n\n/**\n * Per-process session-id → sandbox instance memo.\n *\n * The provider contract is id-keyed getOrCreate, but provider find-then-create\n * has a real double-create race across independent instances. Memoizing the\n * instance per session makes the base class's per-instance start coalescing\n * apply process-wide per session — the same single-flight scope the fleet's\n * per-binding coalescing provided. Cross-replica races are accepted (the\n * fleet was also per-replica).\n */\ninterface SessionSandboxEntry {\n sandbox: WorkspaceSandbox;\n /**\n * The session's repo checkout root, recorded for passive readers (fs\n * routes, capture, authz). Local sandboxes derive it at construction;\n * remote sandboxes clone into the VM's own home, so it is undefined until\n * `resolveSessionWorkdir` probes the first started VM — passive readers\n * treat an unresolved workdir as \"nothing materialized\".\n */\n workdir?: string;\n}\n\nconst sessionSandboxes = new Map<string, SessionSandboxEntry>();\n\n/**\n * Get the session's memoized sandbox entry, constructing (and memoizing) it on\n * first access. Construction is cheap and side-effect-free by contract; VMs\n * are provisioned on `start()` only. Local sandboxes get their workdir here;\n * remote workdirs are a runtime fact of the VM, resolved on first start.\n */\nexport function getSessionSandbox(\n sessionId: string,\n repoFullName: string,\n construct: () => WorkspaceSandbox,\n): SessionSandboxEntry {\n const existing = sessionSandboxes.get(sessionId);\n if (existing) return existing;\n const sandbox = construct();\n const local = deriveLocalWorkdir(sandbox, repoFullName);\n const entry: SessionSandboxEntry = { sandbox, ...(local ? { workdir: local } : {}) };\n sessionSandboxes.set(sessionId, entry);\n return entry;\n}\n\n/**\n * Resolve (and memoize on the session entry) the session's repo checkout\n * root. Local sandboxes answer synchronously from their configured\n * `workingDirectory`; remote sandboxes clone into the VM's own default cwd,\n * so the first resolution probes it with one `pwd` — the VM tells us where\n * home is, we never invent a path. Calling this against a stopped sandbox\n * lazily starts it (the probe is a command), so passive readers must peek\n * `entry.workdir` instead.\n */\nexport async function resolveSessionWorkdir(\n sessionId: string,\n sandbox: WorkspaceSandbox,\n repoFullName: string,\n): Promise<string> {\n const entry = sessionSandboxes.get(sessionId);\n if (entry?.workdir && entry.sandbox === sandbox) return entry.workdir;\n const workdir =\n deriveLocalWorkdir(sandbox, repoFullName) ??\n deriveRemoteRepoDir(sandbox, repoFullName) ??\n repoDirUnder(await probeHome(sandbox), repoFullName);\n if (entry && entry.sandbox === sandbox) entry.workdir = workdir;\n return workdir;\n}\n\n/** One `pwd` in the VM's default shell cwd — its home dir, by provider convention. */\nasync function probeHome(sandbox: WorkspaceSandbox): Promise<string> {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot resolve its workdir: no executeCommand implementation`);\n }\n const probe = await sandbox.executeCommand('pwd');\n const home = probe.stdout.trim().split('\\n').pop()?.trim() ?? '';\n if (probe.exitCode !== 0 || !home.startsWith('/')) {\n throw new Error(\n `Sandbox '${sandbox.id}' default cwd probe failed (exit ${probe.exitCode}): ${\n probe.stderr.trim() || probe.stdout.trim() || 'empty output'\n }`,\n );\n }\n return home;\n}\n\n/**\n * The session's memoized sandbox (and its workdir) when one was already\n * constructed in this process, else undefined. Never constructs — passive\n * read paths use this so browsing files cannot provision a VM.\n */\nexport function peekSessionSandbox(sessionId: string): SessionSandboxEntry | undefined {\n return sessionSandboxes.get(sessionId);\n}\n\n/** Drop the memoized instance (on stop/destroy/retirement or construction failure). */\nexport function evictSessionSandbox(sessionId: string): void {\n sessionSandboxes.delete(sessionId);\n failedSetupCommands.delete(sessionId);\n}\n\n/** Test-only: reset the process-wide memo between tests. */\nexport function __clearSessionSandboxesForTests(): void {\n sessionSandboxes.clear();\n failedSetupCommands.clear();\n}\n\n/**\n * Setup commands that already failed once for a session. The first failure\n * fails the start loudly — the agent sees the real error in the tool result\n * that triggered it. Recording it lets the next start skip the known-bad\n * command instead of wedging the session behind a permanently failing\n * onStart: clone and checkout still run, and the agent can fix or re-run\n * the setup itself. Keyed by the exact command so an edited setup command\n * runs fresh. In-memory only — a server restart re-runs the (idempotent)\n * setup.\n */\nconst failedSetupCommands = new Map<string, string>();\n\nexport function recordFailedSetupCommand(sessionId: string, command: string): void {\n failedSetupCommands.set(sessionId, command);\n}\n\nexport function hasFailedSetupCommand(sessionId: string, command: string): boolean {\n return failedSetupCommands.get(sessionId) === command;\n}\n\n/**\n * The setup completion marker is a convention shared with the repo templates\n * (`@internal/workspace`): `.mastra-sandbox/setup` beside the checkout,\n * containing a digest of the setup commands. Templates write it as their last\n * build step, so a sandbox booted from a warm image already carries it; the\n * start hook writes it after a successful runtime setup. It is a skip cache,\n * not a correctness mechanism: the setup command is assumed idempotent, and a\n * missing or mismatched marker only re-runs it.\n *\n * The working directory is the parent of the repo dir, which is also the\n * template's build cwd, so this is the file the template's marker step wrote.\n */\nfunction markerShellPath(workdir: string): string {\n return `${path.posix.dirname(workdir)}/${SETUP_MARKER_PATH}`;\n}\n\nasync function markerMatches(sandbox: WorkspaceSandbox, workdir: string, content: string): Promise<boolean> {\n // The marker sits beside the checkout, not inside it, so it can outlive a\n // removed checkout (a wiped local session dir, a recovered VM). Trust it\n // only when the checkout it describes exists and it names this command.\n const marker = markerShellPath(workdir);\n const probe = await sandbox.executeCommand!(\n `test -d \"${workdir}/.git\" && test -f \"${marker}\" && [ \"$(cat \"${marker}\")\" = \"${content}\" ]`,\n );\n return probe.exitCode === 0;\n}\n\nasync function writeMarker(sandbox: WorkspaceSandbox, workdir: string, content: string): Promise<void> {\n // Best-effort: a missing marker only re-runs the idempotent setup later.\n const marker = markerShellPath(workdir);\n await sandbox.executeCommand!(`mkdir -p \"$(dirname \"${marker}\")\" && printf '%s' '${content}' > \"${marker}\"`).catch(\n () => {},\n );\n}\n\n/**\n * Build the session setup hook, which factory attaches to the constructed\n * sandbox with `setOnStart`. Runs inside the sandbox start lifecycle on\n * every start, fresh VM or reconnect: materialize and checkout always run,\n * and the setup command runs unless the sandbox already carries the marker\n * for it (a warm template image, or an earlier successful start). Throwing\n * fails `start()` loudly; core treats onStart errors as fatal.\n */\nexport function createSessionSetupHook(\n run: SessionSetupRun,\n sessionId: string,\n repoFullName: string,\n setupCommand: string | undefined,\n): SandboxStartHook {\n // No command, no marker: nothing to gate.\n const marker = setupCommand?.trim() ? setupMarkerContent(setupCommand) : undefined;\n return async ({ sandbox }) => {\n if (!sandbox.executeCommand) {\n throw new Error(`Sandbox '${sandbox.id}' cannot run the session setup: no executeCommand implementation`);\n }\n // Resolved from the live instance (the hook runs inside `start()`, so the\n // VM is up) and memoized on the session entry for passive readers.\n const workdir = await resolveSessionWorkdir(sessionId, sandbox, repoFullName);\n // Probed before materialize so a wiped checkout reads as \"not done\" even\n // though materialize is about to restore it.\n const setupDone = marker\n ? await timedPhase('workspace.setup-marker', () => markerMatches(sandbox, workdir, marker))\n : true;\n if (marker) {\n process.stderr.write(\n `[factory:setup] ${setupDone ? 'marker matches, skipping setup command' : 'no matching marker, setup command will run'} (${markerShellPath(workdir)})\\n`,\n );\n }\n await run(sandbox, workdir, {\n setupDone,\n markSetupDone: () => (marker ? writeMarker(sandbox, workdir, marker) : Promise.resolve()),\n });\n };\n}\n"],"mappings":";;;;;AAsGA,MAAM,mCAAmB,IAAI,IAAiC;;;;;;;AAQ9D,SAAgB,kBACd,WACA,cACA,WACqB;CACrB,MAAM,WAAW,iBAAiB,IAAI,SAAS;CAC/C,IAAI,UAAU,OAAO;CACrB,MAAM,UAAU,UAAU;CAC1B,MAAM,QAAQ,mBAAmB,SAAS,YAAY;CACtD,MAAM,QAA6B;EAAE;EAAS,GAAI,QAAQ,EAAE,SAAS,MAAM,IAAI,CAAC;CAAG;CACnF,iBAAiB,IAAI,WAAW,KAAK;CACrC,OAAO;AACT;;;;;;;;;;AAWA,eAAsB,sBACpB,WACA,SACA,cACiB;CACjB,MAAM,QAAQ,iBAAiB,IAAI,SAAS;CAC5C,IAAI,OAAO,WAAW,MAAM,YAAY,SAAS,OAAO,MAAM;CAC9D,MAAM,UACJ,mBAAmB,SAAS,YAAY,KACxC,oBAAoB,SAAS,YAAY,KACzC,aAAa,MAAM,UAAU,OAAO,GAAG,YAAY;CACrD,IAAI,SAAS,MAAM,YAAY,SAAS,MAAM,UAAU;CACxD,OAAO;AACT;;AAGA,eAAe,UAA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OAAO;CACtC,MAAM,QAAQ,eAAgB,wBAAwB,OAAO,sBAAsB,QAAQ,OAAO,OAAO,EAAE,CAAC,CAAC,YACrG,CAAC,CACT;AACF;;;;;;;;;AAUA,SAAgB,uBACd,KACA,WACA,cACA,cACkB;CAElB,MAAM,SAAS,cAAc,KAAK,IAAI,mBAAmB,YAAY,IAAI,KAAA;CACzE,OAAO,OAAO,EAAE,cAAc;EAC5B,IAAI,CAAC,QAAQ,gBACX,MAAM,IAAI,MAAM,YAAY,QAAQ,GAAG,iEAAiE;EAI1G,MAAM,UAAU,MAAM,sBAAsB,WAAW,SAAS,YAAY;EAG5E,MAAM,YAAY,SACd,MAAM,WAAW,gCAAgC,cAAc,SAAS,SAAS,MAAM,CAAC,IACxF;EACJ,IAAI,QACF,QAAQ,OAAO,MACb,mBAAmB,YAAY,2CAA2C,6CAA6C,IAAI,gBAAgB,OAAO,EAAE,IACtJ;EAEF,MAAM,IAAI,SAAS,SAAS;GAC1B;GACA,qBAAsB,SAAS,YAAY,SAAS,SAAS,MAAM,IAAI,QAAQ,QAAQ;EACzF,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { resolveProviderOMDefault } from '@mastra/code-sdk/onboarding/packs';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { factoryMemorySettingsUserId } from '../storage/domains/memory-settings/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { applyStoredMemorySettings } from './memory-settings-hydration.js';\nimport { seedSessionOrg } from './org-seed.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\n/**\n * Read the factory project's default model. Best-effort: a missing project or an\n * uninitialized storage domain means \"no default\", never a failed run.\n */\nexport async function resolveFactoryDefaultModelId(\n projects: FactoryProjectsStorage | undefined,\n factoryProjectId: string | undefined,\n): Promise<string | undefined> {\n if (!projects || !factoryProjectId) return undefined;\n try {\n const project = await projects.getById({ id: factoryProjectId });\n return project?.defaultModelId ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolveFactorySourceRepository}. A miss carries which step\n * failed: callers differ on whether that is an error (an autonomous run cannot\n * proceed) or a routine fallback (a chat integration drops to a chat-only\n * session), and the two steps fail for different reasons worth reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * Resolve which repository a factory project's source-control runs act on: the\n * owner's connection on the project, then one of its linked repositories.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolveFactorySourceRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, repositorySlug } = args;\n\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const candidates = connections.filter(candidate => candidate.integrationId === sourceControl.integrationId);\n if (candidates.length === 0) return { found: false, reason: 'connection' };\n\n // A project can carry stale connections: a provider-app reinstall leaves the\n // old connection pointing at an installation that no longer exists, and that\n // row can sit ahead of the healthy one. Try every candidate and skip the ones\n // that no longer resolve rather than failing on the first.\n for (const connection of candidates) {\n let resolved;\n try {\n const projectRepositories = await sourceControl.projectRepositories.list({ orgId, connectionId: connection.id });\n const resolvedRepositories = await Promise.all(\n projectRepositories.map(async projectRepository => ({\n projectRepository,\n repository: await sourceControl.repositories.get({ orgId, id: projectRepository.repositoryId }),\n })),\n );\n resolved = resolvedRepositories.find(\n candidate => candidate.repository && (!repositorySlug || candidate.repository.slug === repositorySlug),\n );\n } catch {\n // The connection no longer resolves (e.g. its installation was deleted).\n continue;\n }\n if (!resolved?.repository) continue;\n\n return {\n found: true,\n projectRepositoryId: resolved.projectRepository.id,\n baseBranch: resolved.projectRepository.branch ?? resolved.repository.defaultBranch,\n connectedByUserId: connection.createdByUserId,\n };\n }\n\n return { found: false, reason: 'repository' };\n}\n\n/**\n * Walk a Factory user-session id back to the project it belongs to.\n *\n * Repo-backed channel threads are keyed by their Factory session id, which is\n * the only handle a session-start hook gets. This turns that id back into the\n * project whose configuration the session should adopt. Durable by\n * construction — it reads the same rows the session was created from, so it\n * survives restarts without any in-memory mapping.\n */\nexport async function resolveFactoryProjectForSession(args: {\n sourceControl: SourceControlStorageHandle;\n sessionId: string;\n}): Promise<{ factoryProjectId: string; orgId: string; userId: string } | null> {\n const { sourceControl, sessionId } = args;\n\n const session = await sourceControl.sessions.getBySessionId(sessionId);\n if (!session) return null;\n const projectRepository = await sourceControl.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) return null;\n const connection = await sourceControl.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n if (!connection) return null;\n\n return { factoryProjectId: connection.factoryProjectId, orgId: session.orgId, userId: session.userId };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, one of\n * its linked repositories, and a session on the requested branch with the\n * repository's pinned or default branch as the base.\n *\n * The run is attributed to `attributeToUserId` when the caller has an\n * interactive user (e.g. the approver of a proposed run), and otherwise falls\n * back to whoever connected the repository (`connection.createdByUserId`),\n * because a genuinely autonomous run has no interactive user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, repositorySlug } = args;\n\n const resolved = await resolveFactorySourceRepository({ sourceControl, orgId, factoryProjectId, repositorySlug });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n const session = await sourceControl.sessions.create({\n sessionId: randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n orgId,\n userId,\n branch,\n baseBranch: resolved.baseBranch,\n visibility: 'org',\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n /**\n * The factory project whose shared memory settings apply. Factory sessions\n * never read an individual user's personal memory settings — the project's\n * own row (or the built-in defaults) is what they run with.\n */\n factoryProjectId?: string;\n /** The factory project's default model. Without it the session keeps the SDK's built-in mode default. */\n defaultModelId?: string;\n /**\n * When provided, the factory project's stored memory-settings row is\n * applied. When omitted (or no row exists) the session is reset to the\n * built-in memory defaults.\n */\n memorySettings?: MemorySettingsStorage;\n}\n\n/**\n * Apply a factory project's configuration to a freshly created session:\n * observational-memory settings, then the project's default model.\n *\n * Both steps are best-effort. A retired model id or an unreachable settings row\n * must not sink a run that is otherwise ready — the session simply keeps the\n * default it was created with, and the reason is logged.\n */\nexport async function hydrateFactorySession(session: FactorySession, args: HydrateFactorySessionArgs): Promise<void> {\n // The org rung knowledge capture scopes on. Seeded first so it lands even if\n // a later best-effort step fails; an empty org marks the session unresolved.\n await seedSessionOrg(session, args.orgId);\n try {\n const record =\n args.memorySettings && args.factoryProjectId\n ? await args.memorySettings.get({\n orgId: args.orgId,\n userId: factoryMemorySettingsUserId(args.factoryProjectId),\n })\n : null;\n // Without a stored row, fall back to the low-cost OM model of the factory\n // default model's provider — a factory connected only to Anthropic should\n // not observe with the (uncredentialed) built-in Google default.\n const provider = args.defaultModelId?.split('/')[0];\n const fallbackOmModelId = provider ? resolveProviderOMDefault(provider, args.defaultModelId).modelId : undefined;\n await applyStoredMemorySettings(session, record, fallbackOmModelId);\n } catch (error) {\n console.warn('[Factory Start] Failed to apply observational-memory settings', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (args.defaultModelId) {\n try {\n await session.model.switch({ modelId: args.defaultModelId });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply factory default model', {\n modelId: args.defaultModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAmBA,eAAsB,6BACpB,UACA,kBAC6B;CAC7B,IAAI,CAAC,YAAY,CAAC,kBAAkB,OAAO,KAAA;CAC3C,IAAI;EAEF,QAAO,MADe,SAAS,QAAQ,EAAE,IAAI,iBAAiB,CAAC,EAAA,EAC/C,kB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QAAQ,KAAK,iEAAiE,EAC5E,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC9D,CAAC;CACH;CACA,IAAI,KAAK,gBACP,IAAI;EACF,MAAM,QAAQ,MAAM,OAAO,EAAE,SAAS,KAAK,eAAe,CAAC;CAC7D,SAAS,OAAO;EACd,QAAQ,KAAK,yDAAyD;GACpE,SAAS,KAAK;GACd,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;AAEJ"}
|
|
1
|
+
{"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { resolveProviderOMDefault } from '@mastra/code-sdk/onboarding/packs';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { factoryMemorySettingsUserId } from '../storage/domains/memory-settings/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { applyStoredMemorySettings } from './memory-settings-hydration.js';\nimport { seedSessionOrg } from './org-seed.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\n/**\n * Read the factory project's default model. Best-effort: a missing project or an\n * uninitialized storage domain means \"no default\", never a failed run.\n */\nexport async function resolveFactoryDefaultModelId(\n projects: FactoryProjectsStorage | undefined,\n factoryProjectId: string | undefined,\n): Promise<string | undefined> {\n if (!projects || !factoryProjectId) return undefined;\n try {\n const project = await projects.getById({ id: factoryProjectId });\n return project?.defaultModelId ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolveFactorySourceRepository}. A miss carries which step\n * failed: callers differ on whether that is an error (an autonomous run cannot\n * proceed) or a routine fallback (a chat integration drops to a chat-only\n * session), and the two steps fail for different reasons worth reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * Resolve which repository a factory project's source-control runs act on: the\n * owner's connection on the project, then one of its linked repositories.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolveFactorySourceRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, repositorySlug } = args;\n\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const candidates = connections.filter(candidate => candidate.integrationId === sourceControl.integrationId);\n if (candidates.length === 0) return { found: false, reason: 'connection' };\n\n // A project can carry stale connections: a provider-app reinstall leaves the\n // old connection pointing at an installation that no longer exists, and that\n // row can sit ahead of the healthy one. Try every candidate and skip the ones\n // that no longer resolve rather than failing on the first.\n for (const connection of candidates) {\n let resolved;\n try {\n const projectRepositories = await sourceControl.projectRepositories.list({ orgId, connectionId: connection.id });\n const resolvedRepositories = await Promise.all(\n projectRepositories.map(async projectRepository => ({\n projectRepository,\n repository: await sourceControl.repositories.get({ orgId, id: projectRepository.repositoryId }),\n })),\n );\n resolved = resolvedRepositories.find(\n candidate => candidate.repository && (!repositorySlug || candidate.repository.slug === repositorySlug),\n );\n } catch {\n // The connection no longer resolves (e.g. its installation was deleted).\n continue;\n }\n if (!resolved?.repository) continue;\n\n return {\n found: true,\n projectRepositoryId: resolved.projectRepository.id,\n baseBranch: resolved.projectRepository.branch ?? resolved.repository.defaultBranch,\n connectedByUserId: connection.createdByUserId,\n };\n }\n\n return { found: false, reason: 'repository' };\n}\n\n/**\n * Walk a Factory user-session id back to the project it belongs to.\n *\n * Repo-backed channel threads are keyed by their Factory session id, which is\n * the only handle a session-start hook gets. This turns that id back into the\n * project whose configuration the session should adopt. Durable by\n * construction — it reads the same rows the session was created from, so it\n * survives restarts without any in-memory mapping.\n */\nexport async function resolveFactoryProjectForSession(args: {\n sourceControl: SourceControlStorageHandle;\n sessionId: string;\n}): Promise<{ factoryProjectId: string; orgId: string; userId: string } | null> {\n const { sourceControl, sessionId } = args;\n\n const session = await sourceControl.sessions.getBySessionId(sessionId);\n if (!session) return null;\n const projectRepository = await sourceControl.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) return null;\n const connection = await sourceControl.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n if (!connection) return null;\n\n return { factoryProjectId: connection.factoryProjectId, orgId: session.orgId, userId: session.userId };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, one of\n * its linked repositories, and a session on the requested branch with the\n * repository's pinned or default branch as the base.\n *\n * The run is attributed to `attributeToUserId` when the caller has an\n * interactive user (e.g. the approver of a proposed run), and otherwise falls\n * back to whoever connected the repository (`connection.createdByUserId`),\n * because a genuinely autonomous run has no interactive user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, repositorySlug } = args;\n\n const resolved = await resolveFactorySourceRepository({ sourceControl, orgId, factoryProjectId, repositorySlug });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n const session = await sourceControl.sessions.create({\n sessionId: randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n orgId,\n userId,\n branch,\n baseBranch: resolved.baseBranch,\n visibility: 'org',\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n /**\n * The factory project whose shared memory settings apply. Factory sessions\n * never read an individual user's personal memory settings — the project's\n * own row (or the built-in defaults) is what they run with.\n */\n factoryProjectId?: string;\n /** The factory project's default model. Without it the session keeps the SDK's built-in mode default. */\n defaultModelId?: string;\n /**\n * When provided, the factory project's stored memory-settings row is\n * applied. When omitted (or no row exists) the session is reset to the\n * built-in memory defaults.\n */\n memorySettings?: MemorySettingsStorage;\n}\n\n/**\n * Apply a factory project's configuration to a freshly created session:\n * observational-memory settings, then the project's default model.\n *\n * Both steps are best-effort. A retired model id or an unreachable settings row\n * must not sink a run that is otherwise ready — the session simply keeps the\n * default it was created with, and the reason is logged.\n */\nexport async function hydrateFactorySession(session: FactorySession, args: HydrateFactorySessionArgs): Promise<void> {\n // The org rung knowledge curation scopes on. Seeded first so it lands even if\n // a later best-effort step fails; an empty org marks the session unresolved.\n await seedSessionOrg(session, args.orgId);\n try {\n const record =\n args.memorySettings && args.factoryProjectId\n ? await args.memorySettings.get({\n orgId: args.orgId,\n userId: factoryMemorySettingsUserId(args.factoryProjectId),\n })\n : null;\n // Without a stored row, fall back to the low-cost OM model of the factory\n // default model's provider — a factory connected only to Anthropic should\n // not observe with the (uncredentialed) built-in Google default.\n const provider = args.defaultModelId?.split('/')[0];\n const fallbackOmModelId = provider ? resolveProviderOMDefault(provider, args.defaultModelId).modelId : undefined;\n await applyStoredMemorySettings(session, record, fallbackOmModelId);\n } catch (error) {\n console.warn('[Factory Start] Failed to apply observational-memory settings', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (args.defaultModelId) {\n try {\n await session.model.switch({ modelId: args.defaultModelId });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply factory default model', {\n modelId: args.defaultModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAmBA,eAAsB,6BACpB,UACA,kBAC6B;CAC7B,IAAI,CAAC,YAAY,CAAC,kBAAkB,OAAO,KAAA;CAC3C,IAAI;EAEF,QAAO,MADe,SAAS,QAAQ,EAAE,IAAI,iBAAiB,CAAC,EAAA,EAC/C,kBAAkB,KAAA;CACpC,QAAQ;EACN;CACF;AACF;AA8BA,IAAa,sCAAb,cAAyD,MAAM;CACxC;CAArB,YAAY,QAA8C;EACxD,MACE,WAAW,eACP,iDACA,8CACN;EALmB,KAAA,SAAA;EAMnB,KAAK,OAAO;CACd;AACF;;;;;;;;AA2BA,eAAsB,+BAA+B,MAMV;CACzC,MAAM,EAAE,eAAe,OAAO,kBAAkB,mBAAmB;CAGnE,MAAM,cAAa,MADO,cAAc,YAAY,KAAK;EAAE;EAAO;CAAiB,CAAC,EAAA,CACrD,QAAO,cAAa,UAAU,kBAAkB,cAAc,aAAa;CAC1G,I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blocking session-created listener so the seed lands before the caller can
|
|
63
63
|
* start a run.
|
|
64
64
|
*
|
|
65
|
-
* The org seed matters beyond settings. Subconscious knowledge
|
|
65
|
+
* The org seed matters beyond settings. Subconscious knowledge curation scopes
|
|
66
66
|
* every node and record on `factoryOrgId`; before the SDK refusal guard,
|
|
67
|
-
* missing it made
|
|
68
|
-
* that is the agent controller's own id rather than a tenant, so
|
|
67
|
+
* missing it made curation substitute the session owner id. For web chat sessions
|
|
68
|
+
* that is the agent controller's own id rather than a tenant, so curated
|
|
69
69
|
* knowledge landed under an org rung no reader ever queries. Same rule as the
|
|
70
70
|
* start coordinator: the org
|
|
71
71
|
* comes from the row the session was created from, never improvised from an
|
|
@@ -34,10 +34,10 @@ async function applyStoredMemorySettings(session, record, fallbackOmModelId) {
|
|
|
34
34
|
* as a blocking session-created listener so the seed lands before the caller can
|
|
35
35
|
* start a run.
|
|
36
36
|
*
|
|
37
|
-
* The org seed matters beyond settings. Subconscious knowledge
|
|
37
|
+
* The org seed matters beyond settings. Subconscious knowledge curation scopes
|
|
38
38
|
* every node and record on `factoryOrgId`; before the SDK refusal guard,
|
|
39
|
-
* missing it made
|
|
40
|
-
* that is the agent controller's own id rather than a tenant, so
|
|
39
|
+
* missing it made curation substitute the session owner id. For web chat sessions
|
|
40
|
+
* that is the agent controller's own id rather than a tenant, so curated
|
|
41
41
|
* knowledge landed under an org rung no reader ever queries. Same rule as the
|
|
42
42
|
* start coordinator: the org
|
|
43
43
|
* comes from the row the session was created from, never improvised from an
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory-settings-hydration.js","names":[],"sources":["../../src/session/memory-settings-hydration.ts"],"sourcesContent":["import { DEFAULT_OM_MODEL_ID } from '@mastra/code-sdk/constants';\n\nimport type { MemorySettingsRecord, MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { hasResolvedOrg, seedSessionOrg } from './org-seed.js';\n\n/** Default thresholds mirror the TUI `/om` fallbacks. */\nexport const DEFAULT_OBSERVATION_THRESHOLD = 30_000;\nexport const DEFAULT_REFLECTION_THRESHOLD = 40_000;\n\n/** One observational-memory role's read/switch surface. */\ninterface OMRoleSlice {\n modelId: () => string | undefined;\n switchModel: (args: { modelId: string }) => Promise<unknown>;\n}\n\n/**\n * Session-state fields memory-settings hydration writes. The index signatures\n * mirror `MastraCodeState` so the concrete `Session.state.set(Partial<MastraCodeState>)`\n * stays assignable to this minimal surface (contravariant parameter check).\n */\ninterface OMStateWrites {\n [key: string]: unknown;\n [key: `subagentModelId_${string}`]: string | undefined;\n observationThreshold?: number;\n reflectionThreshold?: number;\n observeAttachments?: 'auto' | boolean;\n factoryOrgId?: string;\n}\n\n/** The slice of a session needed to apply stored observational-memory settings. */\nexport interface OMConfigurableSession {\n om: { observer: OMRoleSlice; reflector: OMRoleSlice };\n state: {\n get: () => Record<string, unknown> | undefined;\n set: (updates: OMStateWrites) => Promise<void> | void;\n };\n}\n\n/**\n * Apply a stored memory-settings row onto a session, so the DB — not whatever\n * happens to sit in persisted session state (e.g. a stale boot-time seed from\n * before memory settings moved to the DB) — is what the web surface reads and\n * what the session's OM actually runs with. The row is authoritative: knobs\n * without a stored value reset to the built-in defaults. This is the single\n * application path shared by the settings routes, coordinator hydration, and\n * the web session boot seed.\n */\nexport async function applyStoredMemorySettings(\n session: OMConfigurableSession,\n record: MemorySettingsRecord | null,\n fallbackOmModelId?: string,\n): Promise<void> {\n for (const role of ['observer', 'reflector'] as const) {\n const stored = role === 'observer' ? record?.observerModelId : record?.reflectorModelId;\n const target = stored ?? fallbackOmModelId ?? DEFAULT_OM_MODEL_ID;\n if (session.om[role].modelId() !== target) {\n await session.om[role].switchModel({ modelId: target });\n }\n }\n const state = session.state.get() ?? {};\n const updates: OMStateWrites = {};\n const observationThreshold = record?.observationThreshold ?? DEFAULT_OBSERVATION_THRESHOLD;\n if (state.observationThreshold !== observationThreshold) {\n updates.observationThreshold = observationThreshold;\n }\n const reflectionThreshold = record?.reflectionThreshold ?? DEFAULT_REFLECTION_THRESHOLD;\n if (state.reflectionThreshold !== reflectionThreshold) {\n updates.reflectionThreshold = reflectionThreshold;\n }\n const observeAttachments = record?.observeAttachments ?? 'auto';\n if ((state.observeAttachments ?? 'auto') !== observeAttachments) {\n updates.observeAttachments = observeAttachments;\n }\n if (Object.keys(updates).length > 0) await session.state.set(updates);\n}\n\nexport interface MemorySettingsHydrationSession extends OMConfigurableSession {\n readonly identity: { getResourceId(): string };\n}\n\nexport interface MemorySettingsHydrationDependencies {\n /** GitHub-integration source-control rows — the only creator of web user sessions today. */\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n memorySettings: Pick<MemorySettingsStorage, 'get'>;\n}\n\n/**\n * Seed a freshly created controller session's tenant org and its\n * observational-memory settings from the owner's source-control row. Registered\n * as a blocking session-created listener so the seed lands before the caller can\n * start a run.\n *\n * The org seed matters beyond settings. Subconscious knowledge
|
|
1
|
+
{"version":3,"file":"memory-settings-hydration.js","names":[],"sources":["../../src/session/memory-settings-hydration.ts"],"sourcesContent":["import { DEFAULT_OM_MODEL_ID } from '@mastra/code-sdk/constants';\n\nimport type { MemorySettingsRecord, MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { hasResolvedOrg, seedSessionOrg } from './org-seed.js';\n\n/** Default thresholds mirror the TUI `/om` fallbacks. */\nexport const DEFAULT_OBSERVATION_THRESHOLD = 30_000;\nexport const DEFAULT_REFLECTION_THRESHOLD = 40_000;\n\n/** One observational-memory role's read/switch surface. */\ninterface OMRoleSlice {\n modelId: () => string | undefined;\n switchModel: (args: { modelId: string }) => Promise<unknown>;\n}\n\n/**\n * Session-state fields memory-settings hydration writes. The index signatures\n * mirror `MastraCodeState` so the concrete `Session.state.set(Partial<MastraCodeState>)`\n * stays assignable to this minimal surface (contravariant parameter check).\n */\ninterface OMStateWrites {\n [key: string]: unknown;\n [key: `subagentModelId_${string}`]: string | undefined;\n observationThreshold?: number;\n reflectionThreshold?: number;\n observeAttachments?: 'auto' | boolean;\n factoryOrgId?: string;\n}\n\n/** The slice of a session needed to apply stored observational-memory settings. */\nexport interface OMConfigurableSession {\n om: { observer: OMRoleSlice; reflector: OMRoleSlice };\n state: {\n get: () => Record<string, unknown> | undefined;\n set: (updates: OMStateWrites) => Promise<void> | void;\n };\n}\n\n/**\n * Apply a stored memory-settings row onto a session, so the DB — not whatever\n * happens to sit in persisted session state (e.g. a stale boot-time seed from\n * before memory settings moved to the DB) — is what the web surface reads and\n * what the session's OM actually runs with. The row is authoritative: knobs\n * without a stored value reset to the built-in defaults. This is the single\n * application path shared by the settings routes, coordinator hydration, and\n * the web session boot seed.\n */\nexport async function applyStoredMemorySettings(\n session: OMConfigurableSession,\n record: MemorySettingsRecord | null,\n fallbackOmModelId?: string,\n): Promise<void> {\n for (const role of ['observer', 'reflector'] as const) {\n const stored = role === 'observer' ? record?.observerModelId : record?.reflectorModelId;\n const target = stored ?? fallbackOmModelId ?? DEFAULT_OM_MODEL_ID;\n if (session.om[role].modelId() !== target) {\n await session.om[role].switchModel({ modelId: target });\n }\n }\n const state = session.state.get() ?? {};\n const updates: OMStateWrites = {};\n const observationThreshold = record?.observationThreshold ?? DEFAULT_OBSERVATION_THRESHOLD;\n if (state.observationThreshold !== observationThreshold) {\n updates.observationThreshold = observationThreshold;\n }\n const reflectionThreshold = record?.reflectionThreshold ?? DEFAULT_REFLECTION_THRESHOLD;\n if (state.reflectionThreshold !== reflectionThreshold) {\n updates.reflectionThreshold = reflectionThreshold;\n }\n const observeAttachments = record?.observeAttachments ?? 'auto';\n if ((state.observeAttachments ?? 'auto') !== observeAttachments) {\n updates.observeAttachments = observeAttachments;\n }\n if (Object.keys(updates).length > 0) await session.state.set(updates);\n}\n\nexport interface MemorySettingsHydrationSession extends OMConfigurableSession {\n readonly identity: { getResourceId(): string };\n}\n\nexport interface MemorySettingsHydrationDependencies {\n /** GitHub-integration source-control rows — the only creator of web user sessions today. */\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId'>;\n };\n memorySettings: Pick<MemorySettingsStorage, 'get'>;\n}\n\n/**\n * Seed a freshly created controller session's tenant org and its\n * observational-memory settings from the owner's source-control row. Registered\n * as a blocking session-created listener so the seed lands before the caller can\n * start a run.\n *\n * The org seed matters beyond settings. Subconscious knowledge curation scopes\n * every node and record on `factoryOrgId`; before the SDK refusal guard,\n * missing it made curation substitute the session owner id. For web chat sessions\n * that is the agent controller's own id rather than a tenant, so curated\n * knowledge landed under an org rung no reader ever queries. Same rule as the\n * start coordinator: the org\n * comes from the row the session was created from, never improvised from an\n * owner id.\n *\n * Memory settings for sessions tagged `factoryProjectId` (work/review runs) are\n * owned by the start coordinator, and sessions without a GitHub source-control\n * row (e.g. chat-only channel sessions) hydrate through `hydrateFactorySession`\n * with their own resolved tenant; both are skipped here. The org seed is not\n * skipped on the tag alone: a web chat session persists `factoryProjectId` from\n * its browser seed, so on resume it carries the tag without ever having been\n * through the coordinator. Best-effort: failures are logged, never thrown.\n */\nexport async function hydrateSessionMemorySettings(\n session: MemorySettingsHydrationSession,\n { sourceControl, memorySettings }: MemorySettingsHydrationDependencies,\n): Promise<void> {\n const state = session.state.get() ?? {};\n const isFactoryRun = Boolean(state.factoryProjectId);\n // A coordinator-hydrated run already carries both halves. Nothing to add.\n if (isFactoryRun && hasResolvedOrg(state.factoryOrgId)) return;\n try {\n const record = await sourceControl.sessions.getBySessionId(session.identity.getResourceId());\n // No row, or a row whose org is blank, leaves the session with no tenant.\n // Mark it rather than returning silently: an unmarked projectless factory\n // session is indistinguishable from a local one, and curation would file it\n // under the local scope — the same bug wearing a different rung.\n await seedSessionOrg(session, record?.orgId);\n if (!record) return;\n if (isFactoryRun) return;\n const settings = await memorySettings.get({ orgId: record.orgId, userId: record.userId });\n await applyStoredMemorySettings(session, settings);\n } catch (error) {\n console.warn('[Factory memory-settings hydration] Unable to apply stored memory settings.', error);\n // A failed lookup is an unresolved org, not an absent one — unless the seed\n // already landed and a later step is what threw.\n if (!session.state.get()?.factoryOrgId) await seedSessionOrg(session, undefined);\n }\n}\n"],"mappings":";;;;AAOA,MAAa,gCAAgC;AAC7C,MAAa,+BAA+B;;;;;;;;;;AAwC5C,eAAsB,0BACpB,SACA,QACA,mBACe;CACf,KAAK,MAAM,QAAQ,CAAC,YAAY,WAAW,GAAY;EAErD,MAAM,UADS,SAAS,aAAa,QAAQ,kBAAkB,QAAQ,qBAC9C,qBAAqB;EAC9C,IAAI,QAAQ,GAAG,KAAK,CAAC,QAAQ,MAAM,QACjC,MAAM,QAAQ,GAAG,KAAK,CAAC,YAAY,EAAE,SAAS,OAAO,CAAC;CAE1D;CACA,MAAM,QAAQ,QAAQ,MAAM,IAAI,KAAK,CAAC;CACtC,MAAM,UAAyB,CAAC;CAChC,MAAM,uBAAuB,QAAQ,wBAAA;CACrC,IAAI,MAAM,yBAAyB,sBACjC,QAAQ,uBAAuB;CAEjC,MAAM,sBAAsB,QAAQ,uBAAA;CACpC,IAAI,MAAM,wBAAwB,qBAChC,QAAQ,sBAAsB;CAEhC,MAAM,qBAAqB,QAAQ,sBAAsB;CACzD,KAAK,MAAM,sBAAsB,YAAY,oBAC3C,QAAQ,qBAAqB;CAE/B,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,GAAG,MAAM,QAAQ,MAAM,IAAI,OAAO;AACtE;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,eAAsB,6BACpB,SACA,EAAE,eAAe,kBACF;CACf,MAAM,QAAQ,QAAQ,MAAM,IAAI,KAAK,CAAC;CACtC,MAAM,eAAe,QAAQ,MAAM,gBAAgB;CAEnD,IAAI,gBAAgB,eAAe,MAAM,YAAY,GAAG;CACxD,IAAI;EACF,MAAM,SAAS,MAAM,cAAc,SAAS,eAAe,QAAQ,SAAS,cAAc,CAAC;EAK3F,MAAM,eAAe,SAAS,QAAQ,KAAK;EAC3C,IAAI,CAAC,QAAQ;EACb,IAAI,cAAc;EAElB,MAAM,0BAA0B,SAAS,MADlB,eAAe,IAAI;GAAE,OAAO,OAAO;GAAO,QAAQ,OAAO;EAAO,CAAC,CACvC;CACnD,SAAS,OAAO;EACd,QAAQ,KAAK,+EAA+E,KAAK;EAGjG,IAAI,CAAC,QAAQ,MAAM,IAAI,CAAC,EAAE,cAAc,MAAM,eAAe,SAAS,KAAA,CAAS;CACjF;AACF"}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The tenant organization a session's knowledge is scoped to.
|
|
3
3
|
*
|
|
4
|
-
* Subconscious knowledge
|
|
5
|
-
* `factoryOrgId`. A session that reaches the
|
|
4
|
+
* Subconscious knowledge curation scopes every node and record on
|
|
5
|
+
* `factoryOrgId`. A session that reaches the curation seam without one used to
|
|
6
6
|
* fall back to the session owner id — for factory sessions the agent
|
|
7
7
|
* controller's own id — so the knowledge landed under an org rung no reader
|
|
8
8
|
* ever queries. The write succeeded and the read could never see it.
|
|
9
9
|
*
|
|
10
10
|
* The fix is that every session-creation path seeds the org it already holds,
|
|
11
11
|
* and a path that cannot resolve one marks the session `factoryOrgUnresolved`
|
|
12
|
-
* so the
|
|
12
|
+
* so the curation side refuses loudly instead of inventing an identity. "No
|
|
13
13
|
* project id" is not a proxy for "not a factory session" — chat sessions and
|
|
14
14
|
* Slack channel sessions are factory-owned and carry no project id — which is
|
|
15
15
|
* why the unresolved case needs its own explicit marker.
|
|
@@ -45,9 +45,9 @@ export declare function readRequestContextOrgId(requestContext: OrgBearingReques
|
|
|
45
45
|
/**
|
|
46
46
|
* Whether a session state value counts as a resolved organization.
|
|
47
47
|
*
|
|
48
|
-
* The
|
|
48
|
+
* The curation side trims before deciding (`sdk/src/agents/memory.ts`), so the
|
|
49
49
|
* recovery guards have to agree with it: a whitespace-only value that reads as
|
|
50
|
-
* truthy here would look resolved to a heal path while
|
|
50
|
+
* truthy here would look resolved to a heal path while curation still refuses,
|
|
51
51
|
* and nothing would ever repair it. Not every seam routes its seed through
|
|
52
52
|
* `seedSessionOrg`, so this cannot be assumed away.
|
|
53
53
|
*/
|
package/dist/session/org-seed.js
CHANGED
|
@@ -10,9 +10,9 @@ function readRequestContextOrgId(requestContext) {
|
|
|
10
10
|
/**
|
|
11
11
|
* Whether a session state value counts as a resolved organization.
|
|
12
12
|
*
|
|
13
|
-
* The
|
|
13
|
+
* The curation side trims before deciding (`sdk/src/agents/memory.ts`), so the
|
|
14
14
|
* recovery guards have to agree with it: a whitespace-only value that reads as
|
|
15
|
-
* truthy here would look resolved to a heal path while
|
|
15
|
+
* truthy here would look resolved to a heal path while curation still refuses,
|
|
16
16
|
* and nothing would ever repair it. Not every seam routes its seed through
|
|
17
17
|
* `seedSessionOrg`, so this cannot be assumed away.
|
|
18
18
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"org-seed.js","names":[],"sources":["../../src/session/org-seed.ts"],"sourcesContent":["/**\n * The tenant organization a session's knowledge is scoped to.\n *\n * Subconscious knowledge
|
|
1
|
+
{"version":3,"file":"org-seed.js","names":[],"sources":["../../src/session/org-seed.ts"],"sourcesContent":["/**\n * The tenant organization a session's knowledge is scoped to.\n *\n * Subconscious knowledge curation scopes every node and record on\n * `factoryOrgId`. A session that reaches the curation seam without one used to\n * fall back to the session owner id — for factory sessions the agent\n * controller's own id — so the knowledge landed under an org rung no reader\n * ever queries. The write succeeded and the read could never see it.\n *\n * The fix is that every session-creation path seeds the org it already holds,\n * and a path that cannot resolve one marks the session `factoryOrgUnresolved`\n * so the curation side refuses loudly instead of inventing an identity. \"No\n * project id\" is not a proxy for \"not a factory session\" — chat sessions and\n * Slack channel sessions are factory-owned and carry no project id — which is\n * why the unresolved case needs its own explicit marker.\n */\n\n/**\n * Session-state fields org seeding writes. The index signatures mirror\n * `MastraCodeState` so a concrete `Session.state.set(Partial<MastraCodeState>)`\n * stays assignable to this minimal surface (contravariant parameter check).\n */\nexport interface OrgSeedStateWrites {\n [key: string]: unknown;\n [key: `subagentModelId_${string}`]: string | undefined;\n factoryOrgId?: string;\n factoryOrgUnresolved?: boolean;\n}\n\n/** The slice of a session needed to seed its organization. */\nexport interface OrgSeedableSession {\n state: {\n get: () => Record<string, unknown> | undefined;\n set: (updates: OrgSeedStateWrites) => Promise<void> | void;\n };\n}\n\n/**\n * A request context carrying the tenant on its `user` key. Slack stamps\n * `{ id, organizationId }` and the GitHub webhook `{ workosId, organizationId }`,\n * so only the shared `organizationId` field may be read here.\n */\nexport interface OrgBearingRequestContext {\n get: (key: string) => unknown;\n}\n\n/** Read the tenant org off a request context's `user` key, if there is one. */\nexport function readRequestContextOrgId(requestContext: OrgBearingRequestContext | undefined): string | undefined {\n if (!requestContext) return undefined;\n const user = requestContext.get('user');\n if (!user || typeof user !== 'object') return undefined;\n const orgId = (user as { organizationId?: unknown }).organizationId;\n return typeof orgId === 'string' ? orgId : undefined;\n}\n\n/**\n * Whether a session state value counts as a resolved organization.\n *\n * The curation side trims before deciding (`sdk/src/agents/memory.ts`), so the\n * recovery guards have to agree with it: a whitespace-only value that reads as\n * truthy here would look resolved to a heal path while curation still refuses,\n * and nothing would ever repair it. Not every seam routes its seed through\n * `seedSessionOrg`, so this cannot be assumed away.\n */\nexport function hasResolvedOrg(orgId: unknown): boolean {\n return typeof orgId === 'string' && orgId.trim().length > 0;\n}\n\n/**\n * Seed the session's organization, or mark it unresolved when there is none.\n *\n * An absent, empty, or whitespace-only org is a refusal, not a fallback: a\n * blank org rung is not something canonicalization can save. A successful\n * resolve also clears a stale marker, because the session-start hook runs at\n * most once per session per process and nothing else would ever clear it.\n *\n * Best-effort by contract — every caller is a session-created listener that\n * must not sink a run that is otherwise ready.\n */\nexport async function seedSessionOrg(session: OrgSeedableSession, orgId: string | null | undefined): Promise<void> {\n const resolved = typeof orgId === 'string' ? orgId.trim() : '';\n // Some session shapes (approval stubs, lightweight doubles) carry no state at\n // all. There is nothing to seed and nothing to mark, so this is not a warning.\n if (typeof session.state?.get !== 'function' || typeof session.state?.set !== 'function') return;\n try {\n const state = session.state.get() ?? {};\n if (!resolved) {\n if (state.factoryOrgUnresolved !== true) {\n await session.state.set({ factoryOrgUnresolved: true });\n }\n return;\n }\n const updates: OrgSeedStateWrites = {};\n if (state.factoryOrgId !== resolved) updates.factoryOrgId = resolved;\n if (state.factoryOrgUnresolved) updates.factoryOrgUnresolved = false;\n if (Object.keys(updates).length > 0) await session.state.set(updates);\n } catch (error) {\n console.warn('[Factory org seed] Unable to record the session organization.', error);\n }\n}\n"],"mappings":";;AA+CA,SAAgB,wBAAwB,gBAA0E;CAChH,IAAI,CAAC,gBAAgB,OAAO,KAAA;CAC5B,MAAM,OAAO,eAAe,IAAI,MAAM;CACtC,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO,KAAA;CAC9C,MAAM,QAAS,KAAsC;CACrD,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;;;;;;;;;AAWA,SAAgB,eAAe,OAAyB;CACtD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS;AAC5D;;;;;;;;;;;;AAaA,eAAsB,eAAe,SAA6B,OAAiD;CACjH,MAAM,WAAW,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;CAG5D,IAAI,OAAO,QAAQ,OAAO,QAAQ,cAAc,OAAO,QAAQ,OAAO,QAAQ,YAAY;CAC1F,IAAI;EACF,MAAM,QAAQ,QAAQ,MAAM,IAAI,KAAK,CAAC;EACtC,IAAI,CAAC,UAAU;GACb,IAAI,MAAM,yBAAyB,MACjC,MAAM,QAAQ,MAAM,IAAI,EAAE,sBAAsB,KAAK,CAAC;GAExD;EACF;EACA,MAAM,UAA8B,CAAC;EACrC,IAAI,MAAM,iBAAiB,UAAU,QAAQ,eAAe;EAC5D,IAAI,MAAM,sBAAsB,QAAQ,uBAAuB;EAC/D,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,GAAG,MAAM,QAAQ,MAAM,IAAI,OAAO;CACtE,SAAS,OAAO;EACd,QAAQ,KAAK,iEAAiE,KAAK;CACrF;AACF"}
|
|
@@ -320,6 +320,8 @@ export interface CommitFactoryTransitionInput {
|
|
|
320
320
|
consentedBy?: string;
|
|
321
321
|
/** Triage classification reported by an authenticated triage binding. */
|
|
322
322
|
triageType?: FactoryTriageType;
|
|
323
|
+
/** Record the person's acceptance of this item in the same revision-checked update; a no-op once set. */
|
|
324
|
+
accept?: boolean;
|
|
323
325
|
}
|
|
324
326
|
export type CommitFactoryTransitionResult = {
|
|
325
327
|
status: 'committed';
|
|
@@ -388,6 +390,12 @@ export interface WorkItemRow {
|
|
|
388
390
|
* parked plans even while the project's Auto-approve plans switch is off.
|
|
389
391
|
*/
|
|
390
392
|
plansPreapprovedAt: Date | null;
|
|
393
|
+
/**
|
|
394
|
+
* When a person first moved this item out of Intake/Triage into working
|
|
395
|
+
* stages. Non-bug items wait for that gesture; once it is recorded the
|
|
396
|
+
* agents may advance the item through Planning and Execute on their own.
|
|
397
|
+
*/
|
|
398
|
+
acceptedAt: Date | null;
|
|
391
399
|
/** Denormalized feed counters, maintained by the comments domain via recount. */
|
|
392
400
|
commentCount: number;
|
|
393
401
|
/** Bumps on every feed mutation (create/edit/delete) — the clients' change hint. */
|