@mastra/factory 0.2.2 → 0.3.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.
- package/CHANGELOG.md +54 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +54 -6
- package/dist/auth.js.map +1 -1
- package/dist/factory.d.ts +10 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +35 -4
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/integrations/base.d.ts +25 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +23 -8
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/sandbox-release.d.ts +38 -0
- package/dist/integrations/github/sandbox-release.d.ts.map +1 -0
- package/dist/integrations/github/sandbox-release.js +74 -0
- package/dist/integrations/github/sandbox-release.js.map +1 -0
- package/dist/integrations/github/sandbox.d.ts +10 -0
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +18 -1
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +1 -1
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +4 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +52 -17
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/routes/surface.d.ts +3 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +2 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +2 -0
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +43 -12
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/start-coordinator.js +1 -1
- package/dist/rules/transition-service.d.ts +17 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +29 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/sandbox/fleet.d.ts +12 -1
- package/dist/sandbox/fleet.d.ts.map +1 -1
- package/dist/sandbox/fleet.js +35 -1
- package/dist/sandbox/fleet.js.map +1 -1
- package/dist/spa-static.js +2 -1
- package/dist/spa-static.js.map +1 -1
- package/dist/state-signing.d.ts +8 -1
- package/dist/state-signing.d.ts.map +1 -1
- package/dist/state-signing.js +5 -2
- package/dist/state-signing.js.map +1 -1
- package/dist/storage/domains/channel-identity/base.d.ts +96 -0
- package/dist/storage/domains/channel-identity/base.d.ts.map +1 -0
- package/dist/storage/domains/channel-identity/base.js +149 -0
- package/dist/storage/domains/channel-identity/base.js.map +1 -0
- package/dist/storage/domains/source-control/base.d.ts +51 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +91 -0
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +13 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +35 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +19 -3
- package/dist/workspace.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inmemory.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/source-control/inmemory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,+BAA+B,EAC/B,yCAAyC,EACzC,+BAA+B,EAC/B,+BAA+B,EAC/B,0BAA0B,EAC1B,iBAAiB,EACjB,wBAAwB,EACxB,8BAA8B,EAC9B,yBAAyB,EACzB,uBAAuB,EACvB,oBAAoB,EACpB,0BAA0B,EAC1B,qBAAqB,EACrB,4BAA4B,EA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EAAE,MAAM,CAAC;YACvB,UAAU,EAAE,MAAM,CAAC;SACpB;sDAImD;YAAE,KAAK,EAAE,MAAM,CAAC;YAAC,cAAc,EAAE,MAAM,CAAC;YAAC,IAAI,EAAE,MAAM,CAAA;SAAE;oCAOxG;YACD,KAAK,EAAE,MAAM,CAAC;YACd,KAAK,EAAE,kCAAkC,CAAC;SAC3C,KAAG,OAAO,CAAC,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"inmemory.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/source-control/inmemory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,+BAA+B,EAC/B,yCAAyC,EACzC,+BAA+B,EAC/B,+BAA+B,EAC/B,0BAA0B,EAC1B,aAAa,EACb,iBAAiB,EACjB,wBAAwB,EACxB,8BAA8B,EAC9B,yBAAyB,EACzB,yBAAyB,EACzB,uBAAuB,EACvB,oBAAoB,EACpB,0BAA0B,EAC1B,qBAAqB,EACrB,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EAClC,gCAAgC,EACjC,MAAM,WAAW,CAAC;AAEnB,uEAAuE;AACvE,qBAAa,4BAA6B,YAAW,0BAA0B;IAC7E,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,iBAAiB,EAAE,yBAAyB,EAAE,CAAM;IACpD,gBAAgB,EAAE,uBAAuB,EAAE,CAAM;IACjD,eAAe,EAAE,8BAA8B,EAAE,CAAM;IACvD,uBAAuB,EAAE,iBAAiB,EAAE,CAAM;IAClD,aAAa,EAAE,wBAAwB,EAAE,CAAM;IAC/C,eAAe,EAAE,aAAa,EAAE,CAAM;IACtC,aAAa,EAAE,qBAAqB,EAAE,CAAM;IAC5C,YAAY,EAAE,oBAAoB,EAAE,CAAM;gBAE9B,aAAa,SAAW;IAIpC,QAAQ,CAAC,aAAa;0BACI;YAAE,KAAK,EAAE,MAAM,CAAA;SAAE,KAAG,OAAO,CAAC,yBAAyB,EAAE,CAAC;6BAErD;YA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MAAM,EAAE,MAAM,CAAC;YACf,MAAM,EAAE,MAAM,CAAC;SAChB,KAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;wBAIlB,+BAA+B,KAAG,OAAO,CAAC,oBAAoB,CAAC;yDAoBlF;YACD,EAAE,EAAE,MAAM,CAAC;YACX,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;YACzB,cAAc,EAAE,MAAM,CAAC;SACxB;mCAIgC;YAAE,EAAE,EAAE,MAAM,CAAA;SAAE;qBAI5B,MAAM;MAGzB;CACH"}
|
|
@@ -8,6 +8,7 @@ var SourceControlStorageInMemory = class {
|
|
|
8
8
|
connectionsRows = [];
|
|
9
9
|
projectRepositoriesRows = [];
|
|
10
10
|
sandboxesRows = [];
|
|
11
|
+
sandboxPoolRows = [];
|
|
11
12
|
worktreesRows = [];
|
|
12
13
|
sessionsRows = [];
|
|
13
14
|
constructor(integrationId = "github") {
|
|
@@ -104,6 +105,23 @@ var SourceControlStorageInMemory = class {
|
|
|
104
105
|
};
|
|
105
106
|
this.repositoriesRows.push(created);
|
|
106
107
|
return created;
|
|
108
|
+
},
|
|
109
|
+
migrateInstallation: async ({ orgId, id, newInstallationId }) => {
|
|
110
|
+
const existing = await this.repositories.get({
|
|
111
|
+
orgId,
|
|
112
|
+
id
|
|
113
|
+
});
|
|
114
|
+
if (!existing) throw new Error(`Repository ${id} not found in organization ${orgId}`);
|
|
115
|
+
if (!await this.installations.get({
|
|
116
|
+
orgId,
|
|
117
|
+
id: newInstallationId
|
|
118
|
+
})) throw new Error("Source-control installation not found");
|
|
119
|
+
const conflict = this.repositoriesRows.find((row) => row.installationId === newInstallationId && row.externalId === existing.externalId);
|
|
120
|
+
if (conflict) return conflict;
|
|
121
|
+
existing.installationId = newInstallationId;
|
|
122
|
+
existing.updatedAt = /* @__PURE__ */ new Date();
|
|
123
|
+
for (const conn of this.connectionsRows) if (conn.installationId === existing.installationId) conn.installationId = newInstallationId;
|
|
124
|
+
return existing;
|
|
107
125
|
}
|
|
108
126
|
};
|
|
109
127
|
connections = {
|
|
@@ -275,6 +293,23 @@ var SourceControlStorageInMemory = class {
|
|
|
275
293
|
if (row) row.materializedAt = /* @__PURE__ */ new Date();
|
|
276
294
|
}
|
|
277
295
|
};
|
|
296
|
+
sandboxPool = {
|
|
297
|
+
release: async (input) => {
|
|
298
|
+
if (!this.projectRepositoriesRows.some((row) => row.id === input.projectRepositoryId)) return;
|
|
299
|
+
if (this.sandboxPoolRows.some((row) => row.sandboxId === input.sandboxId)) return;
|
|
300
|
+
this.sandboxPoolRows.push({
|
|
301
|
+
id: randomUUID(),
|
|
302
|
+
releasedAt: /* @__PURE__ */ new Date(),
|
|
303
|
+
...input
|
|
304
|
+
});
|
|
305
|
+
},
|
|
306
|
+
claim: async ({ projectRepositoryId }) => {
|
|
307
|
+
const claimed = this.sandboxPoolRows.filter((row) => row.projectRepositoryId === projectRepositoryId).sort((left, right) => right.releasedAt.getTime() - left.releasedAt.getTime())[0];
|
|
308
|
+
if (!claimed) return null;
|
|
309
|
+
this.sandboxPoolRows.splice(this.sandboxPoolRows.indexOf(claimed), 1);
|
|
310
|
+
return claimed;
|
|
311
|
+
}
|
|
312
|
+
};
|
|
278
313
|
worktrees = {
|
|
279
314
|
upsert: async (input) => {
|
|
280
315
|
const existing = this.worktreesRows.find((row) => row.projectRepositoryId === input.projectRepositoryId && row.userId === input.userId && row.branch === input.branch);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inmemory.js","names":[],"sources":["../../../../src/storage/domains/source-control/inmemory.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type {\n ConfiguredExternalRepositoryKey,\n CreateProjectSourceControlConnectionInput,\n CreateSourceControlSessionInput,\n ExternalRepositoryProjectTarget,\n LinkProjectRepositoryInput,\n ProjectRepository,\n ProjectRepositorySandbox,\n ProjectSourceControlConnection,\n SourceControlInstallation,\n SourceControlRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n SourceControlWorktree,\n UpdateProjectRepositoryInput,\n UpsertSourceControlInstallationInput,\n UpsertSourceControlRepositoryInput,\n UpsertSourceControlWorktreeInput,\n} from './base.js';\n\n/** In-memory provider-scoped source-control handle for route tests. */\nexport class SourceControlStorageInMemory implements SourceControlStorageHandle {\n readonly integrationId: string;\n installationsRows: SourceControlInstallation[] = [];\n repositoriesRows: SourceControlRepository[] = [];\n connectionsRows: ProjectSourceControlConnection[] = [];\n projectRepositoriesRows: ProjectRepository[] = [];\n sandboxesRows: ProjectRepositorySandbox[] = [];\n worktreesRows: SourceControlWorktree[] = [];\n sessionsRows: SourceControlSession[] = [];\n\n constructor(integrationId = 'github') {\n this.integrationId = integrationId;\n }\n\n readonly installations = {\n list: async ({ orgId }: { orgId: string }): Promise<SourceControlInstallation[]> =>\n this.installationsRows.filter(row => row.orgId === orgId),\n get: async ({ orgId, id }: { orgId: string; id: string }): Promise<SourceControlInstallation | null> =>\n this.installationsRows.find(row => row.orgId === orgId && row.id === id) ?? null,\n findByExternalId: async ({\n orgId,\n externalId,\n }: {\n orgId: string;\n externalId: string;\n }): Promise<SourceControlInstallation | null> =>\n this.installationsRows.find(row => row.orgId === orgId && row.externalId === externalId) ?? null,\n upsert: async (input: UpsertSourceControlInstallationInput): Promise<SourceControlInstallation> => {\n const existing = this.installationsRows.find(\n row => row.orgId === input.orgId && row.externalId === input.externalId,\n );\n if (existing) {\n Object.assign(existing, {\n connectedByUserId: input.connectedByUserId,\n accountName: input.accountName ?? null,\n accountType: input.accountType ?? null,\n providerMetadata: input.providerMetadata ?? {},\n });\n return existing;\n }\n const created: SourceControlInstallation = {\n id: randomUUID(),\n integrationId: this.integrationId,\n orgId: input.orgId,\n connectedByUserId: input.connectedByUserId,\n externalId: input.externalId,\n accountName: input.accountName ?? null,\n accountType: input.accountType ?? null,\n providerMetadata: input.providerMetadata ?? {},\n createdAt: new Date(),\n };\n this.installationsRows.push(created);\n return created;\n },\n delete: async ({ orgId, id }: { orgId: string; id: string }): Promise<boolean> => {\n const index = this.installationsRows.findIndex(row => row.orgId === orgId && row.id === id);\n if (index < 0) return false;\n this.installationsRows.splice(index, 1);\n return true;\n },\n };\n\n readonly repositories = {\n list: async ({ orgId, installationId }: { orgId: string; installationId: string }) => {\n const installation = await this.installations.get({ orgId, id: installationId });\n return installation ? this.repositoriesRows.filter(row => row.installationId === installationId) : [];\n },\n get: async ({ orgId, id }: { orgId: string; id: string }): Promise<SourceControlRepository | null> => {\n const row = this.repositoriesRows.find(candidate => candidate.id === id);\n if (!row) return null;\n return (await this.installations.get({ orgId, id: row.installationId })) ? row : null;\n },\n findByExternalId: async ({\n orgId,\n installationId,\n externalId,\n }: {\n orgId: string;\n installationId: string;\n externalId: string;\n }) => {\n const rows = await this.repositories.list({ orgId, installationId });\n return rows.find(row => row.externalId === externalId) ?? null;\n },\n findBySlug: async ({ orgId, installationId, slug }: { orgId: string; installationId: string; slug: string }) => {\n const rows = await this.repositories.list({ orgId, installationId });\n return rows.find(row => row.slug === slug) ?? null;\n },\n upsert: async ({\n orgId,\n input,\n }: {\n orgId: string;\n input: UpsertSourceControlRepositoryInput;\n }): Promise<SourceControlRepository> => {\n if (!(await this.installations.get({ orgId, id: input.installationId }))) {\n throw new Error('Source-control installation not found');\n }\n const existing = this.repositoriesRows.find(\n row => row.installationId === input.installationId && row.externalId === input.externalId,\n );\n const now = new Date();\n if (existing) {\n Object.assign(existing, {\n slug: input.slug,\n defaultBranch: input.defaultBranch,\n providerMetadata: input.providerMetadata ?? {},\n updatedAt: now,\n });\n return existing;\n }\n const created: SourceControlRepository = {\n id: randomUUID(),\n installationId: input.installationId,\n externalId: input.externalId,\n slug: input.slug,\n defaultBranch: input.defaultBranch,\n providerMetadata: input.providerMetadata ?? {},\n createdAt: now,\n updatedAt: now,\n };\n this.repositoriesRows.push(created);\n return created;\n },\n };\n\n readonly connections = {\n list: async ({ factoryProjectId }: { orgId: string; factoryProjectId: string }) =>\n this.connectionsRows.filter(row => row.factoryProjectId === factoryProjectId),\n get: async ({ orgId, id }: { orgId: string; id: string }): Promise<ProjectSourceControlConnection | null> => {\n const row = this.connectionsRows.find(candidate => candidate.id === id);\n if (!row) return null;\n return (await this.installations.get({ orgId, id: row.installationId })) ? row : null;\n },\n create: async (input: CreateProjectSourceControlConnectionInput): Promise<ProjectSourceControlConnection> => {\n if (!(await this.installations.get({ orgId: input.orgId, id: input.installationId }))) {\n throw new Error('Source-control installation not found');\n }\n const existing = this.connectionsRows.find(\n row =>\n row.factoryProjectId === input.factoryProjectId &&\n row.integrationId === this.integrationId &&\n row.installationId === input.installationId,\n );\n if (existing) return existing;\n const created: ProjectSourceControlConnection = {\n id: randomUUID(),\n factoryProjectId: input.factoryProjectId,\n integrationId: this.integrationId,\n installationId: input.installationId,\n createdByUserId: input.createdByUserId,\n createdAt: new Date(),\n };\n this.connectionsRows.push(created);\n return created;\n },\n delete: async ({ orgId, id }: { orgId: string; id: string }): Promise<boolean> => {\n if (!(await this.connections.get({ orgId, id }))) return false;\n this.connectionsRows.splice(0, this.connectionsRows.length, ...this.connectionsRows.filter(row => row.id !== id));\n return true;\n },\n };\n\n readonly projectRepositories = {\n list: async ({ orgId, connectionId }: { orgId: string; connectionId: string }) =>\n (await this.connections.get({ orgId, id: connectionId }))\n ? this.projectRepositoriesRows.filter(row => row.connectionId === connectionId)\n : [],\n listConfiguredExternalKeys: async (): Promise<ConfiguredExternalRepositoryKey[]> => {\n const keys = new Map<string, ConfiguredExternalRepositoryKey>();\n for (const connection of this.connectionsRows.filter(row => row.integrationId === this.integrationId)) {\n const installation = this.installationsRows.find(row => row.id === connection.installationId);\n if (!installation) continue;\n for (const link of this.projectRepositoriesRows.filter(row => row.connectionId === connection.id)) {\n const repository = this.repositoriesRows.find(row => row.id === link.repositoryId);\n if (!repository) continue;\n keys.set(`${installation.externalId}\\u0000${repository.externalId}`, {\n installationExternalId: installation.externalId,\n repositoryExternalId: repository.externalId,\n });\n }\n }\n return [...keys.values()];\n },\n listByExternalRepository: async ({\n installationExternalId,\n repositoryExternalId,\n }: {\n installationExternalId: string;\n repositoryExternalId: string;\n }): Promise<ExternalRepositoryProjectTarget[]> => {\n const targets: ExternalRepositoryProjectTarget[] = [];\n for (const installation of this.installationsRows.filter(row => row.externalId === installationExternalId)) {\n const repository = this.repositoriesRows.find(\n row => row.installationId === installation.id && row.externalId === repositoryExternalId,\n );\n if (!repository) continue;\n for (const projectRepository of this.projectRepositoriesRows.filter(\n row => row.repositoryId === repository.id,\n )) {\n const connection = this.connectionsRows.find(\n row =>\n row.id === projectRepository.connectionId &&\n row.installationId === installation.id &&\n row.integrationId === this.integrationId,\n );\n if (!connection) continue;\n targets.push({\n orgId: installation.orgId,\n factoryProjectId: connection.factoryProjectId,\n projectRepository,\n });\n }\n }\n return targets;\n },\n get: async ({ orgId, id }: { orgId: string; id: string }): Promise<ProjectRepository | null> => {\n const row = this.projectRepositoriesRows.find(candidate => candidate.id === id);\n if (!row) return null;\n return (await this.connections.get({ orgId, id: row.connectionId })) ? row : null;\n },\n link: async (input: LinkProjectRepositoryInput): Promise<ProjectRepository> => {\n const connection = await this.connections.get({ orgId: input.orgId, id: input.connectionId });\n const repository = await this.repositories.get({ orgId: input.orgId, id: input.repositoryId });\n if (!connection || !repository || repository.installationId !== connection.installationId) {\n throw new Error('Source-control connection or repository not found');\n }\n const existing = this.projectRepositoriesRows.find(\n row => row.connectionId === input.connectionId && row.repositoryId === input.repositoryId,\n );\n if (existing) return existing;\n const now = new Date();\n const created: ProjectRepository = {\n id: randomUUID(),\n connectionId: input.connectionId,\n repositoryId: input.repositoryId,\n createdByUserId: input.createdByUserId,\n branch: input.branch ?? null,\n sandboxProvider: input.sandboxProvider,\n sandboxWorkdir: input.sandboxWorkdir,\n setupCommand: input.setupCommand ?? null,\n createdAt: now,\n updatedAt: now,\n };\n this.projectRepositoriesRows.push(created);\n return created;\n },\n update: async ({\n orgId,\n id,\n input,\n }: {\n orgId: string;\n id: string;\n input: UpdateProjectRepositoryInput;\n }): Promise<ProjectRepository | null> => {\n const row = await this.projectRepositories.get({ orgId, id });\n if (!row) return null;\n Object.assign(row, input, { updatedAt: new Date() });\n return row;\n },\n unlink: async ({ orgId, id }: { orgId: string; id: string }): Promise<boolean> => {\n if (!(await this.projectRepositories.get({ orgId, id }))) return false;\n this.projectRepositoriesRows.splice(\n 0,\n this.projectRepositoriesRows.length,\n ...this.projectRepositoriesRows.filter(row => row.id !== id),\n );\n return true;\n },\n };\n\n readonly sandboxes = {\n getOrCreate: async ({\n projectRepository,\n userId,\n }: {\n projectRepository: ProjectRepository;\n userId: string;\n }): Promise<ProjectRepositorySandbox> => {\n const existing = this.sandboxesRows.find(\n row => row.projectRepositoryId === projectRepository.id && row.userId === userId,\n );\n if (existing) return existing;\n const created: ProjectRepositorySandbox = {\n id: randomUUID(),\n projectRepositoryId: projectRepository.id,\n userId,\n sandboxId: null,\n sandboxWorkdir: projectRepository.sandboxWorkdir,\n materializedAt: null,\n createdAt: new Date(),\n };\n this.sandboxesRows.push(created);\n return created;\n },\n getById: async ({ id }: { id: string }): Promise<ProjectRepositorySandbox | null> =>\n this.sandboxesRows.find(row => row.id === id) ?? null,\n setWorkdir: async ({ id, sandboxWorkdir }: { id: string; sandboxWorkdir: string }): Promise<void> => {\n const row = this.sandboxesRows.find(candidate => candidate.id === id);\n if (row) Object.assign(row, { sandboxWorkdir, materializedAt: null });\n },\n setSandboxId: async ({ id, sandboxId }: { id: string; sandboxId: string }): Promise<void> => {\n const row = this.sandboxesRows.find(candidate => candidate.id === id);\n if (row) row.sandboxId = sandboxId;\n },\n clearBinding: async ({ id }: { id: string }): Promise<void> => {\n const row = this.sandboxesRows.find(candidate => candidate.id === id);\n if (row) Object.assign(row, { sandboxId: null, materializedAt: null });\n },\n markMaterialized: async ({ id }: { id: string }): Promise<void> => {\n const row = this.sandboxesRows.find(candidate => candidate.id === id);\n if (row) row.materializedAt = new Date();\n },\n };\n\n readonly worktrees = {\n upsert: async (input: UpsertSourceControlWorktreeInput): Promise<void> => {\n const existing = this.worktreesRows.find(\n row =>\n row.projectRepositoryId === input.projectRepositoryId &&\n row.userId === input.userId &&\n row.branch === input.branch,\n );\n if (existing) {\n existing.baseBranch = input.baseBranch;\n existing.worktreePath = input.worktreePath;\n return;\n }\n this.worktreesRows.push({ id: randomUUID(), createdAt: new Date(), ...input });\n },\n list: async ({\n projectRepositoryId,\n userId,\n }: {\n projectRepositoryId: string;\n userId: string;\n }): Promise<SourceControlWorktree[]> =>\n this.worktreesRows.filter(row => row.projectRepositoryId === projectRepositoryId && row.userId === userId),\n get: async ({\n projectRepositoryId,\n userId,\n branch,\n }: {\n projectRepositoryId: string;\n userId: string;\n branch: string;\n }): Promise<SourceControlWorktree | null> =>\n this.worktreesRows.find(\n row => row.projectRepositoryId === projectRepositoryId && row.userId === userId && row.branch === branch,\n ) ?? null,\n findByPath: async ({\n projectRepositoryId,\n userId,\n worktreePath,\n }: {\n projectRepositoryId: string;\n userId: string;\n worktreePath: string;\n }): Promise<SourceControlWorktree | null> =>\n this.worktreesRows.find(\n row =>\n row.projectRepositoryId === projectRepositoryId && row.userId === userId && row.worktreePath === worktreePath,\n ) ?? null,\n delete: async ({\n projectRepositoryId,\n userId,\n branch,\n }: {\n projectRepositoryId: string;\n userId: string;\n branch: string;\n }): Promise<void> => {\n this.worktreesRows.splice(\n 0,\n this.worktreesRows.length,\n ...this.worktreesRows.filter(\n row => !(row.projectRepositoryId === projectRepositoryId && row.userId === userId && row.branch === branch),\n ),\n );\n },\n };\n\n readonly sessions = {\n list: async ({ projectRepositoryId, userId }: { projectRepositoryId: string; userId: string }) =>\n this.sessionsRows.filter(row => row.projectRepositoryId === projectRepositoryId && row.userId === userId),\n getBySessionId: async (sessionId: string): Promise<SourceControlSession | null> =>\n this.sessionsRows.find(row => row.sessionId === sessionId) ?? null,\n getForBranch: async ({\n projectRepositoryId,\n userId,\n branch,\n }: {\n projectRepositoryId: string;\n userId: string;\n branch: string;\n }): Promise<SourceControlSession | null> =>\n this.sessionsRows.find(\n row => row.projectRepositoryId === projectRepositoryId && row.userId === userId && row.branch === branch,\n ) ?? null,\n create: async (input: CreateSourceControlSessionInput): Promise<SourceControlSession> => {\n const existing = await this.sessions.getForBranch(input);\n if (existing) return existing;\n const now = new Date();\n const session: SourceControlSession = {\n id: randomUUID(),\n ...input,\n sandboxId: null,\n sandboxWorkdir: null,\n materializedAt: null,\n createdAt: now,\n updatedAt: now,\n };\n this.sessionsRows.push(session);\n return session;\n },\n setSandbox: async ({\n id,\n sandboxId,\n sandboxWorkdir,\n }: {\n id: string;\n sandboxId: string | null;\n sandboxWorkdir: string;\n }) => {\n const row = this.sessionsRows.find(candidate => candidate.id === id);\n if (row) Object.assign(row, { sandboxId, sandboxWorkdir, updatedAt: new Date() });\n },\n markMaterialized: async ({ id }: { id: string }) => {\n const row = this.sessionsRows.find(candidate => candidate.id === id);\n if (row) Object.assign(row, { materializedAt: new Date(), updatedAt: new Date() });\n },\n delete: async (id: string) => {\n this.sessionsRows.splice(0, this.sessionsRows.length, ...this.sessionsRows.filter(row => row.id !== id));\n },\n };\n}\n"],"mappings":";;;AAuBA,IAAa,+BAAb,MAAgF;CAC9E;CACA,oBAAiD,CAAC;CAClD,mBAA8C,CAAC;CAC/C,kBAAoD,CAAC;CACrD,0BAA+C,CAAC;CAChD,gBAA4C,CAAC;CAC7C,gBAAyC,CAAC;CAC1C,eAAuC,CAAC;CAExC,YAAY,gBAAgB,UAAU;EACpC,KAAK,gBAAgB;CACvB;CAEA,gBAAyB;EACvB,MAAM,OAAO,EAAE,YACb,KAAK,kBAAkB,QAAO,QAAO,IAAI,UAAU,KAAK;EAC1D,KAAK,OAAO,EAAE,OAAO,SACnB,KAAK,kBAAkB,MAAK,QAAO,IAAI,UAAU,SAAS,IAAI,OAAO,EAAE,KAAK;EAC9E,kBAAkB,OAAO,EACvB,OACA,iBAKA,KAAK,kBAAkB,MAAK,QAAO,IAAI,UAAU,SAAS,IAAI,eAAe,UAAU,KAAK;EAC9F,QAAQ,OAAO,UAAoF;GAC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K,OAAO,OAAO,KAAK;IAAE;IAAW;IAAgB,2BAAW,IAAI,KAAK;GAAE,CAAC;EAClF;EACA,kBAAkB,OAAO,EAAE,SAAyB;GAClD,MAAM,MAAM,KAAK,aAAa,MAAK,cAAa,UAAU,OAAO,EAAE;GACnE,IAAI,KAAK,OAAO,OAAO,KAAK;IAAE,gCAAgB,IAAI,KAAK;IAAG,2BAAW,IAAI,KAAK;GAAE,CAAC;EACnF;EACA,QAAQ,OAAO,OAAe;GAC5B,KAAK,aAAa,OAAO,GAAG,KAAK,aAAa,QAAQ,GAAG,KAAK,aAAa,QAAO,QAAO,IAAI,OAAO,EAAE,CAAC;EACzG;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"inmemory.js","names":[],"sources":["../../../../src/storage/domains/source-control/inmemory.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type {\n ConfiguredExternalRepositoryKey,\n CreateProjectSourceControlConnectionInput,\n CreateSourceControlSessionInput,\n ExternalRepositoryProjectTarget,\n LinkProjectRepositoryInput,\n PooledSandbox,\n ProjectRepository,\n ProjectRepositorySandbox,\n ProjectSourceControlConnection,\n ReleasePooledSandboxInput,\n SourceControlInstallation,\n SourceControlRepository,\n SourceControlSession,\n SourceControlStorageHandle,\n SourceControlWorktree,\n UpdateProjectRepositoryInput,\n UpsertSourceControlInstallationInput,\n UpsertSourceControlRepositoryInput,\n UpsertSourceControlWorktreeInput,\n} from './base.js';\n\n/** In-memory provider-scoped source-control handle for route tests. */\nexport class SourceControlStorageInMemory implements SourceControlStorageHandle {\n readonly integrationId: string;\n installationsRows: SourceControlInstallation[] = [];\n repositoriesRows: SourceControlRepository[] = [];\n connectionsRows: ProjectSourceControlConnection[] = [];\n projectRepositoriesRows: ProjectRepository[] = [];\n sandboxesRows: ProjectRepositorySandbox[] = [];\n sandboxPoolRows: PooledSandbox[] = [];\n worktreesRows: SourceControlWorktree[] = [];\n sessionsRows: SourceControlSession[] = [];\n\n constructor(integrationId = 'github') {\n this.integrationId = integrationId;\n }\n\n readonly installations = {\n list: async ({ orgId }: { orgId: string }): Promise<SourceControlInstallation[]> =>\n this.installationsRows.filter(row => row.orgId === orgId),\n get: async ({ orgId, id }: { orgId: string; id: string }): Promise<SourceControlInstallation | null> =>\n this.installationsRows.find(row => row.orgId === orgId && row.id === id) ?? null,\n findByExternalId: async ({\n orgId,\n externalId,\n }: {\n orgId: string;\n externalId: string;\n }): Promise<SourceControlInstallation | null> =>\n this.installationsRows.find(row => row.orgId === orgId && row.externalId === externalId) ?? null,\n upsert: async (input: UpsertSourceControlInstallationInput): Promise<SourceControlInstallation> => {\n const existing = this.installationsRows.find(\n row => row.orgId === input.orgId && row.externalId === input.externalId,\n );\n if (existing) {\n Object.assign(existing, {\n connectedByUserId: input.connectedByUserId,\n accountName: input.accountName ?? null,\n accountType: input.accountType ?? null,\n providerMetadata: input.providerMetadata ?? {},\n });\n return existing;\n }\n const created: SourceControlInstallation = {\n id: randomUUID(),\n integrationId: this.integrationId,\n orgId: input.orgId,\n connectedByUserId: input.connectedByUserId,\n externalId: input.externalId,\n accountName: input.accountName ?? null,\n accountType: input.accountType ?? null,\n providerMetadata: input.providerMetadata ?? {},\n createdAt: new Date(),\n };\n this.installationsRows.push(created);\n return created;\n },\n delete: async ({ orgId, id }: { orgId: string; id: string }): Promise<boolean> => {\n const index = this.installationsRows.findIndex(row => row.orgId === orgId && row.id === id);\n if (index < 0) return false;\n this.installationsRows.splice(index, 1);\n return true;\n },\n };\n\n readonly repositories = {\n list: async ({ orgId, installationId }: { orgId: string; installationId: string }) => {\n const installation = await this.installations.get({ orgId, id: installationId });\n return installation ? this.repositoriesRows.filter(row => row.installationId === installationId) : [];\n },\n get: async ({ orgId, id }: { orgId: string; id: string }): Promise<SourceControlRepository | null> => {\n const row = this.repositoriesRows.find(candidate => candidate.id === id);\n if (!row) return null;\n return (await this.installations.get({ orgId, id: row.installationId })) ? row : null;\n },\n findByExternalId: async ({\n orgId,\n installationId,\n externalId,\n }: {\n orgId: string;\n installationId: string;\n externalId: string;\n }) => {\n const rows = await this.repositories.list({ orgId, installationId });\n return rows.find(row => row.externalId === externalId) ?? null;\n },\n findBySlug: async ({ orgId, installationId, slug }: { orgId: string; installationId: string; slug: string }) => {\n const rows = await this.repositories.list({ orgId, installationId });\n return rows.find(row => row.slug === slug) ?? null;\n },\n upsert: async ({\n orgId,\n input,\n }: {\n orgId: string;\n input: UpsertSourceControlRepositoryInput;\n }): Promise<SourceControlRepository> => {\n if (!(await this.installations.get({ orgId, id: input.installationId }))) {\n throw new Error('Source-control installation not found');\n }\n const existing = this.repositoriesRows.find(\n row => row.installationId === input.installationId && row.externalId === input.externalId,\n );\n const now = new Date();\n if (existing) {\n Object.assign(existing, {\n slug: input.slug,\n defaultBranch: input.defaultBranch,\n providerMetadata: input.providerMetadata ?? {},\n updatedAt: now,\n });\n return existing;\n }\n const created: SourceControlRepository = {\n id: randomUUID(),\n installationId: input.installationId,\n externalId: input.externalId,\n slug: input.slug,\n defaultBranch: input.defaultBranch,\n providerMetadata: input.providerMetadata ?? {},\n createdAt: now,\n updatedAt: now,\n };\n this.repositoriesRows.push(created);\n return created;\n },\n migrateInstallation: async ({\n orgId,\n id,\n newInstallationId,\n }: {\n orgId: string;\n id: string;\n newInstallationId: string;\n }) => {\n const existing = await this.repositories.get({ orgId, id });\n if (!existing) {\n throw new Error(`Repository ${id} not found in organization ${orgId}`);\n }\n if (!(await this.installations.get({ orgId, id: newInstallationId }))) {\n throw new Error('Source-control installation not found');\n }\n // Check if a repository with the same external_id exists under the new installation\n const conflict = this.repositoriesRows.find(\n row => row.installationId === newInstallationId && row.externalId === existing.externalId,\n );\n if (conflict) {\n // Return the existing repository under the new installation\n return conflict;\n }\n // Update the repository's installation\n existing.installationId = newInstallationId;\n existing.updatedAt = new Date();\n // Migrate dependent connections to the new installation\n for (const conn of this.connectionsRows) {\n if (conn.installationId === existing.installationId) {\n conn.installationId = newInstallationId;\n }\n }\n return existing;\n },\n };\n\n readonly connections = {\n list: async ({ factoryProjectId }: { orgId: string; factoryProjectId: string }) =>\n this.connectionsRows.filter(row => row.factoryProjectId === factoryProjectId),\n get: async ({ orgId, id }: { orgId: string; id: string }): Promise<ProjectSourceControlConnection | null> => {\n const row = this.connectionsRows.find(candidate => candidate.id === id);\n if (!row) return null;\n return (await this.installations.get({ orgId, id: row.installationId })) ? row : null;\n },\n create: async (input: CreateProjectSourceControlConnectionInput): Promise<ProjectSourceControlConnection> => {\n if (!(await this.installations.get({ orgId: input.orgId, id: input.installationId }))) {\n throw new Error('Source-control installation not found');\n }\n const existing = this.connectionsRows.find(\n row =>\n row.factoryProjectId === input.factoryProjectId &&\n row.integrationId === this.integrationId &&\n row.installationId === input.installationId,\n );\n if (existing) return existing;\n const created: ProjectSourceControlConnection = {\n id: randomUUID(),\n factoryProjectId: input.factoryProjectId,\n integrationId: this.integrationId,\n installationId: input.installationId,\n createdByUserId: input.createdByUserId,\n createdAt: new Date(),\n };\n this.connectionsRows.push(created);\n return created;\n },\n delete: async ({ orgId, id }: { orgId: string; id: string }): Promise<boolean> => {\n if (!(await this.connections.get({ orgId, id }))) return false;\n this.connectionsRows.splice(0, this.connectionsRows.length, ...this.connectionsRows.filter(row => row.id !== id));\n return true;\n },\n };\n\n readonly projectRepositories = {\n list: async ({ orgId, connectionId }: { orgId: string; connectionId: string }) =>\n (await this.connections.get({ orgId, id: connectionId }))\n ? this.projectRepositoriesRows.filter(row => row.connectionId === connectionId)\n : [],\n listConfiguredExternalKeys: async (): Promise<ConfiguredExternalRepositoryKey[]> => {\n const keys = new Map<string, ConfiguredExternalRepositoryKey>();\n for (const connection of this.connectionsRows.filter(row => row.integrationId === this.integrationId)) {\n const installation = this.installationsRows.find(row => row.id === connection.installationId);\n if (!installation) continue;\n for (const link of this.projectRepositoriesRows.filter(row => row.connectionId === connection.id)) {\n const repository = this.repositoriesRows.find(row => row.id === link.repositoryId);\n if (!repository) continue;\n keys.set(`${installation.externalId}\\u0000${repository.externalId}`, {\n installationExternalId: installation.externalId,\n repositoryExternalId: repository.externalId,\n });\n }\n }\n return [...keys.values()];\n },\n listByExternalRepository: async ({\n installationExternalId,\n repositoryExternalId,\n }: {\n installationExternalId: string;\n repositoryExternalId: string;\n }): Promise<ExternalRepositoryProjectTarget[]> => {\n const targets: ExternalRepositoryProjectTarget[] = [];\n for (const installation of this.installationsRows.filter(row => row.externalId === installationExternalId)) {\n const repository = this.repositoriesRows.find(\n row => row.installationId === installation.id && row.externalId === repositoryExternalId,\n );\n if (!repository) continue;\n for (const projectRepository of this.projectRepositoriesRows.filter(\n row => row.repositoryId === repository.id,\n )) {\n const connection = this.connectionsRows.find(\n row =>\n row.id === projectRepository.connectionId &&\n row.installationId === installation.id &&\n row.integrationId === this.integrationId,\n );\n if (!connection) continue;\n targets.push({\n orgId: installation.orgId,\n factoryProjectId: connection.factoryProjectId,\n projectRepository,\n });\n }\n }\n return targets;\n },\n get: async ({ orgId, id }: { orgId: string; id: string }): Promise<ProjectRepository | null> => {\n const row = this.projectRepositoriesRows.find(candidate => candidate.id === id);\n if (!row) return null;\n return (await this.connections.get({ orgId, id: row.connectionId })) ? row : null;\n },\n link: async (input: LinkProjectRepositoryInput): Promise<ProjectRepository> => {\n const connection = await this.connections.get({ orgId: input.orgId, id: input.connectionId });\n const repository = await this.repositories.get({ orgId: input.orgId, id: input.repositoryId });\n if (!connection || !repository || repository.installationId !== connection.installationId) {\n throw new Error('Source-control connection or repository not found');\n }\n const existing = this.projectRepositoriesRows.find(\n row => row.connectionId === input.connectionId && row.repositoryId === input.repositoryId,\n );\n if (existing) return existing;\n const now = new Date();\n const created: ProjectRepository = {\n id: randomUUID(),\n connectionId: input.connectionId,\n repositoryId: input.repositoryId,\n createdByUserId: input.createdByUserId,\n branch: input.branch ?? null,\n sandboxProvider: input.sandboxProvider,\n sandboxWorkdir: input.sandboxWorkdir,\n setupCommand: input.setupCommand ?? null,\n createdAt: now,\n updatedAt: now,\n };\n this.projectRepositoriesRows.push(created);\n return created;\n },\n update: async ({\n orgId,\n id,\n input,\n }: {\n orgId: string;\n id: string;\n input: UpdateProjectRepositoryInput;\n }): Promise<ProjectRepository | null> => {\n const row = await this.projectRepositories.get({ orgId, id });\n if (!row) return null;\n Object.assign(row, input, { updatedAt: new Date() });\n return row;\n },\n unlink: async ({ orgId, id }: { orgId: string; id: string }): Promise<boolean> => {\n if (!(await this.projectRepositories.get({ orgId, id }))) return false;\n this.projectRepositoriesRows.splice(\n 0,\n this.projectRepositoriesRows.length,\n ...this.projectRepositoriesRows.filter(row => row.id !== id),\n );\n return true;\n },\n };\n\n readonly sandboxes = {\n getOrCreate: async ({\n projectRepository,\n userId,\n }: {\n projectRepository: ProjectRepository;\n userId: string;\n }): Promise<ProjectRepositorySandbox> => {\n const existing = this.sandboxesRows.find(\n row => row.projectRepositoryId === projectRepository.id && row.userId === userId,\n );\n if (existing) return existing;\n const created: ProjectRepositorySandbox = {\n id: randomUUID(),\n projectRepositoryId: projectRepository.id,\n userId,\n sandboxId: null,\n sandboxWorkdir: projectRepository.sandboxWorkdir,\n materializedAt: null,\n createdAt: new Date(),\n };\n this.sandboxesRows.push(created);\n return created;\n },\n getById: async ({ id }: { id: string }): Promise<ProjectRepositorySandbox | null> =>\n this.sandboxesRows.find(row => row.id === id) ?? null,\n setWorkdir: async ({ id, sandboxWorkdir }: { id: string; sandboxWorkdir: string }): Promise<void> => {\n const row = this.sandboxesRows.find(candidate => candidate.id === id);\n if (row) Object.assign(row, { sandboxWorkdir, materializedAt: null });\n },\n setSandboxId: async ({ id, sandboxId }: { id: string; sandboxId: string }): Promise<void> => {\n const row = this.sandboxesRows.find(candidate => candidate.id === id);\n if (row) row.sandboxId = sandboxId;\n },\n clearBinding: async ({ id }: { id: string }): Promise<void> => {\n const row = this.sandboxesRows.find(candidate => candidate.id === id);\n if (row) Object.assign(row, { sandboxId: null, materializedAt: null });\n },\n markMaterialized: async ({ id }: { id: string }): Promise<void> => {\n const row = this.sandboxesRows.find(candidate => candidate.id === id);\n if (row) row.materializedAt = new Date();\n },\n };\n\n readonly sandboxPool = {\n release: async (input: ReleasePooledSandboxInput): Promise<void> => {\n // Mirror the SQL implementation: a missing project-repository link\n // makes the release a silent no-op.\n if (!this.projectRepositoriesRows.some(row => row.id === input.projectRepositoryId)) return;\n if (this.sandboxPoolRows.some(row => row.sandboxId === input.sandboxId)) return;\n this.sandboxPoolRows.push({ id: randomUUID(), releasedAt: new Date(), ...input });\n },\n claim: async ({ projectRepositoryId }: { projectRepositoryId: string }): Promise<PooledSandbox | null> => {\n const candidates = this.sandboxPoolRows\n .filter(row => row.projectRepositoryId === projectRepositoryId)\n .sort((left, right) => right.releasedAt.getTime() - left.releasedAt.getTime());\n const claimed = candidates[0];\n if (!claimed) return null;\n this.sandboxPoolRows.splice(this.sandboxPoolRows.indexOf(claimed), 1);\n return claimed;\n },\n };\n\n readonly worktrees = {\n upsert: async (input: UpsertSourceControlWorktreeInput): Promise<void> => {\n const existing = this.worktreesRows.find(\n row =>\n row.projectRepositoryId === input.projectRepositoryId &&\n row.userId === input.userId &&\n row.branch === input.branch,\n );\n if (existing) {\n existing.baseBranch = input.baseBranch;\n existing.worktreePath = input.worktreePath;\n return;\n }\n this.worktreesRows.push({ id: randomUUID(), createdAt: new Date(), ...input });\n },\n list: async ({\n projectRepositoryId,\n userId,\n }: {\n projectRepositoryId: string;\n userId: string;\n }): Promise<SourceControlWorktree[]> =>\n this.worktreesRows.filter(row => row.projectRepositoryId === projectRepositoryId && row.userId === userId),\n get: async ({\n projectRepositoryId,\n userId,\n branch,\n }: {\n projectRepositoryId: string;\n userId: string;\n branch: string;\n }): Promise<SourceControlWorktree | null> =>\n this.worktreesRows.find(\n row => row.projectRepositoryId === projectRepositoryId && row.userId === userId && row.branch === branch,\n ) ?? null,\n findByPath: async ({\n projectRepositoryId,\n userId,\n worktreePath,\n }: {\n projectRepositoryId: string;\n userId: string;\n worktreePath: string;\n }): Promise<SourceControlWorktree | null> =>\n this.worktreesRows.find(\n row =>\n row.projectRepositoryId === projectRepositoryId && row.userId === userId && row.worktreePath === worktreePath,\n ) ?? null,\n delete: async ({\n projectRepositoryId,\n userId,\n branch,\n }: {\n projectRepositoryId: string;\n userId: string;\n branch: string;\n }): Promise<void> => {\n this.worktreesRows.splice(\n 0,\n this.worktreesRows.length,\n ...this.worktreesRows.filter(\n row => !(row.projectRepositoryId === projectRepositoryId && row.userId === userId && row.branch === branch),\n ),\n );\n },\n };\n\n readonly sessions = {\n list: async ({ projectRepositoryId, userId }: { projectRepositoryId: string; userId: string }) =>\n this.sessionsRows.filter(row => row.projectRepositoryId === projectRepositoryId && row.userId === userId),\n getBySessionId: async (sessionId: string): Promise<SourceControlSession | null> =>\n this.sessionsRows.find(row => row.sessionId === sessionId) ?? null,\n getForBranch: async ({\n projectRepositoryId,\n userId,\n branch,\n }: {\n projectRepositoryId: string;\n userId: string;\n branch: string;\n }): Promise<SourceControlSession | null> =>\n this.sessionsRows.find(\n row => row.projectRepositoryId === projectRepositoryId && row.userId === userId && row.branch === branch,\n ) ?? null,\n create: async (input: CreateSourceControlSessionInput): Promise<SourceControlSession> => {\n const existing = await this.sessions.getForBranch(input);\n if (existing) return existing;\n const now = new Date();\n const session: SourceControlSession = {\n id: randomUUID(),\n ...input,\n sandboxId: null,\n sandboxWorkdir: null,\n materializedAt: null,\n createdAt: now,\n updatedAt: now,\n };\n this.sessionsRows.push(session);\n return session;\n },\n setSandbox: async ({\n id,\n sandboxId,\n sandboxWorkdir,\n }: {\n id: string;\n sandboxId: string | null;\n sandboxWorkdir: string;\n }) => {\n const row = this.sessionsRows.find(candidate => candidate.id === id);\n if (row) Object.assign(row, { sandboxId, sandboxWorkdir, updatedAt: new Date() });\n },\n markMaterialized: async ({ id }: { id: string }) => {\n const row = this.sessionsRows.find(candidate => candidate.id === id);\n if (row) Object.assign(row, { materializedAt: new Date(), updatedAt: new Date() });\n },\n delete: async (id: string) => {\n this.sessionsRows.splice(0, this.sessionsRows.length, ...this.sessionsRows.filter(row => row.id !== id));\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ChE,cAAc,OAAO,EACnB,qBACA,QACA,aAMA,KAAK,aAAa,MAChB,QAAO,IAAI,wBAAwB,uBAAuB,IAAI,WAAW,UAAU,IAAI,WAAW,MACpG,KAAK;EACP,QAAQ,OAAO,UAA0E;GACvF,MAAM,WAAW,MAAM,KAAK,SAAS,aAAa,KAAK;GACvD,IAAI,UAAU,OAAO;GACrB,MAAM,sBAAM,IAAI,KAAK;GACrB,MAAM,UAAgC;IACpC,IAAI,WAAW;IACf,GAAG;IACH,WAAW;IACX,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;IACX,WAAW;GACb;GACA,KAAK,aAAa,KAAK,OAAO;GAC9B,OAAO;EACT;EACA,YAAY,OAAO,EACjB,IACA,WACA,qBAKI;GACJ,MAAM,MAAM,KAAK,aAAa,MAAK,cAAa,UAAU,OAAO,EAAE;GACnE,IAAI,KAAK,OAAO,OAAO,KAAK;IAAE;IAAW;IAAgB,2BAAW,IAAI,KAAK;GAAE,CAAC;EAClF;EACA,kBAAkB,OAAO,EAAE,SAAyB;GAClD,MAAM,MAAM,KAAK,aAAa,MAAK,cAAa,UAAU,OAAO,EAAE;GACnE,IAAI,KAAK,OAAO,OAAO,KAAK;IAAE,gCAAgB,IAAI,KAAK;IAAG,2BAAW,IAAI,KAAK;GAAE,CAAC;EACnF;EACA,QAAQ,OAAO,OAAe;GAC5B,KAAK,aAAa,OAAO,GAAG,KAAK,aAAa,QAAQ,GAAG,KAAK,aAAa,QAAO,QAAO,IAAI,OAAO,EAAE,CAAC;EACzG;CACF;AACF"}
|
package/dist/workspace.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,OAAO,EAAE,YAAY,EAAoB,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAInF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;
|
|
1
|
+
{"version":3,"file":"workspace.d.ts","sourceRoot":"","sources":["../src/workspace.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,OAAO,EAAE,YAAY,EAAoB,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAInF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sCAAsC,CAAC;AAY9E,OAAO,KAAK,EAAuB,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAK7E,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AA+ED,KAAK,uBAAuB,GAAG,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC;AAEzE,MAAM,WAAW,6BAA6B;IAC5C,wEAAwE;IACxE,OAAO,CAAC,EAAE,0BAA0B,CAAC;IACrC,gFAAgF;IAChF,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B,0EAA0E;IAC1E,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB;;iEAE6D;IAC7D,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,yBAAyB,CAAC,CAAC;CAC/D;AAED,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,6BAAkC,IAYlE,4CAA4C,uBAAuB,2PAoPlF;AAED,eAAO,MAAM,mBAAmB,+CAtP4B,uBAAuB,0PAsPxB,CAAC"}
|
package/dist/workspace.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { getFactoryAuthUserId } from "./auth.js";
|
|
2
2
|
import { getGithubPat } from "./integrations/github/pat.js";
|
|
3
3
|
import { registerGithubPatKind, registerGithubTokenInjector } from "./integrations/github/token-refresh.js";
|
|
4
|
-
import { MaterializeError, checkoutSessionBranch, materializeRepo, runWorktreeSetup } from "./integrations/github/sandbox.js";
|
|
4
|
+
import { MaterializeError, checkoutSessionBranch, materializeRepo, recycleClaimedWorkdir, runWorktreeSetup } from "./integrations/github/sandbox.js";
|
|
5
5
|
import { getFactorySessionAddress } from "./rules/binding-context.js";
|
|
6
|
-
import path, { dirname, join } from "path";
|
|
7
6
|
import { LocalSandbox, LocalSkillSource, Workspace } from "@mastra/core/workspace";
|
|
7
|
+
import path, { dirname, join } from "path";
|
|
8
8
|
import { DEFAULT_CONFIG_DIR } from "@mastra/code-sdk/constants";
|
|
9
9
|
import { SandboxFilesystem } from "@mastra/code-sdk/agents/sandbox-filesystem";
|
|
10
10
|
import { existsSync } from "fs";
|
|
@@ -112,7 +112,7 @@ function createWorkspaceFactory(options = {}) {
|
|
|
112
112
|
id: connection.installationId
|
|
113
113
|
})) throw new Error(`GitHub installation ${connection.installationId} was not found`);
|
|
114
114
|
const repoFullName = repository.slug;
|
|
115
|
-
|
|
115
|
+
let workdir = isLocalSandbox ? fleet.computeLocalSessionWorkdir(repoFullName, session.id) : session.sandboxWorkdir ?? projectRepository.sandboxWorkdir;
|
|
116
116
|
if (ctx && workdir && ctx.getState()?.projectPath !== workdir) await ctx.setState({
|
|
117
117
|
projectPath: workdir,
|
|
118
118
|
projectName: repoFullName
|
|
@@ -160,6 +160,21 @@ function createWorkspaceFactory(options = {}) {
|
|
|
160
160
|
}
|
|
161
161
|
} catch {}
|
|
162
162
|
const materialize = async () => {
|
|
163
|
+
let claimedPooledSandbox = false;
|
|
164
|
+
if (!isLocalSandbox && !session.sandboxId) {
|
|
165
|
+
const pooled = await storage.sandboxPool.claim({ projectRepositoryId: session.projectRepositoryId });
|
|
166
|
+
if (pooled) {
|
|
167
|
+
await storage.sessions.setSandbox({
|
|
168
|
+
id: session.id,
|
|
169
|
+
sandboxId: pooled.sandboxId,
|
|
170
|
+
sandboxWorkdir: pooled.sandboxWorkdir
|
|
171
|
+
});
|
|
172
|
+
session.sandboxId = pooled.sandboxId;
|
|
173
|
+
session.sandboxWorkdir = pooled.sandboxWorkdir;
|
|
174
|
+
workdir = pooled.sandboxWorkdir;
|
|
175
|
+
claimedPooledSandbox = true;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
163
178
|
const token = (await github.versionControl.getRepositoryAccess({
|
|
164
179
|
orgId: session.orgId,
|
|
165
180
|
repositoryId: repository.id
|
|
@@ -189,6 +204,7 @@ function createWorkspaceFactory(options = {}) {
|
|
|
189
204
|
});
|
|
190
205
|
const isGitMissing = (error) => error instanceof MaterializeError && error.code === "git-missing";
|
|
191
206
|
let sandbox = await ensureSandbox();
|
|
207
|
+
if (claimedPooledSandbox) await recycleClaimedWorkdir(sandbox, workdir, repository.defaultBranch);
|
|
192
208
|
try {
|
|
193
209
|
await runMaterialize(sandbox);
|
|
194
210
|
} catch (error) {
|
package/dist/workspace.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.js","names":["#factorySource","#fallbackSkillRoots","#isFactoryPath","#factoryPath"],"sources":["../src/workspace.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { SandboxFilesystem } from '@mastra/code-sdk/agents/sandbox-filesystem';\nimport { MASTRACODE_WORKSPACE_TOOLS } from '@mastra/code-sdk/agents/tool-availability';\nimport { getDynamicWorkspace } from '@mastra/code-sdk/agents/workspace';\nimport type { WorkspaceSkillExtension } from '@mastra/code-sdk/agents/workspace';\nimport { DEFAULT_CONFIG_DIR } from '@mastra/code-sdk/constants';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { LocalSandbox, LocalSkillSource, Workspace } from '@mastra/core/workspace';\nimport type { SkillSource, SkillSourceEntry, SkillSourceStat } from '@mastra/core/workspace';\nimport { getFactoryAuthUserId } from './auth.js';\nimport type { FactoryAuthUser } from './auth.js';\nimport type { MastraFactorySandboxConfig } from './factory.js';\nimport type { GithubIntegration } from './integrations/github/integration.js';\nimport { getGithubPat } from './integrations/github/pat.js';\nimport type { GithubPatKind } from './integrations/github/pat.js';\nimport {\n checkoutSessionBranch,\n MaterializeError,\n materializeRepo,\n runWorktreeSetup,\n} from './integrations/github/sandbox.js';\nimport { registerGithubPatKind, registerGithubTokenInjector } from './integrations/github/token-refresh.js';\nimport { getFactorySessionAddress } from './rules/binding-context.js';\nimport type { SandboxBindingStore, SandboxFleet } from './sandbox/fleet.js';\nimport type { WorkItemsStorage } from './storage/domains/work-items/base.js';\n\nconst WORKSPACE_ID_PREFIX = 'mfw';\nconst SESSION_CHECKPOINT_PREFIX = 'mastracode-session';\n\nexport function checkpointNameForSession(sessionId: string): string {\n return `${SESSION_CHECKPOINT_PREFIX}-${sessionId}`;\n}\n\nconst bundleDirectory = dirname(fileURLToPath(import.meta.url));\nconst bundledFactorySkillsPath = join(bundleDirectory, 'factory-skills');\nconst FACTORY_SKILLS_SOURCE_PATH =\n [\n // Deploy bundle: the consumer copies `factory-skills/` next to the built\n // server module (e.g. via its public/ dir).\n bundledFactorySkillsPath,\n // Package layout: `dist/../factory-skills` (also `src/../factory-skills`\n // when running tests against sources).\n join(bundleDirectory, '..', 'factory-skills'),\n // Consumer repo running from its package root before a build.\n join(process.cwd(), 'src', 'mastra', 'public', 'factory-skills'),\n ].find(existsSync) ?? bundledFactorySkillsPath;\nconst FACTORY_SKILLS_MOUNT = path.resolve(path.parse(process.cwd()).root, '__mastracode_factory_skills__');\nconst FACTORY_SKILL_NAMES = new Set(['configure-factory-rules', 'factory-plan', 'factory-review', 'factory-triage']);\n\nclass FactorySkillSource implements SkillSource {\n readonly #factorySource = new LocalSkillSource({ basePath: FACTORY_SKILLS_SOURCE_PATH });\n readonly #fallbackSkillRoots: Set<string>;\n\n constructor(\n readonly fallback: SkillSource,\n fallbackSkillRoots: string[],\n ) {\n this.#fallbackSkillRoots = new Set(fallbackSkillRoots.map(skillPath => path.normalize(skillPath)));\n }\n\n #isFactoryPath(skillPath: string): boolean {\n const normalized = path.normalize(skillPath);\n return normalized === FACTORY_SKILLS_MOUNT || normalized.startsWith(`${FACTORY_SKILLS_MOUNT}${path.sep}`);\n }\n\n #factoryPath(skillPath: string): string {\n return path.relative(FACTORY_SKILLS_MOUNT, path.normalize(skillPath));\n }\n\n exists(skillPath: string): Promise<boolean> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.exists(this.#factoryPath(skillPath))\n : this.fallback.exists(skillPath);\n }\n\n stat(skillPath: string): Promise<SkillSourceStat> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.stat(this.#factoryPath(skillPath))\n : this.fallback.stat(skillPath);\n }\n\n readFile(skillPath: string): Promise<string | Buffer> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.readFile(this.#factoryPath(skillPath))\n : this.fallback.readFile(skillPath);\n }\n\n async readdir(skillPath: string): Promise<SkillSourceEntry[]> {\n if (this.#isFactoryPath(skillPath)) {\n return this.#factorySource.readdir(this.#factoryPath(skillPath));\n }\n const entries = await this.fallback.readdir(skillPath);\n if (this.#fallbackSkillRoots.has(path.normalize(skillPath))) {\n return entries.filter(entry => !FACTORY_SKILL_NAMES.has(entry.name));\n }\n return entries;\n }\n\n realpath(skillPath: string): Promise<string> {\n if (this.#isFactoryPath(skillPath)) return Promise.resolve(path.normalize(skillPath));\n return this.fallback.realpath ? this.fallback.realpath(skillPath) : Promise.resolve(skillPath);\n }\n}\n\nconst factorySkillExtension: WorkspaceSkillExtension = {\n id: 'web-factory',\n paths: [FACTORY_SKILLS_MOUNT],\n createSource: (fallback, fallbackSkillRoots) => new FactorySkillSource(fallback, fallbackSkillRoots),\n};\n\ntype DynamicWorkspaceContext = Parameters<typeof getDynamicWorkspace>[0];\n\nexport interface CreateWorkspaceFactoryOptions {\n /** Factory sandbox runtime config (template machine + workdir base). */\n sandbox?: MastraFactorySandboxConfig;\n /** GitHub integration used to resolve Factory sessions and mint repo tokens. */\n github?: GithubIntegration;\n /** Fleet the per-session sandboxes are provisioned/reattached through. */\n fleet?: SandboxFleet;\n /** Work-items storage used to resolve the session's run-binding role, so\n * review-board sessions get the reviewer PAT as `GH_TOKEN`. Optional —\n * without it every session uses the default (worker) PAT. */\n workItems?: Pick<WorkItemsStorage, 'findRunBindingBySession'>;\n}\n\nexport function createWorkspaceFactory(options: CreateWorkspaceFactoryOptions = {}) {\n const { sandbox: sandboxConfig, github, fleet, workItems } = options;\n const isLocalSandbox = sandboxConfig?.machine instanceof LocalSandbox;\n const githubTokenInjectors = new Map<\n string,\n { inject: (token: string) => void; patKind: GithubPatKind; ghToken: string }\n >();\n // Concurrent requests for the same session (thread list + activity polling +\n // chat) must not each provision a sandbox and clone the repository. The\n // first caller materializes; followers await the same promise.\n const inflightMaterializations = new Map<string, Promise<Workspace>>();\n\n return async ({ requestContext, mastra, skillExtension }: DynamicWorkspaceContext) => {\n const effectiveSkillExtension = skillExtension ?? factorySkillExtension;\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const session =\n ctx?.resourceId && github ? await github.sourceControlStorage.sessions.getBySessionId(ctx.resourceId) : null;\n\n if (!session) {\n if (sandboxConfig && !isLocalSandbox) {\n throw new Error('A Factory session ID is required to create a remote sandbox workspace');\n }\n return getDynamicWorkspace({ requestContext, mastra, skillExtension: effectiveSkillExtension });\n }\n\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n const userId = getFactoryAuthUserId(user);\n if (!user?.organizationId || !userId || user.organizationId !== session.orgId || userId !== session.userId) {\n throw new Error(`Factory session ${session.sessionId} is not available to the current user`);\n }\n if (!sandboxConfig || !github || !fleet) {\n throw new Error('GitHub and sandbox providers are required to create a Factory session workspace');\n }\n\n const storage = github.sourceControlStorage;\n const projectRepository = await storage.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) throw new Error(`Repository link ${session.projectRepositoryId} was not found`);\n const connection = await storage.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n const repository = await storage.repositories.get({ orgId: session.orgId, id: projectRepository.repositoryId });\n if (!connection || !repository) throw new Error(`Repository link ${session.projectRepositoryId} is incomplete`);\n const installation = await storage.installations.get({ orgId: session.orgId, id: connection.installationId });\n if (!installation) throw new Error(`GitHub installation ${connection.installationId} was not found`);\n const repoFullName = repository.slug;\n\n const workdir = isLocalSandbox\n ? fleet.computeLocalSessionWorkdir(repoFullName, session.id)\n : (session.sandboxWorkdir ?? projectRepository.sandboxWorkdir);\n // The system prompt derives its working directory from `state.projectPath`\n // and falls back to the server's own process.cwd() when unset — which\n // points the agent at the host checkout (and lets it run `git checkout`\n // there instead of in its session workdir). Pin it to the session workdir.\n // During createSession this seeds the session's initial state (the\n // workspace resolves before the session is built); on later requests it\n // self-heals live state.\n if (ctx && workdir && ctx.getState()?.projectPath !== workdir) {\n await ctx.setState({ projectPath: workdir, projectName: repoFullName });\n }\n const binding: SandboxBindingStore = {\n // Read through to the session row so teardown after a fresh provision\n // sees the just-persisted id instead of a stale snapshot.\n get sandboxId() {\n return session.sandboxId;\n },\n checkpointName: checkpointNameForSession(session.id),\n setSandboxId: async id => {\n await storage.sessions.setSandbox({ id: session.id, sandboxId: id, sandboxWorkdir: workdir });\n session.sandboxId = id;\n session.sandboxWorkdir = workdir;\n },\n clear: async () => {\n await storage.sessions.setSandbox({ id: session.id, sandboxId: null, sandboxWorkdir: workdir });\n session.sandboxId = null;\n },\n };\n\n const extensionId = effectiveSkillExtension ? `-${effectiveSkillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectRepository.id}-${session.id}${extensionId}`;\n const configDir = sandboxConfig.workdir ?? DEFAULT_CONFIG_DIR;\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) {\n registerGithubTokenInjector(requestContext, registered.inject);\n registerGithubPatKind(requestContext, registered.patKind);\n // A PAT saved in Settings after this sandbox was provisioned must\n // reach the running sandbox without a server restart — re-read it\n // on every reuse and push it into the live sandbox when it changed.\n // Best-effort: a failed read or inject keeps the installed token.\n try {\n const pat = await getGithubPat(() => github.integrationStorage, session.orgId, registered.patKind);\n if (pat && pat !== registered.ghToken) {\n registered.inject(pat);\n }\n } catch {\n // Keep the token already installed in the sandbox.\n }\n }\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const materialize = async (): Promise<Workspace> => {\n const access = await github.versionControl.getRepositoryAccess({\n orgId: session.orgId,\n repositoryId: repository.id,\n });\n const token = access.authorization?.token;\n if (!token) throw new Error('Repository access did not include a bearer token for the Factory session');\n\n // The `gh` CLI needs a PAT when the org configured one (installation\n // tokens 403 on integration-restricted endpoints); git clone/checkout\n // below keep using the minted installation token. Review-board sessions\n // (run-binding role `review`) authenticate `gh` as the reviewer account\n // when a reviewer token is configured; everything else — including\n // sessions with no resolvable run binding — uses the worker token.\n let patKind: GithubPatKind = 'default';\n if (workItems) {\n try {\n const address = getFactorySessionAddress(requestContext);\n const runBinding = address ? await workItems.findRunBindingBySession(address) : null;\n if (runBinding?.role === 'review' && runBinding.orgId === session.orgId) patKind = 'reviewer';\n } catch {\n // No resolvable binding — worker token.\n }\n }\n const ghCliToken = (await getGithubPat(() => github.integrationStorage, session.orgId, patKind)) ?? token;\n\n const ensureSandbox = () =>\n fleet.ensureSandbox(\n binding,\n { GH_TOKEN: ghCliToken },\n undefined,\n isLocalSandbox ? { workingDirectory: workdir } : {},\n );\n const runMaterialize = (target: Awaited<ReturnType<typeof ensureSandbox>>) =>\n materializeRepo({\n row: { id: session.id, sandboxWorkdir: workdir, materializedAt: session.materializedAt },\n repoInfo: { repoFullName: repoFullName, defaultBranch: repository.defaultBranch },\n sandbox: target,\n token,\n storage: storage.sessions,\n });\n const isGitMissing = (error: unknown) => error instanceof MaterializeError && error.code === 'git-missing';\n\n let sandbox = await ensureSandbox();\n try {\n await runMaterialize(sandbox);\n } catch (error) {\n if (!isGitMissing(error)) throw error;\n // A sandbox without git was booted from a bare base image (e.g. the\n // platform proxy falls back to a clean Debian base when its template\n // build fails). That VM can never materialize a repo, and its id is\n // already persisted on the binding — tear it down so re-opens stop\n // reattaching to the poisoned sandbox, then retry once on a fresh VM.\n await fleet.teardownSandbox(binding, sandbox);\n sandbox = await ensureSandbox();\n try {\n await runMaterialize(sandbox);\n } catch (retryError) {\n // Still bare — the provider's template is persistently broken.\n // Clear the binding so a later manual retry provisions fresh.\n if (isGitMissing(retryError)) await fleet.teardownSandbox(binding, sandbox);\n throw retryError;\n }\n }\n await checkoutSessionBranch(sandbox, workdir, {\n branch: session.branch,\n baseBranch: session.baseBranch || projectRepository.branch || repository.defaultBranch,\n token,\n repoFullName: repoFullName,\n });\n if (projectRepository.setupCommand) await runWorktreeSetup(sandbox, workdir, projectRepository.setupCommand);\n\n const injectGithubToken = (freshToken: string) => {\n if (!sandbox.setEnvironmentVariable) {\n throw new Error('The active sandbox provider does not support runtime GitHub token refresh.');\n }\n sandbox.setEnvironmentVariable('GH_TOKEN', freshToken);\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) registered.ghToken = freshToken;\n };\n githubTokenInjectors.set(workspaceId, { inject: injectGithubToken, patKind, ghToken: ghCliToken });\n registerGithubTokenInjector(requestContext, injectGithubToken);\n registerGithubPatKind(requestContext, patKind);\n\n const filesystem = new SandboxFilesystem({ sandbox, workdir });\n const projectSkillPaths = [path.join(configDir, 'skills'), '.claude/skills', '.agents/skills'];\n const skillPaths = [...(effectiveSkillExtension?.paths ?? []), ...projectSkillPaths];\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Factory Session Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n skills: skillPaths,\n skillSource: effectiveSkillExtension?.createSource(filesystem, projectSkillPaths) ?? filesystem,\n });\n };\n\n // Dedupe concurrent materializations of the same workspace: followers\n // await the leader's promise instead of provisioning a second sandbox,\n // then bind the shared token injector into their own request context.\n const inflight = inflightMaterializations.get(workspaceId);\n if (inflight) {\n const workspace = await inflight;\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) {\n registerGithubTokenInjector(requestContext, registered.inject);\n registerGithubPatKind(requestContext, registered.patKind);\n }\n return workspace;\n }\n const materialization = materialize();\n inflightMaterializations.set(workspaceId, materialization);\n try {\n return await materialization;\n } finally {\n inflightMaterializations.delete(workspaceId);\n }\n };\n}\n\nexport const getFactoryWorkspace = createWorkspaceFactory();\n"],"mappings":";;;;;;;;;;;;;;AA6BA,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAElC,SAAgB,yBAAyB,WAA2B;CAClE,OAAO,GAAG,0BAA0B,GAAG;AACzC;AAEA,MAAM,kBAAkB,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;AAC9D,MAAM,2BAA2B,KAAK,iBAAiB,gBAAgB;AACvE,MAAM,6BACJ;CAGE;CAGA,KAAK,iBAAiB,MAAM,gBAAgB;CAE5C,KAAK,QAAQ,IAAI,GAAG,OAAO,UAAU,UAAU,gBAAgB;AACjE,CAAC,CAAC,KAAK,UAAU,KAAK;AACxB,MAAM,uBAAuB,KAAK,QAAQ,KAAK,MAAM,QAAQ,IAAI,CAAC,CAAC,CAAC,MAAM,+BAA+B;AACzG,MAAM,sCAAsB,IAAI,IAAI;CAAC;CAA2B;CAAgB;CAAkB;AAAgB,CAAC;AAEnH,IAAM,qBAAN,MAAgD;CAKnC;CAJX,iBAA0B,IAAI,iBAAiB,EAAE,UAAU,2BAA2B,CAAC;CACvF;CAEA,YACE,UACA,oBACA;EAFS,KAAA,WAAA;EAGT,KAAKC,sBAAsB,IAAI,IAAI,mBAAmB,KAAI,cAAa,KAAK,UAAU,SAAS,CAAC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AAW,OAAO;GAC1D;GACA,OAAO;EACT;EACA,MAAM,kBAAkB,YAAY;EACpC,yBAAyB,IAAI,aAAa,eAAe;EACzD,IAAI;GACF,OAAO,MAAM;EACf,UAAU;GACR,yBAAyB,OAAO,WAAW;EAC7C;CACF;AACF;AAEA,MAAa,sBAAsB,uBAAuB"}
|
|
1
|
+
{"version":3,"file":"workspace.js","names":["#factorySource","#fallbackSkillRoots","#isFactoryPath","#factoryPath"],"sources":["../src/workspace.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { SandboxFilesystem } from '@mastra/code-sdk/agents/sandbox-filesystem';\nimport { MASTRACODE_WORKSPACE_TOOLS } from '@mastra/code-sdk/agents/tool-availability';\nimport { getDynamicWorkspace } from '@mastra/code-sdk/agents/workspace';\nimport type { WorkspaceSkillExtension } from '@mastra/code-sdk/agents/workspace';\nimport { DEFAULT_CONFIG_DIR } from '@mastra/code-sdk/constants';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { LocalSandbox, LocalSkillSource, Workspace } from '@mastra/core/workspace';\nimport type { SkillSource, SkillSourceEntry, SkillSourceStat } from '@mastra/core/workspace';\nimport { getFactoryAuthUserId } from './auth.js';\nimport type { FactoryAuthUser } from './auth.js';\nimport type { MastraFactorySandboxConfig } from './factory.js';\nimport type { GithubIntegration } from './integrations/github/integration.js';\nimport { getGithubPat } from './integrations/github/pat.js';\nimport type { GithubPatKind } from './integrations/github/pat.js';\nimport {\n checkoutSessionBranch,\n MaterializeError,\n materializeRepo,\n recycleClaimedWorkdir,\n runWorktreeSetup,\n} from './integrations/github/sandbox.js';\nimport { registerGithubPatKind, registerGithubTokenInjector } from './integrations/github/token-refresh.js';\nimport { getFactorySessionAddress } from './rules/binding-context.js';\nimport type { SandboxBindingStore, SandboxFleet } from './sandbox/fleet.js';\nimport type { WorkItemsStorage } from './storage/domains/work-items/base.js';\n\nconst WORKSPACE_ID_PREFIX = 'mfw';\nconst SESSION_CHECKPOINT_PREFIX = 'mastracode-session';\n\nexport function checkpointNameForSession(sessionId: string): string {\n return `${SESSION_CHECKPOINT_PREFIX}-${sessionId}`;\n}\n\nconst bundleDirectory = dirname(fileURLToPath(import.meta.url));\nconst bundledFactorySkillsPath = join(bundleDirectory, 'factory-skills');\nconst FACTORY_SKILLS_SOURCE_PATH =\n [\n // Deploy bundle: the consumer copies `factory-skills/` next to the built\n // server module (e.g. via its public/ dir).\n bundledFactorySkillsPath,\n // Package layout: `dist/../factory-skills` (also `src/../factory-skills`\n // when running tests against sources).\n join(bundleDirectory, '..', 'factory-skills'),\n // Consumer repo running from its package root before a build.\n join(process.cwd(), 'src', 'mastra', 'public', 'factory-skills'),\n ].find(existsSync) ?? bundledFactorySkillsPath;\nconst FACTORY_SKILLS_MOUNT = path.resolve(path.parse(process.cwd()).root, '__mastracode_factory_skills__');\nconst FACTORY_SKILL_NAMES = new Set(['configure-factory-rules', 'factory-plan', 'factory-review', 'factory-triage']);\n\nclass FactorySkillSource implements SkillSource {\n readonly #factorySource = new LocalSkillSource({ basePath: FACTORY_SKILLS_SOURCE_PATH });\n readonly #fallbackSkillRoots: Set<string>;\n\n constructor(\n readonly fallback: SkillSource,\n fallbackSkillRoots: string[],\n ) {\n this.#fallbackSkillRoots = new Set(fallbackSkillRoots.map(skillPath => path.normalize(skillPath)));\n }\n\n #isFactoryPath(skillPath: string): boolean {\n const normalized = path.normalize(skillPath);\n return normalized === FACTORY_SKILLS_MOUNT || normalized.startsWith(`${FACTORY_SKILLS_MOUNT}${path.sep}`);\n }\n\n #factoryPath(skillPath: string): string {\n return path.relative(FACTORY_SKILLS_MOUNT, path.normalize(skillPath));\n }\n\n exists(skillPath: string): Promise<boolean> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.exists(this.#factoryPath(skillPath))\n : this.fallback.exists(skillPath);\n }\n\n stat(skillPath: string): Promise<SkillSourceStat> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.stat(this.#factoryPath(skillPath))\n : this.fallback.stat(skillPath);\n }\n\n readFile(skillPath: string): Promise<string | Buffer> {\n return this.#isFactoryPath(skillPath)\n ? this.#factorySource.readFile(this.#factoryPath(skillPath))\n : this.fallback.readFile(skillPath);\n }\n\n async readdir(skillPath: string): Promise<SkillSourceEntry[]> {\n if (this.#isFactoryPath(skillPath)) {\n return this.#factorySource.readdir(this.#factoryPath(skillPath));\n }\n const entries = await this.fallback.readdir(skillPath);\n if (this.#fallbackSkillRoots.has(path.normalize(skillPath))) {\n return entries.filter(entry => !FACTORY_SKILL_NAMES.has(entry.name));\n }\n return entries;\n }\n\n realpath(skillPath: string): Promise<string> {\n if (this.#isFactoryPath(skillPath)) return Promise.resolve(path.normalize(skillPath));\n return this.fallback.realpath ? this.fallback.realpath(skillPath) : Promise.resolve(skillPath);\n }\n}\n\nconst factorySkillExtension: WorkspaceSkillExtension = {\n id: 'web-factory',\n paths: [FACTORY_SKILLS_MOUNT],\n createSource: (fallback, fallbackSkillRoots) => new FactorySkillSource(fallback, fallbackSkillRoots),\n};\n\ntype DynamicWorkspaceContext = Parameters<typeof getDynamicWorkspace>[0];\n\nexport interface CreateWorkspaceFactoryOptions {\n /** Factory sandbox runtime config (template machine + workdir base). */\n sandbox?: MastraFactorySandboxConfig;\n /** GitHub integration used to resolve Factory sessions and mint repo tokens. */\n github?: GithubIntegration;\n /** Fleet the per-session sandboxes are provisioned/reattached through. */\n fleet?: SandboxFleet;\n /** Work-items storage used to resolve the session's run-binding role, so\n * review-board sessions get the reviewer PAT as `GH_TOKEN`. Optional —\n * without it every session uses the default (worker) PAT. */\n workItems?: Pick<WorkItemsStorage, 'findRunBindingBySession'>;\n}\n\nexport function createWorkspaceFactory(options: CreateWorkspaceFactoryOptions = {}) {\n const { sandbox: sandboxConfig, github, fleet, workItems } = options;\n const isLocalSandbox = sandboxConfig?.machine instanceof LocalSandbox;\n const githubTokenInjectors = new Map<\n string,\n { inject: (token: string) => void; patKind: GithubPatKind; ghToken: string }\n >();\n // Concurrent requests for the same session (thread list + activity polling +\n // chat) must not each provision a sandbox and clone the repository. The\n // first caller materializes; followers await the same promise.\n const inflightMaterializations = new Map<string, Promise<Workspace>>();\n\n return async ({ requestContext, mastra, skillExtension }: DynamicWorkspaceContext) => {\n const effectiveSkillExtension = skillExtension ?? factorySkillExtension;\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const session =\n ctx?.resourceId && github ? await github.sourceControlStorage.sessions.getBySessionId(ctx.resourceId) : null;\n\n if (!session) {\n if (sandboxConfig && !isLocalSandbox) {\n throw new Error('A Factory session ID is required to create a remote sandbox workspace');\n }\n return getDynamicWorkspace({ requestContext, mastra, skillExtension: effectiveSkillExtension });\n }\n\n const user = requestContext.get('user') as FactoryAuthUser | undefined;\n const userId = getFactoryAuthUserId(user);\n if (!user?.organizationId || !userId || user.organizationId !== session.orgId || userId !== session.userId) {\n throw new Error(`Factory session ${session.sessionId} is not available to the current user`);\n }\n if (!sandboxConfig || !github || !fleet) {\n throw new Error('GitHub and sandbox providers are required to create a Factory session workspace');\n }\n\n const storage = github.sourceControlStorage;\n const projectRepository = await storage.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) throw new Error(`Repository link ${session.projectRepositoryId} was not found`);\n const connection = await storage.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n const repository = await storage.repositories.get({ orgId: session.orgId, id: projectRepository.repositoryId });\n if (!connection || !repository) throw new Error(`Repository link ${session.projectRepositoryId} is incomplete`);\n const installation = await storage.installations.get({ orgId: session.orgId, id: connection.installationId });\n if (!installation) throw new Error(`GitHub installation ${connection.installationId} was not found`);\n const repoFullName = repository.slug;\n\n let workdir = isLocalSandbox\n ? fleet.computeLocalSessionWorkdir(repoFullName, session.id)\n : (session.sandboxWorkdir ?? projectRepository.sandboxWorkdir);\n // The system prompt derives its working directory from `state.projectPath`\n // and falls back to the server's own process.cwd() when unset — which\n // points the agent at the host checkout (and lets it run `git checkout`\n // there instead of in its session workdir). Pin it to the session workdir.\n // During createSession this seeds the session's initial state (the\n // workspace resolves before the session is built); on later requests it\n // self-heals live state.\n if (ctx && workdir && ctx.getState()?.projectPath !== workdir) {\n await ctx.setState({ projectPath: workdir, projectName: repoFullName });\n }\n const binding: SandboxBindingStore = {\n // Read through to the session row so teardown after a fresh provision\n // sees the just-persisted id instead of a stale snapshot.\n get sandboxId() {\n return session.sandboxId;\n },\n checkpointName: checkpointNameForSession(session.id),\n setSandboxId: async id => {\n await storage.sessions.setSandbox({ id: session.id, sandboxId: id, sandboxWorkdir: workdir });\n session.sandboxId = id;\n session.sandboxWorkdir = workdir;\n },\n clear: async () => {\n await storage.sessions.setSandbox({ id: session.id, sandboxId: null, sandboxWorkdir: workdir });\n session.sandboxId = null;\n },\n };\n\n const extensionId = effectiveSkillExtension ? `-${effectiveSkillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectRepository.id}-${session.id}${extensionId}`;\n const configDir = sandboxConfig.workdir ?? DEFAULT_CONFIG_DIR;\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) {\n registerGithubTokenInjector(requestContext, registered.inject);\n registerGithubPatKind(requestContext, registered.patKind);\n // A PAT saved in Settings after this sandbox was provisioned must\n // reach the running sandbox without a server restart — re-read it\n // on every reuse and push it into the live sandbox when it changed.\n // Best-effort: a failed read or inject keeps the installed token.\n try {\n const pat = await getGithubPat(() => github.integrationStorage, session.orgId, registered.patKind);\n if (pat && pat !== registered.ghToken) {\n registered.inject(pat);\n }\n } catch {\n // Keep the token already installed in the sandbox.\n }\n }\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const materialize = async (): Promise<Workspace> => {\n // A terminal work item or a deleted session may have returned a\n // still-warm VM — with this repository already cloned — to the reuse\n // pool. Adopt it before provisioning a fresh sandbox. Pooled VMs carry\n // no credentials (tokens are injected per command, and the workdir is\n // scrubbed on release and again below), so any user's session for this\n // repository can claim one.\n let claimedPooledSandbox = false;\n if (!isLocalSandbox && !session.sandboxId) {\n const pooled = await storage.sandboxPool.claim({\n projectRepositoryId: session.projectRepositoryId,\n });\n if (pooled) {\n await storage.sessions.setSandbox({\n id: session.id,\n sandboxId: pooled.sandboxId,\n sandboxWorkdir: pooled.sandboxWorkdir,\n });\n session.sandboxId = pooled.sandboxId;\n session.sandboxWorkdir = pooled.sandboxWorkdir;\n workdir = pooled.sandboxWorkdir;\n claimedPooledSandbox = true;\n }\n }\n\n const access = await github.versionControl.getRepositoryAccess({\n orgId: session.orgId,\n repositoryId: repository.id,\n });\n const token = access.authorization?.token;\n if (!token) throw new Error('Repository access did not include a bearer token for the Factory session');\n\n // The `gh` CLI needs a PAT when the org configured one (installation\n // tokens 403 on integration-restricted endpoints); git clone/checkout\n // below keep using the minted installation token. Review-board sessions\n // (run-binding role `review`) authenticate `gh` as the reviewer account\n // when a reviewer token is configured; everything else — including\n // sessions with no resolvable run binding — uses the worker token.\n let patKind: GithubPatKind = 'default';\n if (workItems) {\n try {\n const address = getFactorySessionAddress(requestContext);\n const runBinding = address ? await workItems.findRunBindingBySession(address) : null;\n if (runBinding?.role === 'review' && runBinding.orgId === session.orgId) patKind = 'reviewer';\n } catch {\n // No resolvable binding — worker token.\n }\n }\n const ghCliToken = (await getGithubPat(() => github.integrationStorage, session.orgId, patKind)) ?? token;\n\n const ensureSandbox = () =>\n fleet.ensureSandbox(\n binding,\n { GH_TOKEN: ghCliToken },\n undefined,\n isLocalSandbox ? { workingDirectory: workdir } : {},\n );\n const runMaterialize = (target: Awaited<ReturnType<typeof ensureSandbox>>) =>\n materializeRepo({\n row: { id: session.id, sandboxWorkdir: workdir, materializedAt: session.materializedAt },\n repoInfo: { repoFullName: repoFullName, defaultBranch: repository.defaultBranch },\n sandbox: target,\n token,\n storage: storage.sessions,\n });\n const isGitMissing = (error: unknown) => error instanceof MaterializeError && error.code === 'git-missing';\n\n let sandbox = await ensureSandbox();\n // A claimed VM still has the previous session's branch checked out —\n // reset it to the default branch before materialize/checkout. When the\n // pooled VM was already reaped, `ensureSandbox` provisioned fresh and\n // the recycle is a no-op (no checkout on disk yet).\n if (claimedPooledSandbox) await recycleClaimedWorkdir(sandbox, workdir, repository.defaultBranch);\n try {\n await runMaterialize(sandbox);\n } catch (error) {\n if (!isGitMissing(error)) throw error;\n // A sandbox without git was booted from a bare base image (e.g. the\n // platform proxy falls back to a clean Debian base when its template\n // build fails). That VM can never materialize a repo, and its id is\n // already persisted on the binding — tear it down so re-opens stop\n // reattaching to the poisoned sandbox, then retry once on a fresh VM.\n await fleet.teardownSandbox(binding, sandbox);\n sandbox = await ensureSandbox();\n try {\n await runMaterialize(sandbox);\n } catch (retryError) {\n // Still bare — the provider's template is persistently broken.\n // Clear the binding so a later manual retry provisions fresh.\n if (isGitMissing(retryError)) await fleet.teardownSandbox(binding, sandbox);\n throw retryError;\n }\n }\n await checkoutSessionBranch(sandbox, workdir, {\n branch: session.branch,\n baseBranch: session.baseBranch || projectRepository.branch || repository.defaultBranch,\n token,\n repoFullName: repoFullName,\n });\n if (projectRepository.setupCommand) await runWorktreeSetup(sandbox, workdir, projectRepository.setupCommand);\n\n const injectGithubToken = (freshToken: string) => {\n if (!sandbox.setEnvironmentVariable) {\n throw new Error('The active sandbox provider does not support runtime GitHub token refresh.');\n }\n sandbox.setEnvironmentVariable('GH_TOKEN', freshToken);\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) registered.ghToken = freshToken;\n };\n githubTokenInjectors.set(workspaceId, { inject: injectGithubToken, patKind, ghToken: ghCliToken });\n registerGithubTokenInjector(requestContext, injectGithubToken);\n registerGithubPatKind(requestContext, patKind);\n\n const filesystem = new SandboxFilesystem({ sandbox, workdir });\n const projectSkillPaths = [path.join(configDir, 'skills'), '.claude/skills', '.agents/skills'];\n const skillPaths = [...(effectiveSkillExtension?.paths ?? []), ...projectSkillPaths];\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Factory Session Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n skills: skillPaths,\n skillSource: effectiveSkillExtension?.createSource(filesystem, projectSkillPaths) ?? filesystem,\n });\n };\n\n // Dedupe concurrent materializations of the same workspace: followers\n // await the leader's promise instead of provisioning a second sandbox,\n // then bind the shared token injector into their own request context.\n const inflight = inflightMaterializations.get(workspaceId);\n if (inflight) {\n const workspace = await inflight;\n const registered = githubTokenInjectors.get(workspaceId);\n if (registered) {\n registerGithubTokenInjector(requestContext, registered.inject);\n registerGithubPatKind(requestContext, registered.patKind);\n }\n return workspace;\n }\n const materialization = materialize();\n inflightMaterializations.set(workspaceId, materialization);\n try {\n return await materialization;\n } finally {\n inflightMaterializations.delete(workspaceId);\n }\n };\n}\n\nexport const getFactoryWorkspace = createWorkspaceFactory();\n"],"mappings":";;;;;;;;;;;;;;AA8BA,MAAM,sBAAsB;AAC5B,MAAM,4BAA4B;AAElC,SAAgB,yBAAyB,WAA2B;CAClE,OAAO,GAAG,0BAA0B,GAAG;AACzC;AAEA,MAAM,kBAAkB,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC;AAC9D,MAAM,2BAA2B,KAAK,iBAAiB,gBAAgB;AACvE,MAAM,6BACJ;CAGE;CAGA,KAAK,iBAAiB,MAAM,gBAAgB;CAE5C,KAAK,QAAQ,IAAI,GAAG,OAAO,UAAU,UAAU,gBAAgB;AACjE,CAAC,CAAC,KAAK,UAAU,KAAK;AACxB,MAAM,uBAAuB,KAAK,QAAQ,KAAK,MAAM,QAAQ,IAAI,CAAC,CAAC,CAAC,MAAM,+BAA+B;AACzG,MAAM,sCAAsB,IAAI,IAAI;CAAC;CAA2B;CAAgB;CAAkB;AAAgB,CA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;IAAmB;IAAS,SAAS;GAAW,CAAC;GACjG,4BAA4B,gBAAgB,iBAAiB;GAC7D,sBAAsB,gBAAgB,OAAO;GAE7C,MAAM,aAAa,IAAI,kBAAkB;IAAE;IAAS;GAAQ,CAAC;GAC7D,MAAM,oBAAoB;IAAC,KAAK,KAAK,WAAW,QAAQ;IAAG;IAAkB;GAAgB;GAC7F,MAAM,aAAa,CAAC,GAAI,yBAAyB,SAAS,CAAC,GAAI,GAAG,iBAAiB;GACnF,OAAO,IAAI,UAAU;IACnB,IAAI;IACJ,MAAM;IACN;IACS;IACT,OAAO;IACP,QAAQ;IACR,aAAa,yBAAyB,aAAa,YAAY,iBAAiB,KAAK;GACvF,CAAC;EACH;EAKA,MAAM,WAAW,yBAAyB,IAAI,WAAW;EACzD,IAAI,UAAU;GACZ,MAAM,YAAY,MAAM;GACxB,MAAM,aAAa,qBAAqB,IAAI,WAAW;GACvD,IAAI,YAAY;IACd,4BAA4B,gBAAgB,WAAW,MAAM;IAC7D,sBAAsB,gBAAgB,WAAW,OAAO;GAC1D;GACA,OAAO;EACT;EACA,MAAM,kBAAkB,YAAY;EACpC,yBAAyB,IAAI,aAAa,eAAe;EACzD,IAAI;GACF,OAAO,MAAM;EACf,UAAU;GACR,yBAAyB,OAAO,WAAW;EAC7C;CACF;AACF;AAEA,MAAa,sBAAsB,uBAAuB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/factory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0-alpha.2",
|
|
4
4
|
"description": "Mastra Software Factory module: the server core behind the Mastra Software Factory — storage domains, integrations, and surfaces for agent-powered software delivery",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -50,10 +50,10 @@
|
|
|
50
50
|
"@octokit/rest": "^22.0.1",
|
|
51
51
|
"hono": "^4.12.8",
|
|
52
52
|
"zod": "^4.3.6",
|
|
53
|
-
"@mastra/auth-studio": "1.3.3",
|
|
54
53
|
"@mastra/auth-workos": "1.6.4",
|
|
55
|
-
"@mastra/
|
|
56
|
-
"@mastra/
|
|
54
|
+
"@mastra/auth-studio": "1.3.3",
|
|
55
|
+
"@mastra/code-sdk": "1.1.1-alpha.2",
|
|
56
|
+
"@mastra/core": "1.55.0-alpha.2"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@types/node": "22.20.1",
|
|
@@ -63,8 +63,8 @@
|
|
|
63
63
|
"typescript-eslint": "^8.57.0",
|
|
64
64
|
"vitest": "4.1.10",
|
|
65
65
|
"@internal/lint": "0.0.118",
|
|
66
|
-
"@mastra/libsql": "1.18.0",
|
|
67
66
|
"@mastra/pg": "1.18.0",
|
|
67
|
+
"@mastra/libsql": "1.18.0",
|
|
68
68
|
"@internal/types-builder": "0.0.93"
|
|
69
69
|
},
|
|
70
70
|
"engines": {
|