@mastra/factory 0.26.0-alpha.1 → 0.26.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/environment/build.d.ts +1 -1
  2. package/dist/environment/build.d.ts.map +1 -1
  3. package/dist/environment/build.js +2 -0
  4. package/dist/environment/build.js.map +1 -1
  5. package/dist/factory.d.ts.map +1 -1
  6. package/dist/factory.js +2 -2
  7. package/dist/factory.js.map +1 -1
  8. package/dist/integrations/github/integration.d.ts +5 -4
  9. package/dist/integrations/github/integration.d.ts.map +1 -1
  10. package/dist/integrations/github/integration.js +10 -8
  11. package/dist/integrations/github/integration.js.map +1 -1
  12. package/dist/integrations/github/sandbox.d.ts +2 -2
  13. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  14. package/dist/integrations/github/sandbox.js +6 -1
  15. package/dist/integrations/github/sandbox.js.map +1 -1
  16. package/dist/integrations/platform/github/integration.d.ts +5 -0
  17. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  18. package/dist/integrations/platform/github/integration.js +7 -0
  19. package/dist/integrations/platform/github/integration.js.map +1 -1
  20. package/dist/routes/surface.d.ts.map +1 -1
  21. package/dist/routes/surface.js +1 -0
  22. package/dist/routes/surface.js.map +1 -1
  23. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  24. package/dist/rules/dispatch-errors.js +4 -0
  25. package/dist/rules/dispatch-errors.js.map +1 -1
  26. package/dist/sandbox/local-factory-sandbox.d.ts +4 -1
  27. package/dist/sandbox/local-factory-sandbox.d.ts.map +1 -1
  28. package/dist/sandbox/local-factory-sandbox.js +1 -1
  29. package/dist/sandbox/local-factory-sandbox.js.map +1 -1
  30. package/dist/storage/domains/work-items/base.d.ts +2 -2
  31. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  32. package/dist/storage/domains/work-items/base.js +1 -0
  33. package/dist/storage/domains/work-items/base.js.map +1 -1
  34. package/dist/workspace.d.ts +2 -0
  35. package/dist/workspace.d.ts.map +1 -1
  36. package/dist/workspace.js +13 -4
  37. package/dist/workspace.js.map +1 -1
  38. package/package.json +6 -6
@@ -57,7 +57,7 @@ export declare function errorReason(error: unknown): string;
57
57
  * session id, with heads served from `heads` so the provider never resolves
58
58
  * them itself.
59
59
  */
60
- export declare function environmentBuildContext(project: Pick<FactoryProject, 'id' | 'orgId'>, environment: SessionEnvironment, heads: EnvironmentHeads, versionControl: Pick<VersionControl, 'getRepositoryAccess'>): FactorySandboxContext;
60
+ export declare function environmentBuildContext(project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>, environment: SessionEnvironment, heads: EnvironmentHeads, versionControl: Pick<VersionControl, 'getRepositoryAccess'>): FactorySandboxContext;
61
61
  /**
62
62
  * Fingerprint of everything a build bakes into the template besides the
63
63
  * repository heads: provider settings, the repositories and their order,
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/environment/build.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClG,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,eAAO,MAAM,0BAA0B,YAAI,QAAQ,EAAE,UAAU,EAAE,MAAM,CAAU,CAAC;AAClF,MAAM,MAAM,uBAAuB,GAAG,CAAC,OAAO,0BAA0B,CAAC,CAAC,MAAM,CAAC,CAAC;AAElF,MAAM,WAAW,6BAA6B;IAC5C,OAAO,EAAE,IAAI,CAAC,0BAA0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AC1F,KAAK,CAAC,EAAE,gBAAgB,CAAC;CAC1B;AAED,8EAA8E;AAC9E,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAEnE;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED,kFAAkF;AAClF,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAElD;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,IAAI,GAAG,OAAO,GAAG,MAAM,CAAC,EACtD,WAAW,EAAE,kBAAkB,EAC/B,KAAK,EAAE,gBAAgB,EACvB,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,qBAAqB,CAAC,GAC1D,qBAAqB,CAWvB;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,kBAAkB,GAAG,MAAM,CAY9E;AAED;;;;;GAKG;AACH,wBAAsB,uBAAuB,CAC3C,aAAa,EAAE,6BAA6B,EAC5C,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,CAAC,EACtC,WAAW,EAAE,kBAAkB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAS3B;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,QAAc,CAAC;AAKhD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,oBAAoB,EAC1B,KAAK,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,uBAAuB,CAAA;CAAE,GAC7D,OAAO,CAAC,uBAAuB,CAAC,CA4LlC"}
@@ -39,6 +39,8 @@ function errorReason(error) {
39
39
  function environmentBuildContext(project, environment, heads, versionControl) {
40
40
  return {
41
41
  sessionId: environmentBuildSessionId(project.id),
42
+ factoryId: project.id,
43
+ factoryName: project.name,
42
44
  ...environmentSandboxContext(environment, {
43
45
  orgId: project.orgId,
44
46
  getRepositoryAccess: (args) => versionControl.getRepositoryAccess(args),
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","names":[],"sources":["../../src/environment/build.ts"],"sourcesContent":["/**\n * One proactive environment build: decide whether a trigger should build,\n * hand the sandbox's `builds` capability a context identical to a session's,\n * and record the started build on the project row. Polling the build to its\n * end and pinning the active template is the workflow's second step\n * (`build-workflow.ts`), so a request that only needs the start answer never\n * waits on the provider.\n */\n\nimport { createHash, randomUUID } from 'node:crypto';\n\nimport type { FactorySandbox, FactorySandboxContext } from '@mastra/core/workspace';\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { environmentSandboxContext, resolveProjectEnvironment } from '../workspace.js';\nimport type { SessionEnvironment } from '../workspace.js';\nimport { headsChanged, recordedHeadResolver, resolveCurrentHeads } from './heads.js';\nimport type { EnvironmentHeads } from './heads.js';\n\nexport const ENVIRONMENT_BUILD_TRIGGERS = ['manual', 'schedule', 'push'] as const;\nexport type EnvironmentBuildTrigger = (typeof ENVIRONMENT_BUILD_TRIGGERS)[number];\n\nexport interface EnvironmentBuildSourceControl {\n storage: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>;\n}\n\nexport interface EnvironmentBuildDeps {\n /** The factory's normalized sandbox; builds are unavailable without its `builds`. */\n sandbox: FactorySandbox | undefined;\n projects: Pick<\n FactoryProjectsStorage,\n 'getById' | 'claimBuildAttempt' | 'claimBuildStart' | 'renewBuildStart' | 'releaseBuildStart' | 'pinActiveTemplate'\n >;\n /** Absent when the factory has no source-control integration to resolve heads with. */\n sourceControl: EnvironmentBuildSourceControl | undefined;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n now?: () => Date;\n /** How often a run renews its build-start lease; a third of `BUILD_START_LEASE_MS` by default. */\n leaseRenewMs?: number;\n /** Waits between tries at recording a started build. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface EnvironmentBuildOutcome {\n outcome: 'started' | 'skipped' | 'unavailable' | 'failed';\n buildId?: string;\n templateId?: string;\n /** Why nothing started: `debounced`, `starting` (another run is starting a build), `in_progress`, `unchanged`, `unresolved` (a lapsed run may have started a build the provider cannot list), `no_environment`, `no_builds`, `no_source_control`; why a run failed: `not_recorded`, `superseded`, or an error. */\n reason?: string;\n /** The heads the started build pins; the workflow stores them once the build is ready. */\n heads?: EnvironmentHeads;\n}\n\n/** The synthetic session id a project's build runs under; never a session. */\nexport function environmentBuildSessionId(projectId: string): string {\n return `environment-build:${projectId}`;\n}\n\n/**\n * A build or setup error may echo a clone URL or a token; strip URL userinfo\n * and GitHub token shapes before the message is stored, logged or shown.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(/\\/\\/[^/\\s@]+@/g, '//***@').replace(/\\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]+/g, '***');\n}\n\n/** An error's message with credentials redacted, safe to log, store or return. */\nexport function errorReason(error: unknown): string {\n return redactCredentials(error instanceof Error ? error.message : String(error));\n}\n\n/**\n * The context an environment build (or a read of its status) hands the\n * provider: the same list form a session boots with, under the build's own\n * session id, with heads served from `heads` so the provider never resolves\n * them itself.\n */\nexport function environmentBuildContext(\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>,\n): FactorySandboxContext {\n return {\n sessionId: environmentBuildSessionId(project.id),\n ...environmentSandboxContext(environment, {\n orgId: project.orgId,\n getRepositoryAccess: args => versionControl.getRepositoryAccess(args),\n resolveHead: recordedHeadResolver(heads),\n }),\n };\n}\n\n/**\n * Fingerprint of everything a build bakes into the template besides the\n * repository heads: provider settings, the repositories and their order,\n * their setup commands, the workspace setup command and the working\n * directory. A schedule or push skips a ready build only while this matches.\n */\nexport function environmentBuildInputs(environment: SessionEnvironment): string {\n const inputs = {\n settings: environment.settings,\n workspaceSetupCommand: environment.workspaceSetupCommand ?? null,\n workingDirectory: environment.workingDirectory ?? null,\n repos: environment.repos.map(repo => ({\n repositoryId: repo.repositoryId,\n templateBranch: repo.templateBranch,\n setupCommand: repo.setupCommand ?? null,\n })),\n };\n return createHash('sha256').update(JSON.stringify(inputs)).digest('hex');\n}\n\n/**\n * The current head of every environment repository's template branch, keyed\n * by slug. The template clones the repository default branch (a link's own\n * branch is the session's base, checked out after boot), so that is the\n * branch a build pins; sessions let the provider resolve the same head.\n */\nexport async function resolveEnvironmentHeads(\n sourceControl: EnvironmentBuildSourceControl,\n project: Pick<FactoryProject, 'orgId'>,\n environment: SessionEnvironment,\n): Promise<EnvironmentHeads> {\n return resolveCurrentHeads(sourceControl, {\n orgId: project.orgId,\n repositories: environment.repos.map(repo => ({\n id: repo.repositoryId,\n slug: repo.slug,\n branch: repo.templateBranch,\n })),\n });\n}\n\n/**\n * How long a build-start lease lasts without renewal. The run holding it\n * renews it every third of that while it works, so a lease lapses only when\n * its run died or stalled.\n */\nexport const BUILD_START_LEASE_MS = 10 * 60_000;\n\n/** Tries at recording a started build before the run leaves its lease to lapse. */\nconst RECORD_ATTEMPTS = 5;\n\n/**\n * Start a build for `projectId` when `trigger` calls for one. Every trigger\n * takes the project's build-start lease before reading build state and renews\n * it until the started build is recorded, so overlapping manual, scheduled and\n * push runs never both start a build, however long the provider takes; a run\n * that finds the lease held skips as `starting`. Every trigger skips while the\n * last build is still running; `schedule` and `push` also skip when the last\n * build is ready and neither a head nor any other template input changed;\n * `manual` otherwise always builds. A `push` that would build then takes the\n * leading-edge debounce claim, so only a push that starts a build opens the\n * window. Saving settings never builds.\n *\n * Taking over a lapsed lease leaves the start uncertain: the lapsed run may\n * have started a build it never recorded. The mark persists until resolved.\n * While it stands, a provider that lists builds is asked for a running one\n * (and every trigger skips as `in_progress` on it); with a provider that\n * cannot list, every trigger skips as `unresolved`.\n *\n * The result is written as the lease is released, and only while this run\n * still holds it. A failed `builds.start` clears the last build id, so a later\n * `schedule` or `push` cannot mistake the previous ready build for the current\n * template; any other error keeps a running build's id. A started build whose\n * recording keeps failing yields `failed` (`not_recorded`) with the lease left\n * to lapse rather than released, and a run that lost its lease while the\n * provider started yields `failed` (`superseded`); neither is polled or pinned.\n */\nexport async function runEnvironmentBuild(\n deps: EnvironmentBuildDeps,\n input: { projectId: string; trigger: EnvironmentBuildTrigger },\n): Promise<EnvironmentBuildOutcome> {\n const builds = deps.sandbox?.builds;\n if (!builds) return { outcome: 'unavailable', reason: 'no_builds' };\n if (!deps.sourceControl) return { outcome: 'unavailable', reason: 'no_source_control' };\n const sourceControl = deps.sourceControl;\n const initial = await deps.projects.getById({ id: input.projectId });\n if (!initial) return { outcome: 'skipped', reason: 'no_environment' };\n const now = deps.now ?? (() => new Date());\n const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\n const pushDebounced = (project: FactoryProject, at: Date) =>\n project.lastPushBuildAt !== null &&\n at.getTime() - project.lastPushBuildAt.getTime() < project.buildPushDebounceMinutes * 60_000;\n if (input.trigger === 'push' && pushDebounced(initial, now())) return { outcome: 'skipped', reason: 'debounced' };\n\n const token = randomUUID();\n const lease = { id: initial.id, token, leaseMs: BUILD_START_LEASE_MS };\n const claim = await deps.projects.claimBuildStart({ ...lease, now: now() });\n if (!claim.claimed) return { outcome: 'skipped', reason: 'starting' };\n let held = true;\n const renewal = setInterval(\n () => {\n deps.projects.renewBuildStart({ ...lease, now: now() }).then(\n renewed => {\n if (!renewed) held = false;\n },\n // A failed renewal is retried on the next tick; the lease outlasts two misses.\n () => {},\n );\n },\n deps.leaseRenewMs ?? BUILD_START_LEASE_MS / 3,\n );\n renewal.unref?.();\n\n const attempted = { lastBuildAttemptedAt: now() };\n // Set once this run has reconciled an uncertain start, or builds past it.\n let resolved = false;\n const release = (changes: Parameters<EnvironmentBuildDeps['projects']['releaseBuildStart']>[0]['changes'] = {}) =>\n deps.projects.releaseBuildStart({ id: initial.id, token, changes, resolved, now: now() });\n const failed = async (error: unknown, changes: Parameters<typeof release>[0]) => {\n const reason = errorReason(error);\n await release(changes);\n deps.logger?.info('environment build failed', { factoryProjectId: initial.id, trigger: input.trigger, reason });\n return { outcome: 'failed', reason } satisfies EnvironmentBuildOutcome;\n };\n\n try {\n let project: FactoryProject;\n let environment: SessionEnvironment;\n let heads: EnvironmentHeads;\n let ctx: FactorySandboxContext;\n let buildInputs: string;\n try {\n // Read build state only once this run holds the lease, so a run that\n // finished while this one waited has already recorded its build.\n project = (await deps.projects.getById({ id: initial.id })) ?? initial;\n environment = await resolveProjectEnvironment(sourceControl.storage, project);\n if (environment.repos.length === 0) {\n await release();\n return { outcome: 'skipped', reason: 'no_environment' };\n }\n heads = await resolveEnvironmentHeads(sourceControl, project, environment);\n ctx = environmentBuildContext(project, environment, heads, sourceControl.versionControl);\n buildInputs = environmentBuildInputs(environment);\n\n if (claim.uncertain) {\n // A run whose lease lapsed may have reached the provider before it\n // died; a build it left running is never raced by a second one. The\n // mark stays until that build is gone, since its inputs are unknown.\n if (builds.list) {\n const listed = await builds.list(ctx, environment.settings);\n const running = listed.find(build => build.status === 'pending' || build.status === 'building');\n if (running) {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: running.buildId };\n }\n resolved = true;\n } else {\n // Without history the earlier start can never be reconciled, so no\n // trigger starts another build beside it.\n await release();\n return { outcome: 'skipped', reason: 'unresolved' };\n }\n }\n\n if (project.lastBuildId) {\n const last = await builds.get(ctx, environment.settings, project.lastBuildId);\n // Two runs polling one template fight over it (each poll resubmits its\n // own definition and the provider cancels the other), so a running\n // build is never joined by a second one, whatever asked.\n if (last.status === 'pending' || last.status === 'building') {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: project.lastBuildId };\n }\n // A ready build whose poll ran out or died with its host was never\n // pinned; pin it now so the skip below compares against what it built.\n let pinnedHeads = project.activeTemplateHeads;\n const lastTemplateId = last.templateId ?? project.lastBuildId;\n if (last.status === 'ready' && project.lastBuildHeads && project.activeTemplateId !== lastTemplateId) {\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: project.lastBuildId,\n templateId: lastTemplateId,\n heads: project.lastBuildHeads,\n });\n if (pinned) pinnedHeads = project.lastBuildHeads;\n }\n if (\n (input.trigger === 'schedule' || input.trigger === 'push') &&\n last.status === 'ready' &&\n !headsChanged(pinnedHeads, heads) &&\n project.lastBuildInputs === buildInputs\n ) {\n await release();\n return { outcome: 'skipped', reason: 'unchanged' };\n }\n }\n } catch (error) {\n return await failed(error, attempted);\n }\n\n // A run that lost its lease while reading must not start beside its successor.\n if (!held) return { outcome: 'skipped', reason: 'starting' };\n\n if (input.trigger === 'push') {\n // Claimed only now, so a push that skipped above never closes the window.\n let claimed: boolean;\n try {\n claimed = await deps.projects.claimBuildAttempt({\n id: project.id,\n debounceMinutes: project.buildPushDebounceMinutes,\n now: now(),\n });\n } catch (error) {\n return await failed(error, {});\n }\n if (!claimed) {\n await release();\n return { outcome: 'skipped', reason: 'debounced' };\n }\n }\n\n let started: Awaited<ReturnType<typeof builds.start>>;\n try {\n started = await builds.start(ctx, environment.settings);\n } catch (error) {\n // Only a failed start clears the last build: the previous one no longer\n // describes the template this project wants.\n return await failed(error, { lastBuildId: null, lastBuildHeads: null, lastBuildInputs: null, ...attempted });\n }\n\n // The provider has started the build: from here on, no error clears it.\n const log = { factoryProjectId: project.id, trigger: input.trigger, buildId: started.buildId };\n const changes = { lastBuildId: started.buildId, lastBuildHeads: heads, lastBuildInputs: buildInputs, ...attempted };\n let recorded: boolean | undefined;\n for (let attempt = 1; recorded === undefined; attempt++) {\n try {\n recorded = await release(changes);\n } catch (error) {\n if (attempt >= RECORD_ATTEMPTS) {\n // Keep the lease: it lapses once renewal stops, and the run that\n // takes it over looks for this build at the provider first.\n deps.logger?.info('environment build started but not recorded', { ...log, reason: errorReason(error) });\n return { outcome: 'failed', reason: 'not_recorded', buildId: started.buildId };\n }\n await sleep(1000 * 2 ** (attempt - 1));\n }\n }\n if (!recorded) {\n // A newer run took the lease while the provider started this build; the\n // project tracks that run's build, so this one is never polled or pinned.\n deps.logger?.info('environment build superseded', log);\n return { outcome: 'failed', reason: 'superseded', buildId: started.buildId };\n }\n try {\n deps.logger?.info('environment build started', { ...log, templateId: started.templateId });\n } catch {\n // Logging never turns a recorded build into a failure.\n }\n return {\n outcome: 'started',\n buildId: started.buildId,\n ...(started.templateId ? { templateId: started.templateId } : {}),\n heads,\n };\n } finally {\n clearInterval(renewal);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,6BAA6B;CAAC;CAAU;CAAY;AAAM;;AAoCvE,SAAgB,0BAA0B,WAA2B;CACnE,OAAO,qBAAqB;AAC9B;;;;;AAMA,SAAgB,kBAAkB,SAAyB;CACzD,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,CAAC,CAAC,QAAQ,6CAA6C,KAAK;AAC/G;;AAGA,SAAgB,YAAY,OAAwB;CAClD,OAAO,kBAAkB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACjF;;;;;;;AAQA,SAAgB,wBACd,SACA,aACA,OACA,gBACuB;CACvB,OAAO;EACL,WAAW,0BAA0B,QAAQ,EAAE;EAC/C,GAAG,0BAA0B,aAAa;GACxC,OAAO,QAAQ;GACf,sBAAqB,SAAQ,eAAe,oBAAoB,IAAI;GACpE,aAAa,qBAAqB,KAAK;EACzC,CAAC;CACH;AACF;;;;;;;AAQA,SAAgB,uBAAuB,aAAyC;CAC9E,MAAM,SAAS;EACb,UAAU,YAAY;EACtB,uBAAuB,YAAY,yBAAyB;EAC5D,kBAAkB,YAAY,oBAAoB;EAClD,OAAO,YAAY,MAAM,KAAI,UAAS;GACpC,cAAc,KAAK;GACnB,gBAAgB,KAAK;GACrB,cAAc,KAAK,gBAAgB;EACrC,EAAE;CACJ;CACA,OAAO,WAAW,QAAQ,CAAC,CA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AAW,IAAI,CAAC;GAC/D;EACF;CACF,UAAU;EACR,cAAc,OAAO;CACvB;AACF"}
1
+ {"version":3,"file":"build.js","names":[],"sources":["../../src/environment/build.ts"],"sourcesContent":["/**\n * One proactive environment build: decide whether a trigger should build,\n * hand the sandbox's `builds` capability a context identical to a session's,\n * and record the started build on the project row. Polling the build to its\n * end and pinning the active template is the workflow's second step\n * (`build-workflow.ts`), so a request that only needs the start answer never\n * waits on the provider.\n */\n\nimport { createHash, randomUUID } from 'node:crypto';\n\nimport type { FactorySandbox, FactorySandboxContext } from '@mastra/core/workspace';\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { environmentSandboxContext, resolveProjectEnvironment } from '../workspace.js';\nimport type { SessionEnvironment } from '../workspace.js';\nimport { headsChanged, recordedHeadResolver, resolveCurrentHeads } from './heads.js';\nimport type { EnvironmentHeads } from './heads.js';\n\nexport const ENVIRONMENT_BUILD_TRIGGERS = ['manual', 'schedule', 'push'] as const;\nexport type EnvironmentBuildTrigger = (typeof ENVIRONMENT_BUILD_TRIGGERS)[number];\n\nexport interface EnvironmentBuildSourceControl {\n storage: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>;\n}\n\nexport interface EnvironmentBuildDeps {\n /** The factory's normalized sandbox; builds are unavailable without its `builds`. */\n sandbox: FactorySandbox | undefined;\n projects: Pick<\n FactoryProjectsStorage,\n 'getById' | 'claimBuildAttempt' | 'claimBuildStart' | 'renewBuildStart' | 'releaseBuildStart' | 'pinActiveTemplate'\n >;\n /** Absent when the factory has no source-control integration to resolve heads with. */\n sourceControl: EnvironmentBuildSourceControl | undefined;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n now?: () => Date;\n /** How often a run renews its build-start lease; a third of `BUILD_START_LEASE_MS` by default. */\n leaseRenewMs?: number;\n /** Waits between tries at recording a started build. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface EnvironmentBuildOutcome {\n outcome: 'started' | 'skipped' | 'unavailable' | 'failed';\n buildId?: string;\n templateId?: string;\n /** Why nothing started: `debounced`, `starting` (another run is starting a build), `in_progress`, `unchanged`, `unresolved` (a lapsed run may have started a build the provider cannot list), `no_environment`, `no_builds`, `no_source_control`; why a run failed: `not_recorded`, `superseded`, or an error. */\n reason?: string;\n /** The heads the started build pins; the workflow stores them once the build is ready. */\n heads?: EnvironmentHeads;\n}\n\n/** The synthetic session id a project's build runs under; never a session. */\nexport function environmentBuildSessionId(projectId: string): string {\n return `environment-build:${projectId}`;\n}\n\n/**\n * A build or setup error may echo a clone URL or a token; strip URL userinfo\n * and GitHub token shapes before the message is stored, logged or shown.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(/\\/\\/[^/\\s@]+@/g, '//***@').replace(/\\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]+/g, '***');\n}\n\n/** An error's message with credentials redacted, safe to log, store or return. */\nexport function errorReason(error: unknown): string {\n return redactCredentials(error instanceof Error ? error.message : String(error));\n}\n\n/**\n * The context an environment build (or a read of its status) hands the\n * provider: the same list form a session boots with, under the build's own\n * session id, with heads served from `heads` so the provider never resolves\n * them itself.\n */\nexport function environmentBuildContext(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>,\n): FactorySandboxContext {\n return {\n sessionId: environmentBuildSessionId(project.id),\n factoryId: project.id,\n factoryName: project.name,\n ...environmentSandboxContext(environment, {\n orgId: project.orgId,\n getRepositoryAccess: args => versionControl.getRepositoryAccess(args),\n resolveHead: recordedHeadResolver(heads),\n }),\n };\n}\n\n/**\n * Fingerprint of everything a build bakes into the template besides the\n * repository heads: provider settings, the repositories and their order,\n * their setup commands, the workspace setup command and the working\n * directory. A schedule or push skips a ready build only while this matches.\n */\nexport function environmentBuildInputs(environment: SessionEnvironment): string {\n const inputs = {\n settings: environment.settings,\n workspaceSetupCommand: environment.workspaceSetupCommand ?? null,\n workingDirectory: environment.workingDirectory ?? null,\n repos: environment.repos.map(repo => ({\n repositoryId: repo.repositoryId,\n templateBranch: repo.templateBranch,\n setupCommand: repo.setupCommand ?? null,\n })),\n };\n return createHash('sha256').update(JSON.stringify(inputs)).digest('hex');\n}\n\n/**\n * The current head of every environment repository's template branch, keyed\n * by slug. The template clones the repository default branch (a link's own\n * branch is the session's base, checked out after boot), so that is the\n * branch a build pins; sessions let the provider resolve the same head.\n */\nexport async function resolveEnvironmentHeads(\n sourceControl: EnvironmentBuildSourceControl,\n project: Pick<FactoryProject, 'orgId'>,\n environment: SessionEnvironment,\n): Promise<EnvironmentHeads> {\n return resolveCurrentHeads(sourceControl, {\n orgId: project.orgId,\n repositories: environment.repos.map(repo => ({\n id: repo.repositoryId,\n slug: repo.slug,\n branch: repo.templateBranch,\n })),\n });\n}\n\n/**\n * How long a build-start lease lasts without renewal. The run holding it\n * renews it every third of that while it works, so a lease lapses only when\n * its run died or stalled.\n */\nexport const BUILD_START_LEASE_MS = 10 * 60_000;\n\n/** Tries at recording a started build before the run leaves its lease to lapse. */\nconst RECORD_ATTEMPTS = 5;\n\n/**\n * Start a build for `projectId` when `trigger` calls for one. Every trigger\n * takes the project's build-start lease before reading build state and renews\n * it until the started build is recorded, so overlapping manual, scheduled and\n * push runs never both start a build, however long the provider takes; a run\n * that finds the lease held skips as `starting`. Every trigger skips while the\n * last build is still running; `schedule` and `push` also skip when the last\n * build is ready and neither a head nor any other template input changed;\n * `manual` otherwise always builds. A `push` that would build then takes the\n * leading-edge debounce claim, so only a push that starts a build opens the\n * window. Saving settings never builds.\n *\n * Taking over a lapsed lease leaves the start uncertain: the lapsed run may\n * have started a build it never recorded. The mark persists until resolved.\n * While it stands, a provider that lists builds is asked for a running one\n * (and every trigger skips as `in_progress` on it); with a provider that\n * cannot list, every trigger skips as `unresolved`.\n *\n * The result is written as the lease is released, and only while this run\n * still holds it. A failed `builds.start` clears the last build id, so a later\n * `schedule` or `push` cannot mistake the previous ready build for the current\n * template; any other error keeps a running build's id. A started build whose\n * recording keeps failing yields `failed` (`not_recorded`) with the lease left\n * to lapse rather than released, and a run that lost its lease while the\n * provider started yields `failed` (`superseded`); neither is polled or pinned.\n */\nexport async function runEnvironmentBuild(\n deps: EnvironmentBuildDeps,\n input: { projectId: string; trigger: EnvironmentBuildTrigger },\n): Promise<EnvironmentBuildOutcome> {\n const builds = deps.sandbox?.builds;\n if (!builds) return { outcome: 'unavailable', reason: 'no_builds' };\n if (!deps.sourceControl) return { outcome: 'unavailable', reason: 'no_source_control' };\n const sourceControl = deps.sourceControl;\n const initial = await deps.projects.getById({ id: input.projectId });\n if (!initial) return { outcome: 'skipped', reason: 'no_environment' };\n const now = deps.now ?? (() => new Date());\n const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\n const pushDebounced = (project: FactoryProject, at: Date) =>\n project.lastPushBuildAt !== null &&\n at.getTime() - project.lastPushBuildAt.getTime() < project.buildPushDebounceMinutes * 60_000;\n if (input.trigger === 'push' && pushDebounced(initial, now())) return { outcome: 'skipped', reason: 'debounced' };\n\n const token = randomUUID();\n const lease = { id: initial.id, token, leaseMs: BUILD_START_LEASE_MS };\n const claim = await deps.projects.claimBuildStart({ ...lease, now: now() });\n if (!claim.claimed) return { outcome: 'skipped', reason: 'starting' };\n let held = true;\n const renewal = setInterval(\n () => {\n deps.projects.renewBuildStart({ ...lease, now: now() }).then(\n renewed => {\n if (!renewed) held = false;\n },\n // A failed renewal is retried on the next tick; the lease outlasts two misses.\n () => {},\n );\n },\n deps.leaseRenewMs ?? BUILD_START_LEASE_MS / 3,\n );\n renewal.unref?.();\n\n const attempted = { lastBuildAttemptedAt: now() };\n // Set once this run has reconciled an uncertain start, or builds past it.\n let resolved = false;\n const release = (changes: Parameters<EnvironmentBuildDeps['projects']['releaseBuildStart']>[0]['changes'] = {}) =>\n deps.projects.releaseBuildStart({ id: initial.id, token, changes, resolved, now: now() });\n const failed = async (error: unknown, changes: Parameters<typeof release>[0]) => {\n const reason = errorReason(error);\n await release(changes);\n deps.logger?.info('environment build failed', { factoryProjectId: initial.id, trigger: input.trigger, reason });\n return { outcome: 'failed', reason } satisfies EnvironmentBuildOutcome;\n };\n\n try {\n let project: FactoryProject;\n let environment: SessionEnvironment;\n let heads: EnvironmentHeads;\n let ctx: FactorySandboxContext;\n let buildInputs: string;\n try {\n // Read build state only once this run holds the lease, so a run that\n // finished while this one waited has already recorded its build.\n project = (await deps.projects.getById({ id: initial.id })) ?? initial;\n environment = await resolveProjectEnvironment(sourceControl.storage, project);\n if (environment.repos.length === 0) {\n await release();\n return { outcome: 'skipped', reason: 'no_environment' };\n }\n heads = await resolveEnvironmentHeads(sourceControl, project, environment);\n ctx = environmentBuildContext(project, environment, heads, sourceControl.versionControl);\n buildInputs = environmentBuildInputs(environment);\n\n if (claim.uncertain) {\n // A run whose lease lapsed may have reached the provider before it\n // died; a build it left running is never raced by a second one. The\n // mark stays until that build is gone, since its inputs are unknown.\n if (builds.list) {\n const listed = await builds.list(ctx, environment.settings);\n const running = listed.find(build => build.status === 'pending' || build.status === 'building');\n if (running) {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: running.buildId };\n }\n resolved = true;\n } else {\n // Without history the earlier start can never be reconciled, so no\n // trigger starts another build beside it.\n await release();\n return { outcome: 'skipped', reason: 'unresolved' };\n }\n }\n\n if (project.lastBuildId) {\n const last = await builds.get(ctx, environment.settings, project.lastBuildId);\n // Two runs polling one template fight over it (each poll resubmits its\n // own definition and the provider cancels the other), so a running\n // build is never joined by a second one, whatever asked.\n if (last.status === 'pending' || last.status === 'building') {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: project.lastBuildId };\n }\n // A ready build whose poll ran out or died with its host was never\n // pinned; pin it now so the skip below compares against what it built.\n let pinnedHeads = project.activeTemplateHeads;\n const lastTemplateId = last.templateId ?? project.lastBuildId;\n if (last.status === 'ready' && project.lastBuildHeads && project.activeTemplateId !== lastTemplateId) {\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: project.lastBuildId,\n templateId: lastTemplateId,\n heads: project.lastBuildHeads,\n });\n if (pinned) pinnedHeads = project.lastBuildHeads;\n }\n if (\n (input.trigger === 'schedule' || input.trigger === 'push') &&\n last.status === 'ready' &&\n !headsChanged(pinnedHeads, heads) &&\n project.lastBuildInputs === buildInputs\n ) {\n await release();\n return { outcome: 'skipped', reason: 'unchanged' };\n }\n }\n } catch (error) {\n return await failed(error, attempted);\n }\n\n // A run that lost its lease while reading must not start beside its successor.\n if (!held) return { outcome: 'skipped', reason: 'starting' };\n\n if (input.trigger === 'push') {\n // Claimed only now, so a push that skipped above never closes the window.\n let claimed: boolean;\n try {\n claimed = await deps.projects.claimBuildAttempt({\n id: project.id,\n debounceMinutes: project.buildPushDebounceMinutes,\n now: now(),\n });\n } catch (error) {\n return await failed(error, {});\n }\n if (!claimed) {\n await release();\n return { outcome: 'skipped', reason: 'debounced' };\n }\n }\n\n let started: Awaited<ReturnType<typeof builds.start>>;\n try {\n started = await builds.start(ctx, environment.settings);\n } catch (error) {\n // Only a failed start clears the last build: the previous one no longer\n // describes the template this project wants.\n return await failed(error, { lastBuildId: null, lastBuildHeads: null, lastBuildInputs: null, ...attempted });\n }\n\n // The provider has started the build: from here on, no error clears it.\n const log = { factoryProjectId: project.id, trigger: input.trigger, buildId: started.buildId };\n const changes = { lastBuildId: started.buildId, lastBuildHeads: heads, lastBuildInputs: buildInputs, ...attempted };\n let recorded: boolean | undefined;\n for (let attempt = 1; recorded === undefined; attempt++) {\n try {\n recorded = await release(changes);\n } catch (error) {\n if (attempt >= RECORD_ATTEMPTS) {\n // Keep the lease: it lapses once renewal stops, and the run that\n // takes it over looks for this build at the provider first.\n deps.logger?.info('environment build started but not recorded', { ...log, reason: errorReason(error) });\n return { outcome: 'failed', reason: 'not_recorded', buildId: started.buildId };\n }\n await sleep(1000 * 2 ** (attempt - 1));\n }\n }\n if (!recorded) {\n // A newer run took the lease while the provider started this build; the\n // project tracks that run's build, so this one is never polled or pinned.\n deps.logger?.info('environment build superseded', log);\n return { outcome: 'failed', reason: 'superseded', buildId: started.buildId };\n }\n try {\n deps.logger?.info('environment build started', { ...log, templateId: started.templateId });\n } catch {\n // Logging never turns a recorded build into a failure.\n }\n return {\n outcome: 'started',\n buildId: started.buildId,\n ...(started.templateId ? { templateId: started.templateId } : {}),\n heads,\n };\n } finally {\n clearInterval(renewal);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,6BAA6B;CAAC;CAAU;CAAY;AAAM;;AAoCvE,SAAgB,0BAA0B,WAA2B;CACnE,OAAO,qBAAqB;AAC9B;;;;;AAMA,SAAgB,kBAAkB,SAAyB;CACzD,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,CAAC,CAAC,QAAQ,6CAA6C,KAAK;AAC/G;;AAGA,SAAgB,YAAY,OAAwB;CAClD,OAAO,kBAAkB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACjF;;;;;;;AAQA,SAAgB,wBACd,SACA,aACA,OACA,gBACuB;CACvB,OAAO;EACL,WAAW,0BAA0B,QAAQ,EAAE;EAC/C,WAAW,QAAQ;EACnB,aAAa,QAAQ;EACrB,GAAG,0BAA0B,aAAa;GACxC,OAAO,QAAQ;GACf,sBAAqB,SAAQ,eAAe,oBAAoB,IAAI;GACpE,aAAa,qBAAqB,KAAK;EACzC,CAAC;CACH;AACF;;;;;;;AAQA,SAAgB,uBAAuB,aAAyC;CAC9E,MAAM,SAAS;EACb,UAAU,YAAY;EACtB,uBAAuB,YAAY,yBAAyB;EAC5D,kBAAkB,YAAY,oBAAoB;EAClD,OAAO,YAAY,MAAM,KAAI,UAAS;GACpC,cAAc,KAAK;GACnB,gBAAgB,KAAK;GACrB,cAAc,KAAK,gBAAgB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B;;;eAGG;YACH,IAAI,CAAC,EAAE,MAAM,CAAC;SACf,CAAC;KACH,CAAC;CACH;AAED,YAAY,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC3G,YAAY,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1D;;;;GAIG;AACH,MAAM,WAAW,6BAA6B;IAC5C,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAuGD,qBAAa,aAAa;;IAoBxB,YAAY,MAAM,EAAE,mBAAmB,EAwBtC;IAED;;;;OAIG;IACH,IAAI,kBAAkB,IAAI,yBAAyB,GAAG,SAAS,CAI9D;IAED;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,CAgiDnC;IAED;;;;OAIG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAoB9B;IAED,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAsB9B;CACF"}
package/dist/factory.js CHANGED
@@ -614,8 +614,8 @@ var MastraFactory = class {
614
614
  id: installationId
615
615
  });
616
616
  if (!installation) return null;
617
- const selected = (await githubIntegration.listInstallationRepos(Number(installation.externalId))).find((repo) => repo.id.toString() === externalId && repo.fullName === slug);
618
- if (!selected) return null;
617
+ const selected = await githubIntegration.getInstallationRepo(Number(installation.externalId), slug);
618
+ if (!selected || selected.id.toString() !== externalId || selected.fullName !== slug) return null;
619
619
  return githubIntegration.sourceControlStorage.repositories.upsert({
620
620
  orgId,
621
621
  input: {