|
| 1 | +// Reads an existing agent's deploy source back out of its workflow asset, |
| 2 | +// so the new-workbench picker can re-push the same definition into a |
| 3 | +// child tenant (agent-deploy.ts already generalizes that push+deploy). |
| 4 | +// There is no stock file-read route for a workflow asset (only |
| 5 | +// package-registry tarballs get one), so this fetches `main` over the |
| 6 | +// asset's smart-HTTP git remote with a short-lived read-only token. |
| 7 | +import { parseWorkflowSourceEntry, WORKFLOW_SOURCE_ENTRY_PATH } from "@corbits/workflows"; |
| 8 | +import { type } from "arktype"; |
| 9 | + |
| 10 | +import { fetchSourceFile } from "./git-fetch"; |
| 11 | + |
| 12 | +export class AgentSourceReadError extends Error {} |
| 13 | + |
| 14 | +const GitTokenMintShape = type({ id: "string", secret: "string" }); |
| 15 | + |
| 16 | +const AgentWorkflowJsonShape = type({ |
| 17 | + id: "string", |
| 18 | + steps: type.Record( |
| 19 | + "string", |
| 20 | + type({ |
| 21 | + agent: type({ |
| 22 | + systemPrompt: "string", |
| 23 | + inference: { sources: type({ provider: "string", model: "string" }).array() }, |
| 24 | + }), |
| 25 | + }), |
| 26 | + ), |
| 27 | +}); |
| 28 | + |
| 29 | +const READ_TOKEN_LIFETIME_MS = 10 * 60 * 1000; |
| 30 | + |
| 31 | +async function readErrorBody(response: Response): Promise<string> { |
| 32 | + const body: unknown = await response.json().catch(() => undefined); |
| 33 | + const envelope = type({ |
| 34 | + error: { code: "string", userMessage: "string", refId: "string" }, |
| 35 | + })(body); |
| 36 | + return envelope instanceof type.errors ? `HTTP ${response.status}` : envelope.error.userMessage; |
| 37 | +} |
| 38 | + |
| 39 | +/** An existing agent's deploy source, in the shape `deployAgentSource`'s |
| 40 | + * `NewAgentInput` needs plus the sources it declares for inference. */ |
| 41 | +export type AgentSource = { |
| 42 | + readonly systemPrompt: string; |
| 43 | + readonly declaredSources: readonly { readonly provider: string; readonly model: string }[]; |
| 44 | +}; |
| 45 | + |
| 46 | +/** Mints a read-only token, fetches the asset's `main`, and parses out the |
| 47 | + * agent definition its source tree carries. */ |
| 48 | +export async function readAgentSource( |
| 49 | + tenantId: string, |
| 50 | + assetId: string, |
| 51 | + assetName: string, |
| 52 | + fetchImpl: typeof fetch = fetch, |
| 53 | +): Promise<AgentSource> { |
| 54 | + const tokensPath = `/api/tenants/${encodeURIComponent(tenantId)}/git-tokens`; |
| 55 | + const minted = await fetchImpl(tokensPath, { |
| 56 | + method: "POST", |
| 57 | + headers: { "content-type": "application/json" }, |
| 58 | + body: JSON.stringify({ |
| 59 | + name: `agent-read-${crypto.randomUUID()}`, |
| 60 | + resource: `asset:${assetId}`, |
| 61 | + refPattern: "refs/heads/main", |
| 62 | + actions: ["can_read"], |
| 63 | + expiresAt: new Date(Date.now() + READ_TOKEN_LIFETIME_MS).toISOString(), |
| 64 | + }), |
| 65 | + }); |
| 66 | + if (!minted.ok) { |
| 67 | + throw new AgentSourceReadError(`minting a read token failed: ${await readErrorBody(minted)}`); |
| 68 | + } |
| 69 | + const token = GitTokenMintShape(await minted.json()); |
| 70 | + if (token instanceof type.errors) { |
| 71 | + throw new AgentSourceReadError( |
| 72 | + `the read token came back an unexpected shape: ${token.summary}`, |
| 73 | + ); |
| 74 | + } |
| 75 | + |
| 76 | + const url = new URL( |
| 77 | + `/api/tenants/${encodeURIComponent(tenantId)}/assets/workflow/${assetName}.git`, |
| 78 | + globalThis.location.origin, |
| 79 | + ).toString(); |
| 80 | + try { |
| 81 | + const entryModule = await fetchSourceFile({ |
| 82 | + url, |
| 83 | + token: token.secret, |
| 84 | + filepath: WORKFLOW_SOURCE_ENTRY_PATH, |
| 85 | + }); |
| 86 | + const workflowJson = parseWorkflowSourceEntry(entryModule, assetId); |
| 87 | + const parsed = AgentWorkflowJsonShape(JSON.parse(workflowJson)); |
| 88 | + if (parsed instanceof type.errors) { |
| 89 | + throw new AgentSourceReadError( |
| 90 | + `this agent's source came back an unexpected shape: ${parsed.summary}`, |
| 91 | + ); |
| 92 | + } |
| 93 | + const step = Object.values(parsed.steps)[0]; |
| 94 | + if (step === undefined) { |
| 95 | + throw new AgentSourceReadError("this agent's source has no steps to read a prompt from"); |
| 96 | + } |
| 97 | + return { |
| 98 | + systemPrompt: step.agent.systemPrompt, |
| 99 | + declaredSources: step.agent.inference.sources, |
| 100 | + }; |
| 101 | + } finally { |
| 102 | + await fetchImpl(`${tokensPath}/${encodeURIComponent(token.id)}`, { method: "DELETE" }); |
| 103 | + } |
| 104 | +} |
0 commit comments