diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index b186571ce..c2f258d36 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -42,6 +42,7 @@ import { } from "@intx/hub-api"; import { + agentDefinitionSourceTree, buildAgentDefinitionWorkflow, createAgentDefinitionRoutes, createDefinitionAssetHistory, @@ -2568,13 +2569,6 @@ export async function createHub(config: HubConfig) { listModels: listMyraModels, }; - // Mirrors `@corbits/agent-directory`'s own private - // `AGENT_DEFINITION_ASSET_PATH` constant (not exported — the route - // module keeps it internal), kept in lockstep by convention since - // this is the same asset-tree contract `ensureWorkflowDefinitionForAsset` - // reads back from. - const PLANNER_AGENT_DEFINITION_ASSET_PATH = "workflow.json"; - /** * Wraps the same sequence `@corbits/agent-directory`'s `POST /` * handler runs (`buildAgentDefinitionWorkflow` → `reindexPinnedSkills` @@ -2656,9 +2650,7 @@ export async function createHub(config: HubConfig) { ref: DEFAULT_ASSET_REF, principal: { kind: "hub" }, tree: { - files: { - [PLANNER_AGENT_DEFINITION_ASSET_PATH]: workflowJson, - }, + files: agentDefinitionSourceTree({ handle, workflowJson }), message: `Define agent ${input.name}`, }, }); diff --git a/bun.lock b/bun.lock index 4dfd95393..627225496 100644 --- a/bun.lock +++ b/bun.lock @@ -189,6 +189,7 @@ "@corbits/chat": "workspace:*", "@corbits/skills": "workspace:*", "@corbits/workflow-catalog": "workspace:*", + "@corbits/workflow-source": "workspace:*", "@intx/agent": "workspace:*", "@intx/db": "workspace:*", "@intx/hub-api": "workspace:*", @@ -236,6 +237,7 @@ "name": "@corbits/agent-runtime", "version": "0.0.1", "dependencies": { + "@corbits/workflow-source": "workspace:*", "@intx/agent": "workspace:*", "@intx/types": "workspace:*", "@intx/workflow": "workspace:*", @@ -713,6 +715,7 @@ "@corbits/tool-registry-publish": "workspace:*", "@corbits/workbench-digest-workflow": "workspace:*", "@corbits/workflow-catalog": "workspace:*", + "@corbits/workflow-source": "workspace:*", "@intx/inference": "workspace:*", "@intx/types": "workspace:*", "arktype": "catalog:", @@ -825,7 +828,7 @@ }, "packages/mcp-tools": { "name": "@corbits/mcp-tools", - "version": "0.0.4", + "version": "0.0.5", "dependencies": { "@intx/agent": "workspace:*", "@intx/types": "workspace:*", @@ -1326,6 +1329,14 @@ "typescript": "catalog:", }, }, + "packages/workflow-source": { + "name": "@corbits/workflow-source", + "version": "0.0.1", + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:", + }, + }, "vendor/intx/agent": { "name": "@intx/agent", "version": "0.2.2", @@ -2075,6 +2086,8 @@ "@corbits/workflow-catalog": ["@corbits/workflow-catalog@workspace:packages/workflow-catalog"], + "@corbits/workflow-source": ["@corbits/workflow-source@workspace:packages/workflow-source"], + "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="], "@esbuild-kit/core-utils": ["@esbuild-kit/core-utils@3.3.2", "", { "dependencies": { "esbuild": "~0.18.20", "source-map-support": "^0.5.21" } }, "sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ=="], @@ -3335,6 +3348,8 @@ "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@corbits/memory-hub/@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], + "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], @@ -3357,7 +3372,7 @@ "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.6", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="], - "@workbench/hub/@corbits/mailbox": ["@corbits/mailbox@github:corbitsdev/corbits-mailbox#caa5214", { "dependencies": { "@hono/standard-validator": "0.2.3", "@standard-community/standard-json": "0.3.5", "@standard-community/standard-openapi": "0.2.9", "arktype": "2.1.29", "hono-openapi": "1.3.1" }, "peerDependencies": { "@intx/log": "^0.2.2", "@intx/mime": "^0.2.2", "@intx/types": "^0.2.2", "drizzle-orm": "^0.45.2", "hono": "^4.12.0", "postgres": "^3.4.0" } }, "corbitsdev-corbits-mailbox-caa5214", "sha512-z8DRBFgA4ukM8p29COeaMjfKZYe5jAUF4OBMiaIQFuW592+DGD/y6Ws6SjGlXmR9azkHNWh8oTzjlWlRP24vsQ=="], + "@workbench/hub/@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], diff --git a/docs/revendor-inventory.md b/docs/revendor-inventory.md index 166604085..530db4784 100644 --- a/docs/revendor-inventory.md +++ b/docs/revendor-inventory.md @@ -770,12 +770,156 @@ folded-run-`), definition loaded from that closure, run grants `scripts/e2e/cl-6324-launch-proof.ts` keeps the assertion as written rather than weakening it to something the current shape happens to satisfy. -5. **STILL OPEN — the agent-directory authoring lineage still writes the - retired envelope.** `createAgentDefinitionCore` and the read/modify/ - write routes in `routes.ts`, `workflow-capability-routes.ts`, and - `workflow-skill-pin-routes.ts` all populate a `workflow`-kind asset +5. **CLOSED — the agent-directory authoring lineage now writes the source + form.** `createAgentDefinitionCore` and the read/modify/write routes in + `routes.ts`, `workflow-capability-routes.ts`, and + `workflow-skill-pin-routes.ts` used to populate a `workflow`-kind asset with a bare `workflow.json`, which `workflowKindHandler.validatePush` - now refuses. That lineage is authoring, not launching — a projection - is a read-only artefact and cannot be written back through — so it - needs its own cutover to the codebase form, and none of the four - proofs exercise it. + now refuses. That lineage is authoring, not launching — a projection is + a read-only artefact and cannot be written back through — so it got its + own cutover. See the section below. + +## CL-6324: the agent-directory authoring cutover + +The renderer that had been living in `@workbench/hub-client`'s +`workflow-push.ts`, and a second copy of it in `@corbits/agent-runtime`'s +`source-tree.ts`, moved into a new dependency-free package, +`@corbits/workflow-source`. Every authoring path in the repo now writes +its asset tree through that one `renderWorkflowSourceTree` — the seed +pusher, the per-run agent-runtime package, and the agent-directory +lineage — so there is a single producer of the bytes a workflow-kind +asset carries. + +`@corbits/agent-directory`'s `definition-asset.ts` is the lineage's own +seam onto it: `agentDefinitionSourceTree` renders a definition's tree +under a `@workbench-agent/` package name, and +`readAgentDefinitionWorkflowJson` reads the definition back out of the +entry module. Both replace the private `AGENT_DEFINITION_ASSET_PATH = +"workflow.json"` constant each of the four writers used to declare for +itself; `apps/hub`'s planner deploy and `@corbits/evals`' world snapshot +route through the same two functions rather than re-deriving the path. +The `workflow.json` write path is gone, not kept beside the new one. + +Reading the definition back is a strict slice of the exact bytes the +renderer emits (the `export default ` prefix and `;\n` suffix), never an +eval and never a pattern search. Anything else — in practice, an asset +last written before this cutover, whose tree still holds a bare +`workflow.json` — throws `RetiredWorkflowEnvelopeError`, defined in +`@corbits/workflow-source` and re-exported from `@corbits/agent-directory`. +It carries re-author-and-re-deploy guidance and is mapped to a 409 in +every route module that can reach it: `routes.ts`, +`workflow-capability-routes.ts`, and `workflow-skill-pin-routes.ts` each +answer it from their own `app.onError`, so a stale asset never reads as a +server fault. + +One behavioural change rode along: `POST /:definitionId/restore` now +reports the definition it just wrote, parsed from the entry module it +restored, instead of re-reading the asset immediately afterward. + +## CL-6324: what the four proofs found on a real stack + +`scripts/e2e/cl-6324-launch-proof.ts` is the harness: one scratch +database, a real signup, a real local Ollama, nothing mocked. It runs as + +``` +E2E_PROVIDER=ollama OLLAMA_BASE_URL=http://localhost:11434 \ +E2E_OLLAMA_MODEL= \ +DATABASE_URL=postgres://localhost:5432/ \ +bun run scripts/e2e/cl-6324-launch-proof.ts +``` + +### Proof 2, in the shape each deploy actually takes + +The earlier revision asserted a workflow-host `RunStarted` for a folded +`step`-mode run and hung on it forever. That was an assertion about the +section shape aimed at the step shape's run. The two are now asserted +separately, each against the artefact it really produces. + +**Step mode.** One unbounded step services every inbound mail, so the run +starts no child run per message and its own workflow event log stays +empty — the harness asserts exactly that, as a falsifiable statement +rather than a footnote. Its per-message bracket is the +`message.run.started` / `message.run.ended` AGENT event pair, which +travels the sidecar's `agent.event` channel and is never committed to the +workflow-run repo. The durable, HTTP-observable evidence that the bracket +opened AND closed is `@corbits/insights`' `turn_latency` row: the tracker +opens it on `message.run.started` and commits it on `message.run.ended`, +and `GET /api/tenants/:tenantId/insights/latency` reports it as a sample +count. That, plus the reply row itself, is what the proof asserts. + +**Section mode — and CL-6329's first live validation.** `mode: "section"` +had existed as a config argument since the agent-runtime cutover and +nothing had ever deployed or run one. The proof now does, for real: it +renders a section-mode `AgentRuntimeConfig` into its own source package, +pushes it as a `workflow`-kind asset, deploys it by source-ref through +`POST /workflows/deployments`, and drives it with real mail. Every +message is an `onTrigger` occurrence with its own child run and its own +event log, which is where `RunStarted` genuinely lives: + +``` +turn__0 events: RunStarted, StepStarted, StepCompleted, RunCompleted +parent run events: RunStarted, StepStarted, ChildSpawned, + ChildCompleted, SignalAwaited +``` + +The parent's `SignalAwaited` after `ChildCompleted` is the section +re-arming for the next message. This is the shape the milestone's +`RunStarted` assertion was always about, and it works. + +### Proof 4 FAILS, in both shapes, for the same reason + +Kill the sidecar mid-turn, restart it, and boot restore does its half of +the job: the scan finds every deployment record, replays each pin, and +re-materializes the closure — the restarted stack reports the run's own +`liveness: "ok"` 9.2s after the restart. But the run inside it comes back +**terminal**, and every later message is refused: + +- the folded chat run: `workflow-host·supervisor: rejecting inbound mail +'<...>': workflow run 'run_...' is terminal` — the hub accepts the room + message, nothing ever answers it, and the turn times out with no reply + and no notice; +- the section deployment: `POST /workflows//mail` answers `409 +workflow_run_terminal`, "is terminal and cannot receive more mail". + +So a mid-turn sidecar death is permanent for the run. `onBodyFailure: +"continue"` does not rescue the section here, and could not: the failure +is on the TOP-LEVEL run, not on a body occurrence, so there is no failed +child edge for the policy to act on. Nothing in the chat layer recovers +either, because its wake choke point only redeploys an address that is +NOT routable — and this address is routable, just dead. + +This is the milestone's real remaining gap, and it is a platform-level +one rather than anything the app-side conversion introduced: restoring a +deployment is not the same as resurrecting its run, and at this pin +nothing does the second half. + +### Timings, from a clean boot + +| Phase | Wall clock | +| ---------------------------------------------------- | ---------- | +| section-mode deploy (push + probe + freeze + deploy) | 4.3s | +| section occurrence to its own `RunStarted` | 1.0s | +| sidecar restart + boot restore to `liveness: "ok"` | 9.2s | + +Two phases read as ~0s and should not be mistaken for speed: a chat mint +is DB-only (the deploy happens later, on the first traffic), and the join +greeting is canned copy `@corbits/chat` posts in the agent's voice, not a +model turn. The first REAL token is proof 3's reply. + +### Two environment traps the harness now closes explicitly + +1. **The onboarding seed pins the curated model; the catalog is seeded + from the live instance.** `modelSourceFor` takes its model from + `CATALOG_SEEDS.ollama`, so every default workflow deploys pinned at + that name, while `seedCatalog` fills the tenant catalog from the + instance's own `/api/tags`. On an instance that never pulled the + curated model the two never meet, and every chat turn dies as + `InferenceResolutionError: No launchable inference source for model +""` — surfaced to the reader as "I can't reach a model right + now". The harness names its model through `E2E_OLLAMA_MODEL` instead + of inheriting the curated one. +2. **A live Ollama connect seeds embedding models as offerings with no + capability metadata** (CL-6351), so default-model resolution breaks + the tie alphabetically and `all-minilm` can win the bench default. The + harness narrows the bench catalog to its one pinned model through the + catalog API before it asserts anything about a turn. diff --git a/packages/agent-directory/package.json b/packages/agent-directory/package.json index 68381edc9..81ce99545 100644 --- a/packages/agent-directory/package.json +++ b/packages/agent-directory/package.json @@ -17,6 +17,7 @@ "@corbits/chat": "workspace:*", "@corbits/skills": "workspace:*", "@corbits/workflow-catalog": "workspace:*", + "@corbits/workflow-source": "workspace:*", "@intx/agent": "workspace:*", "@intx/db": "workspace:*", "@intx/hub-api": "workspace:*", diff --git a/packages/agent-directory/src/agent-workflow.ts b/packages/agent-directory/src/agent-workflow.ts index 01fb7a480..a307c351c 100644 --- a/packages/agent-directory/src/agent-workflow.ts +++ b/packages/agent-directory/src/agent-workflow.ts @@ -32,6 +32,7 @@ import { } from "@corbits/skills"; import { type } from "arktype"; +import { agentDefinitionSourceTree } from "./definition-asset"; import type { DefinitionSkillsStore } from "./skills-store"; export const AGENT_DEFINITION_STEP_ID = "agent"; @@ -367,13 +368,6 @@ export function serializeAgentDefinitionWorkflow( return JSON.stringify(definition); } -/** Where a definition's serialized `WorkflowDefinition` lives in its - * asset tree — the same path every route that reads/writes a - * definition's `workflow.json` declares privately for itself - * (`./routes.ts`, `./workflow-capability-routes.ts`); this copy is the - * one `createAgentDefinitionCore` itself writes to. */ -const AGENT_DEFINITION_ASSET_PATH = "workflow.json"; - export type CreateAgentDefinitionCoreDeps = { readonly db: DB["db"]; readonly assetService: AssetService; @@ -448,7 +442,7 @@ export class DuplicateAgentHandleError extends Error { /** * The full create-agent-definition sequence: resolve the tenant's mail - * domain, build and pin the definition's `workflow.json`, materialize + * domain, build and pin the definition's serialized workflow, materialize * it as a `workflow`-kind asset, persist its pinned skills, and * project it onto a first-class `workflow_definition` row. Factored out * of `./routes.ts`'s `POST /` handler so `./workflow-create-routes.ts` @@ -509,7 +503,7 @@ export async function createAgentDefinitionCore( cause.reason === "duplicate_asset" ) { // A previous attempt may have created the asset row but failed - // before populateAsset wrote workflow.json — an empty shell that + // before populateAsset wrote its source tree — an empty shell that // blocks retries with a misleading conflict. Recover: look up the // existing asset and reuse it only if it has no definition yet. const existing = await deps.db.query.asset.findFirst({ @@ -542,7 +536,7 @@ export async function createAgentDefinitionCore( ref: DEFAULT_ASSET_REF, principal: { kind: "hub" }, tree: { - files: { [AGENT_DEFINITION_ASSET_PATH]: workflowJson }, + files: agentDefinitionSourceTree({ handle: input.handle, workflowJson }), message: `Define agent ${input.name}`, }, }); diff --git a/packages/agent-directory/src/definition-asset.ts b/packages/agent-directory/src/definition-asset.ts new file mode 100644 index 000000000..ee1ca2630 --- /dev/null +++ b/packages/agent-directory/src/definition-asset.ts @@ -0,0 +1,58 @@ +// Every read and write of an agent definition's asset tree goes through +// here, so this lineage has exactly one notion of what a definition's +// asset holds: the source codebase `@corbits/workflow-source` renders, +// never the retired `workflow.json` envelope the push validator now +// refuses. +// +// The rendered package's name never leaves the asset — the tree is a +// standalone codebase the sidecar evaluates, not something anyone +// installs — so it only has to be a valid, stable npm name. A +// definition's handle is already lowercase-kebab (see `./validation.ts`), +// which makes it one. + +import { + parseWorkflowSourceEntry, + readWorkflowSourceDefinition, + renderWorkflowSourceTree, + RetiredWorkflowEnvelopeError, + WORKFLOW_SOURCE_ENTRY_PATH, + type WorkflowSourceBlobReader, + type WorkflowSourceTree, +} from "@corbits/workflow-source"; + +export { + RetiredWorkflowEnvelopeError, + WORKFLOW_SOURCE_ENTRY_PATH as AGENT_DEFINITION_ENTRY_PATH, +}; + +const AGENT_PACKAGE_SCOPE = "@workbench-agent"; + +/** The source tree a definition's serialized workflow is written as. */ +export function agentDefinitionSourceTree(args: { + handle: string; + workflowJson: string; +}): WorkflowSourceTree { + return renderWorkflowSourceTree({ + packageName: `${AGENT_PACKAGE_SCOPE}/${args.handle}`, + workflowJson: args.workflowJson, + }); +} + +/** A definition's current serialized workflow, read back out of its asset. */ +export function readAgentDefinitionWorkflowJson( + reader: WorkflowSourceBlobReader, + assetId: string, +): Promise { + return readWorkflowSourceDefinition(reader, assetId); +} + +/** The serialized workflow inside entry-module bytes read at a past commit. */ +export function parseAgentDefinitionEntry( + entryModule: Uint8Array, + assetId: string, +): string { + return parseWorkflowSourceEntry( + new TextDecoder().decode(entryModule), + assetId, + ); +} diff --git a/packages/agent-directory/src/index.ts b/packages/agent-directory/src/index.ts index ed05e4e51..95f67d3c1 100644 --- a/packages/agent-directory/src/index.ts +++ b/packages/agent-directory/src/index.ts @@ -14,6 +14,13 @@ export { type CreateAgentDefinitionCoreInput, type CreateAgentDefinitionCoreResult, } from "./agent-workflow"; +export { + agentDefinitionSourceTree, + parseAgentDefinitionEntry, + readAgentDefinitionWorkflowJson, + AGENT_DEFINITION_ENTRY_PATH, + RetiredWorkflowEnvelopeError, +} from "./definition-asset"; export { createDrizzleDefinitionSkillsStore, createInMemoryDefinitionSkillsStore, diff --git a/packages/agent-directory/src/routes.ts b/packages/agent-directory/src/routes.ts index 249cb8473..ea77697f6 100644 --- a/packages/agent-directory/src/routes.ts +++ b/packages/agent-directory/src/routes.ts @@ -3,8 +3,8 @@ // materializes it exactly the way the platform's own starter agents // (`@corbits/assistant-workflow`, `@corbits/chat`'s workbench host) are // materialized — a `workflow`-kind asset carrying a single-step -// `workflow.json`, projected onto a first-class `workflow_definition` -// row. No git subprocess: `AssetService.populateAsset` writes the +// definition as a source codebase (see `./definition-asset.ts`), +// projected onto a first-class `workflow_definition` row. No git subprocess: `AssetService.populateAsset` writes the // commit in-process, the same seam `createAsset` used to hydrate a // workbench host's asset lives beside. // @@ -43,6 +43,13 @@ import { type CreateAgentDefinitionCoreDeps, type CreateAgentDefinitionCoreInput, } from "./agent-workflow"; +import { + agentDefinitionSourceTree, + AGENT_DEFINITION_ENTRY_PATH, + parseAgentDefinitionEntry, + readAgentDefinitionWorkflowJson, + RetiredWorkflowEnvelopeError, +} from "./definition-asset"; import type { DefinitionSkillsStore } from "./skills-store"; import { CreateAgentDefinitionInput, @@ -84,9 +91,6 @@ export type CreateAgentDefinitionRoutesDeps = { tenantDefaultModel?: CreateAgentDefinitionCoreDeps["tenantDefaultModel"]; }; -/** Where a definition's serialized `WorkflowDefinition` lives in its asset tree. */ -const AGENT_DEFINITION_ASSET_PATH = "workflow.json"; - function errorEnvelope(code: string, message: string) { return { error: { code, message } }; } @@ -143,6 +147,9 @@ export function createAgentDefinitionRoutes({ if (err instanceof CapabilityOutOfInventoryError) { return c.json(errorEnvelope("bad_request", err.message), 400); } + if (err instanceof RetiredWorkflowEnvelopeError) { + return c.json(errorEnvelope("conflict", err.message), 409); + } throw err; }); @@ -307,11 +314,9 @@ export function createAgentDefinitionRoutes({ return c.json(definitionNotFound(definitionId), 404); } - const workflowJson = new TextDecoder().decode( - await assetService.readAssetBlob({ - assetId: row.assetId, - path: AGENT_DEFINITION_ASSET_PATH, - }), + const workflowJson = await readAgentDefinitionWorkflowJson( + assetService, + row.assetId, ); const capabilities = readAgentCapabilities(workflowJson); const skills = await skillsStore.getSkills(row.assetId); @@ -378,12 +383,12 @@ export function createAgentDefinitionRoutes({ return c.json(definitionNotFound(definitionId), 404); } - const workflowBytes = await history.readBlobAtCommit({ + const entryBytes = await history.readBlobAtCommit({ assetId: row.assetId, - path: AGENT_DEFINITION_ASSET_PATH, + path: AGENT_DEFINITION_ENTRY_PATH, commitSha: body.commitSha, }); - if (workflowBytes === null) { + if (entryBytes === null) { return c.json( errorEnvelope( "not_found", @@ -392,31 +397,29 @@ export function createAgentDefinitionRoutes({ 404, ); } - const decoder = new TextDecoder(); + const restoredWorkflowJson = parseAgentDefinitionEntry( + entryBytes, + row.assetId, + ); // Pinned skills live outside the asset tree (see // `DefinitionSkillsStore`), so restoring a prior commit only ever - // rewrites `workflow.json` — the definition's currently pinned - // skills are untouched by restoring an earlier instructions - // revision. + // rewrites the definition's source tree — the definition's + // currently pinned skills are untouched by restoring an earlier + // instructions revision. await assetService.populateAsset({ assetId: row.assetId, ref: DEFAULT_ASSET_REF, principal: { kind: "hub" }, tree: { - files: { - [AGENT_DEFINITION_ASSET_PATH]: decoder.decode(workflowBytes), - }, + files: agentDefinitionSourceTree({ + handle: row.name, + workflowJson: restoredWorkflowJson, + }), message: `Restore agent ${row.name} to ${body.commitSha.slice(0, 8)}`, }, }); - const restoredWorkflowJson = new TextDecoder().decode( - await assetService.readAssetBlob({ - assetId: row.assetId, - path: AGENT_DEFINITION_ASSET_PATH, - }), - ); const capabilities = readAgentCapabilities(restoredWorkflowJson); const skills = await skillsStore.getSkills(row.assetId); @@ -467,11 +470,9 @@ export function createAgentDefinitionRoutes({ // fetched, never a stale or wider one. assertCapabilityInInventory(body, inventory); - const workflowJson = new TextDecoder().decode( - await assetService.readAssetBlob({ - assetId: row.assetId, - path: AGENT_DEFINITION_ASSET_PATH, - }), + const workflowJson = await readAgentDefinitionWorkflowJson( + assetService, + row.assetId, ); let nextWorkflowJson: string; @@ -512,7 +513,10 @@ export function createAgentDefinitionRoutes({ ref: DEFAULT_ASSET_REF, principal: { kind: "hub" }, tree: { - files: { [AGENT_DEFINITION_ASSET_PATH]: nextWorkflowJson }, + files: agentDefinitionSourceTree({ + handle: row.name, + workflowJson: nextWorkflowJson, + }), message, }, }); @@ -558,11 +562,9 @@ export function createAgentDefinitionRoutes({ return c.json(definitionNotFound(definitionId), 404); } - const workflowJson = new TextDecoder().decode( - await assetService.readAssetBlob({ - assetId: row.assetId, - path: AGENT_DEFINITION_ASSET_PATH, - }), + const workflowJson = await readAgentDefinitionWorkflowJson( + assetService, + row.assetId, ); // Git first: the row updates below are what can still be retried @@ -574,12 +576,13 @@ export function createAgentDefinitionRoutes({ ref: DEFAULT_ASSET_REF, principal: { kind: "hub" }, tree: { - files: { - [AGENT_DEFINITION_ASSET_PATH]: withAgentSystemPrompt( + files: agentDefinitionSourceTree({ + handle: row.name, + workflowJson: withAgentSystemPrompt( workflowJson, body.systemPrompt, ), - }, + }), message: `Update agent instructions for ${row.name}`, }, }); @@ -650,11 +653,9 @@ export function createAgentDefinitionRoutes({ } const principal = c.get("principal"); - const workflowJson = new TextDecoder().decode( - await assetService.readAssetBlob({ - assetId: row.assetId, - path: AGENT_DEFINITION_ASSET_PATH, - }), + const workflowJson = await readAgentDefinitionWorkflowJson( + assetService, + row.assetId, ); await assetService.populateAsset({ @@ -662,12 +663,13 @@ export function createAgentDefinitionRoutes({ ref: DEFAULT_ASSET_REF, principal: { kind: "hub" }, tree: { - files: { - [AGENT_DEFINITION_ASSET_PATH]: reindexPinnedSkills( + files: agentDefinitionSourceTree({ + handle: row.name, + workflowJson: reindexPinnedSkills( workflowJson, await skillIndex.resolve(tenant.id, principal.id, body.skills), ), - }, + }), message: `Update agent skills for ${row.name}`, }, }); diff --git a/packages/agent-directory/src/workflow-capability-routes.ts b/packages/agent-directory/src/workflow-capability-routes.ts index 075826360..9f46b77d5 100644 --- a/packages/agent-directory/src/workflow-capability-routes.ts +++ b/packages/agent-directory/src/workflow-capability-routes.ts @@ -61,13 +61,14 @@ import { CapabilityOutOfInventoryError, type CapabilityInventoryProvider, } from "./capability-inventory"; +import { + agentDefinitionSourceTree, + readAgentDefinitionWorkflowJson, + RetiredWorkflowEnvelopeError, +} from "./definition-asset"; import type { PinnedSkillIndexResolver } from "./routes"; import type { DefinitionSkillsStore } from "./skills-store"; -/** Where a definition's serialized `WorkflowDefinition` lives in its - * asset tree — same path `./routes.ts` reads/writes. */ -const AGENT_DEFINITION_ASSET_PATH = "workflow.json"; - /** * The tenant + principal + run a presented sidecar token and run * address resolve to. Declared structurally (mirroring @@ -135,6 +136,9 @@ export function createWorkflowCapabilityRoutes( if (err instanceof CapabilityOutOfInventoryError) { return c.json(errorEnvelope("bad_request", err.message), 400); } + if (err instanceof RetiredWorkflowEnvelopeError) { + return c.json(errorEnvelope("conflict", err.message), 409); + } throw err; }); @@ -217,11 +221,9 @@ export function createWorkflowCapabilityRoutes( // tenant-session route's own fail-closed check. assertCapabilityInInventory(body, inventory); - const workflowJson = new TextDecoder().decode( - await deps.assetService.readAssetBlob({ - assetId: row.assetId, - path: AGENT_DEFINITION_ASSET_PATH, - }), + const workflowJson = await readAgentDefinitionWorkflowJson( + deps.assetService, + row.assetId, ); let nextWorkflowJson: string; @@ -266,7 +268,10 @@ export function createWorkflowCapabilityRoutes( ref: DEFAULT_ASSET_REF, principal: { kind: "hub" }, tree: { - files: { [AGENT_DEFINITION_ASSET_PATH]: nextWorkflowJson }, + files: agentDefinitionSourceTree({ + handle: row.name, + workflowJson: nextWorkflowJson, + }), message, }, }); diff --git a/packages/agent-directory/src/workflow-skill-pin-routes.ts b/packages/agent-directory/src/workflow-skill-pin-routes.ts index a0914aaa1..5dd36d288 100644 --- a/packages/agent-directory/src/workflow-skill-pin-routes.ts +++ b/packages/agent-directory/src/workflow-skill-pin-routes.ts @@ -34,6 +34,11 @@ import type { AssetService } from "@intx/hub-sessions"; import { isWorkbenchHostDefinitionName } from "@corbits/chat/workbench-host-naming"; import { reindexPinnedSkills } from "./agent-workflow"; +import { + agentDefinitionSourceTree, + readAgentDefinitionWorkflowJson, + RetiredWorkflowEnvelopeError, +} from "./definition-asset"; import type { PinnedSkillIndexResolver } from "./routes"; import type { DefinitionSkillsStore } from "./skills-store"; import type { @@ -41,11 +46,6 @@ import type { WorkflowRunAuthenticator as WorkflowCapabilityRunAuthenticator, } from "./workflow-capability-routes"; -/** Where a definition's serialized `WorkflowDefinition` lives in its - * asset tree — same path `./routes.ts`/`./workflow-capability-routes.ts` - * read/write. */ -const AGENT_DEFINITION_ASSET_PATH = "workflow.json"; - /** Structurally the same run scope `workflow-capability-routes.ts` * resolves — reused by type alias rather than a fresh declaration, since * this route lives in the same package and there is no cycle risk to @@ -101,6 +101,16 @@ export function createWorkflowSkillPinRoutes( ): Hono { const app = new Hono(); + // A definition whose asset predates the source-form cutover cannot be + // read or re-pinned until it is re-authored — a client-visible + // conflict, never a server fault. + app.onError((err, c) => { + if (err instanceof RetiredWorkflowEnvelopeError) { + return c.json(errorEnvelope("conflict", err.message), 409); + } + throw err; + }); + app.use("*", async (c, next) => { const authHeader = c.req.header("authorization") ?? ""; const token = authHeader.startsWith("Bearer ") @@ -141,11 +151,9 @@ export function createWorkflowSkillPinRoutes( return c.json(definitionNotFound(body.definitionId), 404); } - const workflowJson = new TextDecoder().decode( - await deps.assetService.readAssetBlob({ - assetId: row.assetId, - path: AGENT_DEFINITION_ASSET_PATH, - }), + const workflowJson = await readAgentDefinitionWorkflowJson( + deps.assetService, + row.assetId, ); const skills = await deps.skillsStore.getSkills(row.assetId); @@ -166,7 +174,10 @@ export function createWorkflowSkillPinRoutes( ref: DEFAULT_ASSET_REF, principal: { kind: "hub" }, tree: { - files: { [AGENT_DEFINITION_ASSET_PATH]: nextWorkflowJson }, + files: agentDefinitionSourceTree({ + handle: row.name, + workflowJson: nextWorkflowJson, + }), message: `Pin ${body.skillName} skill to ${row.name}`, }, }); diff --git a/packages/agent-directory/test/routes.integration.test.ts b/packages/agent-directory/test/routes.integration.test.ts index e6300f5c3..3e18c4832 100644 --- a/packages/agent-directory/test/routes.integration.test.ts +++ b/packages/agent-directory/test/routes.integration.test.ts @@ -5,13 +5,13 @@ // an actual git commit — `routes.test.ts`'s hand-rolled fake // `AssetService` never exercises that validator, so it could not have // caught this. A definition created WITH skills used to write -// `skills.json` alongside `workflow.json` into the asset tree; that -// validator's hard allowlist (`workflow.json`, -// `capability-declarations.json`, `.gitignore`) rejects any other -// top-level entry with a `path_violation` 500. Pinned skills now live -// in this package's own `agent_directory.definition_skills` table (see -// `../src/skills-store.ts`), so the asset tree only ever carries -// `workflow.json`. +// `skills.json` into the asset tree beside its definition, which that +// validator rejected. Pinned skills now live in this package's own +// `agent_directory.definition_skills` table (see +// `../src/skills-store.ts`), so the asset tree only ever carries the +// source codebase `agentDefinitionSourceTree` renders — the one shape +// the validator now accepts, the retired `workflow.json` envelope +// having been refused at the push boundary. // // DB-gated: skipped when DATABASE_URL is unset, so a fresh checkout // still runs the unit gates. Run with e.g. diff --git a/packages/agent-directory/test/routes.test.ts b/packages/agent-directory/test/routes.test.ts index 67f3a9746..6022ce13a 100644 --- a/packages/agent-directory/test/routes.test.ts +++ b/packages/agent-directory/test/routes.test.ts @@ -21,6 +21,10 @@ import { buildAgentDefinitionWorkflow, serializeAgentDefinitionWorkflow, } from "../src/agent-workflow"; +import { + agentDefinitionSourceTree, + AGENT_DEFINITION_ENTRY_PATH, +} from "../src/definition-asset"; import { createAgentDefinitionRoutes } from "../src/routes"; import type { PinnedSkillIndexResolver } from "../src/routes"; import { @@ -29,12 +33,13 @@ import { } from "../src/skills-store"; import type { DefinitionAssetHistory } from "../src/definition-history"; import type { CapabilityInventoryProvider } from "../src/capability-inventory"; +import { definitionFrom, SOURCE_TREE_PATHS } from "./source-tree"; -/** A `readAssetBlob` that always answers `workflow.json` with - * `workflowBytes` — pinned skills no longer live in the asset tree (see - * `../src/skills-store.ts`), so a test that needs a definition's skills - * seeds a `DefinitionSkillsStore` directly instead of stubbing a second - * path here. */ +/** A `readAssetBlob` that always answers the definition's entry module + * with `workflowBytes` — pinned skills no longer live in the asset tree + * (see `../src/skills-store.ts`), so a test that needs a definition's + * skills seeds a `DefinitionSkillsStore` directly instead of stubbing a + * second path here. */ function readAssetBlobFor( workflowBytes: Uint8Array, ): AssetService["readAssetBlob"] { @@ -106,13 +111,14 @@ function fakeAssetService(overrides: Partial = {}): AssetService { }; } -/** The serialized definition a stored `workflow.json` carries, so the - * PUT path has something real to re-index. */ +/** The entry module a stored definition's asset carries, so the PUT + * path has something real to re-index. */ function storedDefinitionBytes( systemPrompt = "You are a careful research assistant.", ): Uint8Array { - return new TextEncoder().encode( - serializeAgentDefinitionWorkflow( + const tree = agentDefinitionSourceTree({ + handle: "research-buddy", + workflowJson: serializeAgentDefinitionWorkflow( buildAgentDefinitionWorkflow({ handle: "research-buddy", tenantDomain: TENANT.domain, @@ -120,7 +126,8 @@ function storedDefinitionBytes( systemPrompt, }), ), - ); + }); + return new TextEncoder().encode(tree[AGENT_DEFINITION_ENTRY_PATH]); } /** The one step agent's tool-package pins inside a serialized definition. */ @@ -405,7 +412,7 @@ function fakeCreateDb(): DB["db"] { } as unknown as DB["db"]; } -test("a create request with skills writes only workflow.json to the asset tree and records skills in the skills store", async () => { +test("a create request with skills writes the definition source tree to the asset and records skills in the skills store", async () => { let writtenFiles: Record | undefined; const skillsStore = createInMemoryDefinitionSkillsStore(); const app = buildApp( @@ -440,7 +447,7 @@ test("a create request with skills writes only workflow.json to the asset tree a }); expect(response.status).toBe(201); expect(writtenFiles).toBeDefined(); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); expect(await skillsStore.getSkills("ast_1")).toEqual([ "web-research", "long-form-write", @@ -482,7 +489,7 @@ test("a create request without skills records an empty skills list", async () => systemPrompt: "You are a careful research assistant.", }); expect(response.status).toBe(201); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); expect(await skillsStore.getSkills("ast_1")).toEqual([]); }); @@ -546,7 +553,7 @@ test("GET /skills omits unknown definition ids from the map rather than erroring expect(body.skills).toEqual({}); }); -test("PUT /:definitionId/skills replaces the skill set, writing only workflow.json to the asset tree", async () => { +test("PUT /:definitionId/skills replaces the skill set, writing the definition source tree to the asset", async () => { let writtenFiles: Record | undefined; const skillsStore = createInMemoryDefinitionSkillsStore(); const app = buildApp( @@ -567,7 +574,7 @@ test("PUT /:definitionId/skills replaces the skill set, writing only workflow.js skills: ["long-form-write"], }); expect(response.status).toBe(200); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); expect(await skillsStore.getSkills("ast_1")).toEqual(["long-form-write"]); const body = (await response.json()) as { skills: readonly string[] }; expect(body.skills).toEqual(["long-form-write"]); @@ -598,7 +605,7 @@ test("PUT /:definitionId/skills re-indexes the system prompt to exactly the new fakeSkillsDb({ id: "def_1", assetId: "ast_1" }), ); await put(app, "/def_1/skills", { skills: ["long-form-write"] }); - const prompt = promptFrom(writtenFiles?.["workflow.json"] as string); + const prompt = promptFrom(definitionFrom(writtenFiles)); expect(prompt).toContain("- long-form-write: What long-form-write does."); expect(prompt).not.toContain("stale"); expect(prompt.split("")).toHaveLength(2); @@ -623,7 +630,7 @@ test("PUT /:definitionId/skills with no pins strips the index from the prompt", fakeSkillsDb({ id: "def_1", assetId: "ast_1" }), ); await put(app, "/def_1/skills", { skills: [] }); - const workflowJson = writtenFiles?.["workflow.json"] as string; + const workflowJson = definitionFrom(writtenFiles); expect(promptFrom(workflowJson)).toBe( "You are a careful research assistant.", ); @@ -727,13 +734,72 @@ test("GET /:definitionId returns the agent's display name and system prompt", as expect(body.systemPrompt).toBe("You are a careful research assistant."); }); +/** A `readAssetBlob` for an asset written before the source-form + * cutover: it carries a bare `workflow.json`, so the entry module the + * routes read is simply absent. */ +function retiredEnvelopeAssetService( + overrides: Partial = {}, +): AssetService { + return fakeAssetService({ + readAssetBlob: (params) => + Promise.reject( + new AssetServiceError( + "not_found", + `readAssetBlob: asset ${params.assetId} has no blob at "${params.path}"`, + ), + ), + ...overrides, + }); +} + +test("GET /:definitionId answers 409, never a 500, for an asset still on the retired envelope", async () => { + const app = buildApp( + retiredEnvelopeAssetService(), + fakeInstructionsDb({ + id: "def_1", + assetId: "ast_1", + name: "research-buddy", + }), + ); + const response = await app.request("/def_1"); + expect(response.status).toBe(409); + const body = (await response.json()) as { + error: { code: string; message: string }; + }; + expect(body.error.code).toBe("conflict"); + expect(body.error.message).toContain("workflow.json"); +}); + +test("PUT /:definitionId answers 409 and writes nothing for an asset still on the retired envelope", async () => { + let populateCalled = false; + const app = buildApp( + retiredEnvelopeAssetService({ + populateAsset: () => { + populateCalled = true; + return Promise.resolve({ commitSha: "deadbeef" }); + }, + }), + fakeInstructionsDb({ + id: "def_1", + assetId: "ast_1", + name: "research-buddy", + }), + ); + const response = await put(app, "/def_1", { + name: "Research Buddy", + systemPrompt: "You are now polite.", + }); + expect(response.status).toBe(409); + expect(populateCalled).toBe(false); +}); + test("GET /:definitionId 404s for an unknown definition", async () => { const app = buildApp(fakeAssetService(), fakeInstructionsDb(undefined)); const response = await app.request("/def_missing"); expect(response.status).toBe(404); }); -test("PUT /:definitionId writes the new system prompt in a single workflow.json commit", async () => { +test("PUT /:definitionId writes the new system prompt in a single source-tree commit", async () => { let writtenFiles: Record | undefined; const db = fakeInstructionsDb({ id: "def_1", @@ -758,8 +824,8 @@ test("PUT /:definitionId writes the new system prompt in a single workflow.json systemPrompt: "You are now a blunt, no-nonsense researcher.", }); expect(response.status).toBe(200); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); - expect(promptFrom(writtenFiles?.["workflow.json"] as string)).toBe( + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); + expect(promptFrom(definitionFrom(writtenFiles))).toBe( "You are now a blunt, no-nonsense researcher.", ); expect(db.updateCalls).toEqual([ @@ -972,7 +1038,7 @@ test("a create request indexes its pinned skills into the stored system prompt", systemPrompt: "You are a careful research assistant.", skills: ["web-research"], }); - const workflowJson = writtenFiles?.["workflow.json"] as string; + const workflowJson = definitionFrom(writtenFiles); const prompt = promptFrom(workflowJson); expect(prompt.startsWith("You are a careful research assistant.")).toBe(true); expect(prompt).toContain("- web-research: What web-research does."); @@ -1046,7 +1112,7 @@ test("a create request with no pinned skills stores the author's prompt verbatim handle: "research-buddy", systemPrompt: "You are a careful research assistant.", }); - const workflowJson = writtenFiles?.["workflow.json"] as string; + const workflowJson = definitionFrom(writtenFiles); expect(promptFrom(workflowJson)).toBe( "You are a careful research assistant.", ); @@ -1124,9 +1190,6 @@ test("restore writes the old commit's blobs as a new, human-named commit — nev const oldWorkflow = storedDefinitionBytes("You were once blunt."); const app = buildApp( fakeAssetService({ - readAssetBlob: readAssetBlobFor( - storedDefinitionBytes("You are now polite."), - ), populateAsset: (params) => { writtenFiles = params.tree.files; writtenMessage = params.tree.message; @@ -1147,16 +1210,17 @@ test("restore writes the old commit's blobs as a new, human-named commit — nev commitSha: "sha1old", }); expect(response.status).toBe(200); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); - expect(promptFrom(writtenFiles?.["workflow.json"] as string)).toBe( - "You were once blunt.", - ); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); + expect(promptFrom(definitionFrom(writtenFiles))).toBe("You were once blunt."); expect(writtenMessage).toBe("Restore agent research-buddy to sha1old"); + // The response reports the definition just restored, read out of the + // entry module the route wrote — never a re-read of the asset, which + // would race whatever else is committing to it. const body = (await response.json()) as { systemPrompt: string }; - expect(body.systemPrompt).toBe("You are now polite."); + expect(body.systemPrompt).toBe("You were once blunt."); }); -test("restore 404s when the target commit never carried a workflow.json", async () => { +test("restore 404s when the target commit never carried an entry module", async () => { const app = buildApp( fakeAssetService(), fakeInstructionsDb({ @@ -1231,8 +1295,8 @@ test("adding a tool package pin merges it into the definition in one commit, nam name: "@corbits/github-tools", }); expect(response.status).toBe(200); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); - expect(pinsFrom(writtenFiles?.["workflow.json"] as string)).toEqual([ + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); + expect(pinsFrom(definitionFrom(writtenFiles))).toEqual([ { name: "@corbits/github-tools", version: "*" }, ]); expect(writtenMessage).toBe("Add @corbits/github-tools to research-buddy"); @@ -1320,11 +1384,9 @@ test("adding a skill merges it additively into the skills store and re-indexes t name: "research", }); expect(response.status).toBe(200); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); expect(await skillsStore.getSkills("ast_1")).toEqual(["research"]); - expect((writtenFiles?.["workflow.json"] as string).includes("research")).toBe( - true, - ); + expect(definitionFrom(writtenFiles).includes("research")).toBe(true); const body = (await response.json()) as { skills: string[] }; expect(body.skills).toEqual(["research"]); }); diff --git a/packages/agent-directory/test/source-tree.ts b/packages/agent-directory/test/source-tree.ts new file mode 100644 index 000000000..2f1fd8b17 --- /dev/null +++ b/packages/agent-directory/test/source-tree.ts @@ -0,0 +1,23 @@ +// What every route suite asserts about a written asset tree: it is the +// two-file source codebase `agentDefinitionSourceTree` renders, and the +// definition it carries round-trips back through the same reader the +// routes use. + +import { + AGENT_DEFINITION_ENTRY_PATH, + parseAgentDefinitionEntry, +} from "../src/definition-asset"; + +/** The two files a definition's asset tree carries, in render order. */ +export const SOURCE_TREE_PATHS = ["package.json", AGENT_DEFINITION_ENTRY_PATH]; + +/** The serialized definition a written source tree carries. */ +export function definitionFrom( + files: Record | undefined, +): string { + const entry = files?.[AGENT_DEFINITION_ENTRY_PATH]; + if (typeof entry !== "string") { + throw new Error("the written tree carries no entry module"); + } + return parseAgentDefinitionEntry(new TextEncoder().encode(entry), "ast_1"); +} diff --git a/packages/agent-directory/test/workflow-capability-routes.test.ts b/packages/agent-directory/test/workflow-capability-routes.test.ts index 50d1ef91c..684cc06f6 100644 --- a/packages/agent-directory/test/workflow-capability-routes.test.ts +++ b/packages/agent-directory/test/workflow-capability-routes.test.ts @@ -7,6 +7,7 @@ import { expect, test } from "bun:test"; import { Hono } from "hono"; +import { AssetServiceError } from "@intx/hub-sessions"; import type { AssetService } from "@intx/hub-sessions"; import type { DB } from "@intx/db"; @@ -19,11 +20,16 @@ import { type WorkflowCapabilityRunScope, type WorkflowRunAuthenticator, } from "../src/workflow-capability-routes"; +import { + agentDefinitionSourceTree, + AGENT_DEFINITION_ENTRY_PATH, +} from "../src/definition-asset"; import type { PinnedSkillIndexResolver } from "../src/routes"; import { createInMemoryDefinitionSkillsStore, type DefinitionSkillsStore, } from "../src/skills-store"; +import { SOURCE_TREE_PATHS } from "./source-tree"; import type { CapabilityInventoryProvider } from "../src/capability-inventory"; const TENANT_ID = "tnt_1"; @@ -50,8 +56,9 @@ const fakeSkillIndex: PinnedSkillIndexResolver = { }; function storedDefinitionBytes(): Uint8Array { - return new TextEncoder().encode( - serializeAgentDefinitionWorkflow( + const tree = agentDefinitionSourceTree({ + handle: "research-buddy", + workflowJson: serializeAgentDefinitionWorkflow( buildAgentDefinitionWorkflow({ handle: "research-buddy", tenantDomain: "acme.example", @@ -59,12 +66,14 @@ function storedDefinitionBytes(): Uint8Array { systemPrompt: "You are a careful research assistant.", }), ), - ); + }); + return new TextEncoder().encode(tree[AGENT_DEFINITION_ENTRY_PATH]); } -/** A `readAssetBlob` that always answers `workflow.json` — pinned skills - * no longer live in the asset tree, so a test that needs a definition's - * skills seeds a `DefinitionSkillsStore` directly instead. */ +/** A `readAssetBlob` that always answers the definition's entry module + * — pinned skills no longer live in the asset tree, so a test that needs + * a definition's skills seeds a `DefinitionSkillsStore` directly + * instead. */ function readAssetBlobFor( workflowBytes: Uint8Array, ): AssetService["readAssetBlob"] { @@ -165,6 +174,31 @@ test("a missing or unrecognized bearer token / run address is a 401", async () = expect(response.status).toBe(401); }); +test("a definition still on the retired envelope is a 409, never a 500, and writes nothing", async () => { + let populateCalled = false; + const app = buildApp({ + assetService: fakeAssetService({ + readAssetBlob: (params) => + Promise.reject( + new AssetServiceError( + "not_found", + `readAssetBlob: asset ${params.assetId} has no blob at "${params.path}"`, + ), + ), + populateAsset: () => { + populateCalled = true; + return Promise.resolve({ commitSha: "deadbeef" }); + }, + }), + }); + const response = await postCapability(app, OWN_DEFINITION_ID, { + kind: "toolPackage", + name: "@corbits/capability-tools", + }); + expect(response.status).toBe(409); + expect(populateCalled).toBe(false); +}); + test("a run targeting another definition's capabilities is a 403", async () => { const app = buildApp({}); const response = await postCapability(app, OTHER_DEFINITION_ID, { @@ -192,7 +226,7 @@ test("a run may add a capability to its own definition without any grant check", name: "@corbits/capability-tools", }); expect(response.status).toBe(200); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); expect(writtenMessage).toBe( "Add @corbits/capability-tools to research-buddy", ); @@ -241,7 +275,7 @@ test("adding a skill merges it additively into the skills store and re-indexes t name: "research", }); expect(response.status).toBe(200); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); expect(await skillsStore.getSkills("ast_1")).toEqual(["research"]); const body = (await response.json()) as { skills: string[] }; expect(body.skills).toEqual(["research"]); diff --git a/packages/agent-directory/test/workflow-create-routes.test.ts b/packages/agent-directory/test/workflow-create-routes.test.ts index c13fdf4ec..2d826820d 100644 --- a/packages/agent-directory/test/workflow-create-routes.test.ts +++ b/packages/agent-directory/test/workflow-create-routes.test.ts @@ -21,6 +21,7 @@ import type { import type { PinnedSkillIndexResolver } from "../src/routes"; import { createInMemoryDefinitionSkillsStore } from "../src/skills-store"; import type { CapabilityInventoryProvider } from "../src/capability-inventory"; +import { definitionFrom, SOURCE_TREE_PATHS } from "./source-tree"; const TENANT_ID = "tnt_1"; const RUN_ID = "run_1"; @@ -208,7 +209,7 @@ test("creates a definition and returns it, reusing the same materialization the }), }); expect(response.status).toBe(201); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); const body = (await response.json()) as { id: string; name: string }; expect(body.id).toBe("def_new"); }); @@ -258,9 +259,8 @@ test("a toolPackagePins entry the tenant's inventory offers is pinned onto the c }), }); expect(response.status).toBe(201); - const written = writtenFiles?.["workflow.json"]; - expect(typeof written).toBe("string"); - expect(written as string).toContain("@corbits/memory-tools"); + const written = definitionFrom(writtenFiles); + expect(written).toContain("@corbits/memory-tools"); }); test("a create naming no pins gets the baseline set the inventory offers — a specialist is never toolless (CL-6206)", async () => { @@ -283,7 +283,7 @@ test("a create naming no pins gets the baseline set the inventory offers — a s }), }); expect(response.status).toBe(201); - const written = writtenFiles?.["workflow.json"] as string; + const written = definitionFrom(writtenFiles); // The fake inventory offers memory-tools (see buildApp); mcp-tools and // interaction-tools are not offered, so only the resolvable baseline // member is pinned — never a pin that would fail at launch. @@ -315,9 +315,8 @@ test("a create with no model bakes the tenant's catalog default in, so the defin }), }); expect(response.status).toBe(201); - const written = writtenFiles?.["workflow.json"]; - expect(typeof written).toBe("string"); - expect(written as string).toContain("anthropic/claude-sonnet"); + const written = definitionFrom(writtenFiles); + expect(written).toContain("anthropic/claude-sonnet"); }); test("a create with an explicit model never consults the tenant default", async () => { @@ -344,8 +343,8 @@ test("a create with an explicit model never consults the tenant default", async }), }); expect(response.status).toBe(201); - const written = writtenFiles?.["workflow.json"]; - expect(written as string).toContain("openrouter/some-model"); + const written = definitionFrom(writtenFiles); + expect(written).toContain("openrouter/some-model"); }); test("an invalid body is a 400", async () => { diff --git a/packages/agent-directory/test/workflow-skill-pin-routes.test.ts b/packages/agent-directory/test/workflow-skill-pin-routes.test.ts index dd7c5f23f..67b2f6c28 100644 --- a/packages/agent-directory/test/workflow-skill-pin-routes.test.ts +++ b/packages/agent-directory/test/workflow-skill-pin-routes.test.ts @@ -6,6 +6,7 @@ import { expect, test } from "bun:test"; import { Hono } from "hono"; +import { AssetServiceError } from "@intx/hub-sessions"; import type { AssetService } from "@intx/hub-sessions"; import type { DB } from "@intx/db"; @@ -18,11 +19,16 @@ import { type WorkflowSkillPinRunScope, type WorkflowRunAuthenticator, } from "../src/workflow-skill-pin-routes"; +import { + agentDefinitionSourceTree, + AGENT_DEFINITION_ENTRY_PATH, +} from "../src/definition-asset"; import type { PinnedSkillIndexResolver } from "../src/routes"; import { createInMemoryDefinitionSkillsStore, type DefinitionSkillsStore, } from "../src/skills-store"; +import { SOURCE_TREE_PATHS } from "./source-tree"; const TENANT_ID = "tnt_1"; const OTHER_TENANT_ID = "tnt_2"; @@ -39,8 +45,9 @@ const fakeSkillIndex: PinnedSkillIndexResolver = { }; function storedDefinitionBytes(): Uint8Array { - return new TextEncoder().encode( - serializeAgentDefinitionWorkflow( + const tree = agentDefinitionSourceTree({ + handle: "research-buddy", + workflowJson: serializeAgentDefinitionWorkflow( buildAgentDefinitionWorkflow({ handle: "research-buddy", tenantDomain: "acme.example", @@ -48,7 +55,8 @@ function storedDefinitionBytes(): Uint8Array { systemPrompt: "You are a careful research assistant.", }), ), - ); + }); + return new TextEncoder().encode(tree[AGENT_DEFINITION_ENTRY_PATH]); } function readAssetBlobFor( @@ -252,13 +260,48 @@ test("pins a skill onto another definition in the same tenant and re-indexes its skillName: "research", }); expect(response.status).toBe(200); - expect(Object.keys(writtenFiles ?? {})).toEqual(["workflow.json"]); + expect(Object.keys(writtenFiles ?? {})).toEqual(SOURCE_TREE_PATHS); expect(writtenMessage).toBe("Pin research skill to research-buddy"); expect(await skillsStore.getSkills("ast_1")).toEqual(["research"]); const body = (await response.json()) as { skills: string[] }; expect(body.skills).toEqual(["research"]); }); +test("a definition still on the retired envelope is a 409, never a 500, and writes nothing", async () => { + lookupId = TARGET_DEFINITION_ID; + lookupTenant = TENANT_ID; + let populateCalled = false; + const app = buildApp({ + db: fakeDbWithRows([ + { + id: TARGET_DEFINITION_ID, + tenantId: TENANT_ID, + assetId: "ast_1", + name: "research-buddy", + }, + ]), + assetService: fakeAssetService({ + readAssetBlob: (params) => + Promise.reject( + new AssetServiceError( + "not_found", + `readAssetBlob: asset ${params.assetId} has no blob at "${params.path}"`, + ), + ), + populateAsset: () => { + populateCalled = true; + return Promise.resolve({ commitSha: "deadbeef" }); + }, + }), + }); + const response = await postPin(app, { + definitionId: TARGET_DEFINITION_ID, + skillName: "research", + }); + expect(response.status).toBe(409); + expect(populateCalled).toBe(false); +}); + test("pinning the same skill twice is idempotent, never duplicated", async () => { lookupId = TARGET_DEFINITION_ID; lookupTenant = TENANT_ID; diff --git a/packages/agent-runtime/LICENSE b/packages/agent-runtime/LICENSE new file mode 100644 index 000000000..c6487f4fd --- /dev/null +++ b/packages/agent-runtime/LICENSE @@ -0,0 +1,176 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json index e1a35d50b..07dedd25a 100644 --- a/packages/agent-runtime/package.json +++ b/packages/agent-runtime/package.json @@ -13,6 +13,7 @@ "test": "bun test" }, "dependencies": { + "@corbits/workflow-source": "workspace:*", "@intx/agent": "workspace:*", "@intx/types": "workspace:*", "@intx/workflow": "workspace:*", diff --git a/packages/agent-runtime/src/source-tree.ts b/packages/agent-runtime/src/source-tree.ts index f43038f0e..96ae1c59f 100644 --- a/packages/agent-runtime/src/source-tree.ts +++ b/packages/agent-runtime/src/source-tree.ts @@ -12,21 +12,25 @@ // rather than shipping a call to it: an asset tree is a standalone // codebase, so a `workspace:*` dependency on `@corbits/agent-runtime` // has no workspace to resolve against and the closure resolver rejects -// it outright. This is the same shape the seed's default workflows take -// (`@workbench/hub-client`'s `renderWorkflowSourceTree`) — the whole -// closure is these two files — and it keeps the config-IS-the-bytes -// property the retirement requires: everything that varies per run is -// inside the hashed source, nothing rides beside it. +// it outright. `@corbits/workflow-source` renders the tree itself — +// the same two files every other authoring path writes — which keeps +// the config-IS-the-bytes property the retirement requires: +// everything that varies per run is inside the hashed source, nothing +// rides beside it. // // A host commits the tree into a `workflow`-kind asset and deploys it // with `source.kind: "asset"`, `package.format: "source"`, `commitSha` — // the only source variant whose pin is cheap enough to mint per run // (the registry and tarball variants would each need a publish). +import { + renderWorkflowSourceTree, + WORKFLOW_SOURCE_ENTRY, +} from "@corbits/workflow-source"; import { parseAgentRuntimeConfig, type AgentRuntimeConfig } from "./config"; import { buildAgentRuntimeWorkflow } from "./definition"; /** The entry path the rendered `package.json` declares and the sidecar evaluates. */ -export const AGENT_RUNTIME_ENTRY_PATH = "./workflow.js"; +export const AGENT_RUNTIME_ENTRY_PATH = WORKFLOW_SOURCE_ENTRY; export interface RenderAgentRuntimeSourceTreeInput { /** @@ -52,18 +56,10 @@ export function renderAgentRuntimeSourceTree( const config = parseAgentRuntimeConfig(input.config); const definition = buildAgentRuntimeWorkflow(config); assertJsonPortable(definition, "definition"); - const packageJson = { - name: input.packageName, - version: "0.0.0", - private: true, - type: "module", - interchange: { workflow: AGENT_RUNTIME_ENTRY_PATH }, - }; - - return { - "package.json": `${JSON.stringify(packageJson, null, 2)}\n`, - "workflow.js": `export default ${JSON.stringify(definition, null, 2)};\n`, - }; + return renderWorkflowSourceTree({ + packageName: input.packageName, + workflowJson: JSON.stringify(definition, null, 2), + }); } /** diff --git a/packages/evals/src/targets/world-snapshot.test.ts b/packages/evals/src/targets/world-snapshot.test.ts index c48e7c9eb..e26e42cf9 100644 --- a/packages/evals/src/targets/world-snapshot.test.ts +++ b/packages/evals/src/targets/world-snapshot.test.ts @@ -3,6 +3,8 @@ import { expect, test } from "bun:test"; import type { DB } from "@intx/db"; import type { AssetService } from "@intx/hub-sessions"; +import { agentDefinitionSourceTree } from "@corbits/agent-directory"; + import { captureWorldSnapshot, type WorldSnapshotInfra, @@ -65,10 +67,23 @@ function fakeDb(tables: FakeTables): DB["db"] { } as unknown as DB["db"]; } +/** Answers each asset's entry module out of the source tree its + * definition renders into — the shape the snapshot reads through. */ function fakeAssetService(blobs: Record): AssetService { return { - readAssetBlob: async ({ assetId }: { assetId: string }) => - new TextEncoder().encode(blobs[assetId] ?? "{}"), + readAssetBlob: async ({ + assetId, + path, + }: { + assetId: string; + path: string; + }) => + new TextEncoder().encode( + agentDefinitionSourceTree({ + handle: assetId, + workflowJson: blobs[assetId] ?? "{}", + })[path], + ), } as unknown as AssetService; } diff --git a/packages/evals/src/targets/world-snapshot.ts b/packages/evals/src/targets/world-snapshot.ts index 619091d15..c301780b3 100644 --- a/packages/evals/src/targets/world-snapshot.ts +++ b/packages/evals/src/targets/world-snapshot.ts @@ -12,8 +12,9 @@ // `listVisibleAgentDefinitions` query shape, minus its DM-only // filtering (a world snapshot wants every deployed definition, not // just the conversational ones a sidebar would show), then -// `readAgentCapabilities` on each definition's `workflow.json` — -// the same function `GET /:definitionId/capabilities` calls. +// `readAgentCapabilities` on the definition its asset's source tree +// carries, read back through `readAgentDefinitionWorkflowJson` — +// the same pair `GET /:definitionId/capabilities` calls. // - routines: `routines.routine`, queried the same // `tenantId`/`deletedAt IS NULL` shape `RoutineStore.listRoutines` // uses. @@ -24,15 +25,15 @@ import { and, eq, isNull } from "drizzle-orm"; import type { DB } from "@intx/db"; import { schema } from "@intx/db"; import type { AssetService } from "@intx/hub-sessions"; -import { DEFAULT_ASSET_REF } from "@intx/hub-sessions"; -import { readAgentCapabilities } from "@corbits/agent-directory"; +import { + readAgentCapabilities, + readAgentDefinitionWorkflowJson, +} from "@corbits/agent-directory"; import { routine as routineTable } from "@corbits/routines"; import { listMcpServerConnections } from "@workbench/connections"; import type { FakeReceipt, WorldSnapshot } from "../types.ts"; -const AGENT_DEFINITION_ASSET_PATH = "workflow.json"; - /** The infra `captureWorldSnapshot` reads through — a real `@intx/db` * drizzle handle and `AssetService`, the same two things * `agent-directory`'s own routes already depend on, so a caller @@ -62,12 +63,9 @@ async function readAgentDefinitions( ); return Promise.all( deployable.map(async (row) => { - const workflowJson = new TextDecoder().decode( - await assetService.readAssetBlob({ - assetId: row.assetId, - ref: DEFAULT_ASSET_REF, - path: AGENT_DEFINITION_ASSET_PATH, - }), + const workflowJson = await readAgentDefinitionWorkflowJson( + assetService, + row.assetId, ); const capabilities = readAgentCapabilities(workflowJson); return { diff --git a/packages/hub-client/package.json b/packages/hub-client/package.json index 63b57f0f2..b20b00d37 100644 --- a/packages/hub-client/package.json +++ b/packages/hub-client/package.json @@ -25,6 +25,7 @@ "@corbits/tool-registry-publish": "workspace:*", "@corbits/workbench-digest-workflow": "workspace:*", "@corbits/workflow-catalog": "workspace:*", + "@corbits/workflow-source": "workspace:*", "@intx/inference": "workspace:*", "@intx/types": "workspace:*", "arktype": "catalog:" diff --git a/packages/hub-client/src/seed.ts b/packages/hub-client/src/seed.ts index 9963e4f00..94a6d5346 100644 --- a/packages/hub-client/src/seed.ts +++ b/packages/hub-client/src/seed.ts @@ -53,7 +53,7 @@ import { publishCorbitsToolsRegistry, type PublishCorbitsToolsRegistryArgs, } from "@corbits/tool-registry-publish"; -import { WORKFLOW_SOURCE_ENTRY } from "./workflow-push"; +import { WORKFLOW_SOURCE_ENTRY } from "@corbits/workflow-source"; import { CliError, SidecarUnavailableError } from "./errors"; import { DEFAULT_SKILLS } from "./default-skills"; import { ensureDefaultRoutines } from "./default-routines"; diff --git a/packages/hub-client/src/workflow-push.ts b/packages/hub-client/src/workflow-push.ts index 2d13bd540..f9aa74bc6 100644 --- a/packages/hub-client/src/workflow-push.ts +++ b/packages/hub-client/src/workflow-push.ts @@ -5,45 +5,18 @@ // convention. Content-aware: an identical tree is a reported skip, not // a duplicate commit, which is what makes re-running seed safe. // -// The pushed tree is a source codebase, not the retired `workflow.json` -// envelope: a `package.json` declaring an `interchange.workflow` entry -// plus that entry module, which default-exports the definition. A -// workflow-kind asset accepts nothing else (see -// `vendor/intx/hub-sessions/src/workflow-kind.ts`), and a code-sourced -// deploy evaluates the entry rather than re-reading a serialized -// envelope. The definition these default workflows carry is inert data, -// so the entry is that data as a literal and the package declares no -// dependencies — the whole closure is these two files. +// The pushed tree is the source codebase `@corbits/workflow-source` +// renders — the one shape a workflow-kind asset accepts (see +// `vendor/intx/hub-sessions/src/workflow-kind.ts`), shared with every +// other authoring path in this repo. import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { renderWorkflowSourceTree } from "@corbits/workflow-source"; import { CliError } from "./errors"; import type { WorkflowPusher } from "./seed"; -const ENTRY_PATH = "workflow.js"; -/** The `interchange.workflow` entry a code-sourced deploy names. */ -export const WORKFLOW_SOURCE_ENTRY = `./${ENTRY_PATH}`; -const PACKAGE_JSON_PATH = "package.json"; - -/** The two-file source tree a serialized definition renders into. */ -export function renderWorkflowSourceTree(args: { - packageName: string; - workflowJson: string; -}): Record { - const packageJson = { - name: args.packageName, - version: "0.0.0", - private: true, - type: "module", - interchange: { workflow: WORKFLOW_SOURCE_ENTRY }, - }; - return { - [PACKAGE_JSON_PATH]: `${JSON.stringify(packageJson, null, 2)}\n`, - [ENTRY_PATH]: `export default ${args.workflowJson};\n`, - }; -} - function requireGit(): void { if (Bun.which("git") === null) { throw new CliError( diff --git a/packages/workflow-source/LICENSE b/packages/workflow-source/LICENSE new file mode 100644 index 000000000..c6487f4fd --- /dev/null +++ b/packages/workflow-source/LICENSE @@ -0,0 +1,176 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/packages/workflow-source/package.json b/packages/workflow-source/package.json new file mode 100644 index 000000000..11457ba64 --- /dev/null +++ b/packages/workflow-source/package.json @@ -0,0 +1,19 @@ +{ + "name": "@corbits/workflow-source", + "private": true, + "description": "The source codebase a workflow-kind asset carries — the two-file renderer every authoring path writes and the reader that recovers the definition back out of it", + "version": "0.0.1", + "license": "LGPL-2.1-or-later", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:" + } +} diff --git a/packages/workflow-source/src/index.test.ts b/packages/workflow-source/src/index.test.ts new file mode 100644 index 000000000..f7335d9c5 --- /dev/null +++ b/packages/workflow-source/src/index.test.ts @@ -0,0 +1,71 @@ +import { expect, test } from "bun:test"; + +import { + parseWorkflowSourceEntry, + readWorkflowSourceDefinition, + renderWorkflowSourceTree, + RetiredWorkflowEnvelopeError, + WORKFLOW_SOURCE_ENTRY, +} from "./index"; + +const WORKFLOW_JSON = JSON.stringify({ id: "wf_agent_research-buddy" }); + +test("the rendered tree is a manifest naming the entry plus the entry itself", () => { + const tree = renderWorkflowSourceTree({ + packageName: "@workbench-agent/research-buddy", + workflowJson: WORKFLOW_JSON, + }); + + expect(Object.keys(tree).sort()).toEqual(["package.json", "workflow.js"]); + const manifest = JSON.parse(tree["package.json"] as string) as { + name: string; + interchange: { workflow: string }; + }; + expect(manifest.name).toBe("@workbench-agent/research-buddy"); + expect(manifest.interchange.workflow).toBe(WORKFLOW_SOURCE_ENTRY); +}); + +test("the definition round-trips through the entry module", () => { + const tree = renderWorkflowSourceTree({ + packageName: "@workbench-agent/research-buddy", + workflowJson: WORKFLOW_JSON, + }); + + expect(parseWorkflowSourceEntry(tree["workflow.js"] as string, "ast_1")).toBe( + WORKFLOW_JSON, + ); +}); + +test("a bare workflow.json envelope parses as the named retirement error", () => { + expect(() => parseWorkflowSourceEntry(WORKFLOW_JSON, "ast_1")).toThrow( + RetiredWorkflowEnvelopeError, + ); +}); + +test("an asset with no entry module reads as the named retirement error", async () => { + const reader = { + readAssetBlob: (params: { assetId: string; path: string }) => + Promise.reject( + new Error(`asset ${params.assetId} has no blob at ${params.path}`), + ), + }; + + await expect(readWorkflowSourceDefinition(reader, "ast_1")).rejects.toThrow( + RetiredWorkflowEnvelopeError, + ); +}); + +test("reading a source-form asset answers its serialized definition", async () => { + const tree = renderWorkflowSourceTree({ + packageName: "@workbench-agent/research-buddy", + workflowJson: WORKFLOW_JSON, + }); + const reader = { + readAssetBlob: (params: { assetId: string; path: string }) => + Promise.resolve(new TextEncoder().encode(tree[params.path] as string)), + }; + + expect(await readWorkflowSourceDefinition(reader, "ast_1")).toBe( + WORKFLOW_JSON, + ); +}); diff --git a/packages/workflow-source/src/index.ts b/packages/workflow-source/src/index.ts new file mode 100644 index 000000000..199778f4f --- /dev/null +++ b/packages/workflow-source/src/index.ts @@ -0,0 +1,127 @@ +// The one shape a `workflow`-kind asset may carry. +// +// Upstream retired the on-disk `workflow.json` envelope: the push +// validator (`vendor/intx/hub-sessions/src/workflow-kind.ts`, +// `workflowKindHandler.validatePush`) refuses a bare serialized +// definition and accepts only a source codebase — a `package.json` +// declaring `interchange.workflow` plus that entry module, which +// default-exports the definition. Every authoring path in this repo +// writes that tree through `renderWorkflowSourceTree` and recovers the +// definition back out of it through `parseWorkflowSourceEntry`, so the +// bytes on disk have exactly one producer and one consumer. +// +// The entry is a JSON literal rather than a call into a builder: an +// asset tree is a standalone codebase, so it can declare no workspace +// dependency to evaluate, and the definition it carries is inert data. +// That is what lets the reader below be a strict slice of a known +// prefix and suffix instead of an evaluation. + +/** The entry module's path inside the asset tree. */ +export const WORKFLOW_SOURCE_ENTRY_PATH = "workflow.js"; +/** The `interchange.workflow` entry a code-sourced deploy names. */ +export const WORKFLOW_SOURCE_ENTRY = `./${WORKFLOW_SOURCE_ENTRY_PATH}`; +/** The manifest's path inside the asset tree. */ +export const WORKFLOW_SOURCE_MANIFEST_PATH = "package.json"; +/** The path a pre-retirement asset carried its definition at. */ +export const RETIRED_WORKFLOW_ENVELOPE_PATH = "workflow.json"; + +const ENTRY_PREFIX = "export default "; +const ENTRY_SUFFIX = ";\n"; + +export type WorkflowSourceTree = Readonly>; + +/** The two-file source tree a serialized definition renders into. */ +export function renderWorkflowSourceTree(args: { + packageName: string; + workflowJson: string; +}): WorkflowSourceTree { + const packageJson = { + name: args.packageName, + version: "0.0.0", + private: true, + type: "module", + interchange: { workflow: WORKFLOW_SOURCE_ENTRY }, + }; + return { + [WORKFLOW_SOURCE_MANIFEST_PATH]: `${JSON.stringify(packageJson, null, 2)}\n`, + [WORKFLOW_SOURCE_ENTRY_PATH]: `${ENTRY_PREFIX}${args.workflowJson}${ENTRY_SUFFIX}`, + }; +} + +/** + * Thrown when an asset does not carry the source form — in practice, an + * asset last written before the retirement, whose tree still holds a + * bare `workflow.json`. Named so every route boundary can answer it as + * a client-visible conflict with re-authoring guidance rather than + * letting it read as a server fault. + */ +export class RetiredWorkflowEnvelopeError extends Error { + readonly assetId: string; + + constructor(assetId: string, options?: { cause?: unknown }) { + super( + `Asset "${assetId}" still carries the retired ${RETIRED_WORKFLOW_ENVELOPE_PATH} envelope ` + + `instead of a ${WORKFLOW_SOURCE_ENTRY_PATH} source entry. Re-author and re-deploy the ` + + `definition to write its source tree; nothing can read or edit it until then.`, + options, + ); + this.name = "RetiredWorkflowEnvelopeError"; + this.assetId = assetId; + } +} + +/** + * Recovers the serialized definition from the exact bytes + * `renderWorkflowSourceTree` emits. A strict single-shape slice, never + * an evaluation: anything else is an asset this lineage did not author + * in its current form. + */ +export function parseWorkflowSourceEntry( + entryModule: string, + assetId: string, +): string { + if ( + !entryModule.startsWith(ENTRY_PREFIX) || + !entryModule.endsWith(ENTRY_SUFFIX) + ) { + throw new RetiredWorkflowEnvelopeError(assetId); + } + return entryModule.slice( + ENTRY_PREFIX.length, + entryModule.length - ENTRY_SUFFIX.length, + ); +} + +/** + * The blob read a source-form asset needs. Declared structurally so this + * package stays dependency-free; `@intx/hub-sessions`' `AssetService` + * satisfies it exactly. + */ +export type WorkflowSourceBlobReader = { + readAssetBlob(params: { assetId: string; path: string }): Promise; +}; + +/** + * Reads a source-form asset's serialized definition. A missing entry + * module is the retirement's own failure mode — an asset written before + * the cutover — so it surfaces as `RetiredWorkflowEnvelopeError` rather + * than the asset service's generic not-found. + */ +export async function readWorkflowSourceDefinition( + reader: WorkflowSourceBlobReader, + assetId: string, +): Promise { + let entryBytes: Uint8Array; + try { + entryBytes = await reader.readAssetBlob({ + assetId, + path: WORKFLOW_SOURCE_ENTRY_PATH, + }); + } catch (cause) { + throw new RetiredWorkflowEnvelopeError(assetId, { cause }); + } + return parseWorkflowSourceEntry( + new TextDecoder().decode(entryBytes), + assetId, + ); +} diff --git a/packages/workflow-source/tsconfig.json b/packages/workflow-source/tsconfig.json new file mode 100644 index 000000000..e956ddd88 --- /dev/null +++ b/packages/workflow-source/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["bun"] + }, + "include": ["src", "test"] +} diff --git a/scripts/e2e/cl-6324-launch-proof.ts b/scripts/e2e/cl-6324-launch-proof.ts index 94d25897b..899cf0478 100644 --- a/scripts/e2e/cl-6324-launch-proof.ts +++ b/scripts/e2e/cl-6324-launch-proof.ts @@ -8,11 +8,13 @@ // deploys off a pushed source codebase, no `workflow.json` envelope. // 2. A workbench mint walks the whole new deploy path: the approval // probe answers, the closure materializes FOR REAL on the sidecar, -// and the run's own event log carries `RunStarted`. +// and the run brackets a real per-message turn. Asserted in BOTH +// deploy shapes, because the bracket is a different durable +// artefact in each — see `PROOF 2` and `PROOF 2b` below. // 3. A real human message gets a real model reply. // 4. The sidecar is killed mid-turn and restarted: boot restore // replays the deployment's pin, the room survives, and the next -// message is answered. +// message is answered — in both shapes. // // Usage: // E2E_PROVIDER=ollama OLLAMA_BASE_URL=http://localhost:11434 \ @@ -32,13 +34,20 @@ import { seedTenant, type ApiCall, } from "../../packages/hub-client/src/index.ts"; +import { WORKFLOW_SOURCE_ENTRY } from "../../packages/workflow-source/src/index.ts"; +import { + agentRuntimeTurnRunId, + buildAgentRuntimeWorkflow, +} from "../../packages/agent-runtime/src/index.ts"; import { findPersonalTenant, testAndPersistCredential, ensureSeeded, - modelSourceFor, } from "../../packages/onboarding/src/complete-credential.ts"; -import { OLLAMA_PLACEHOLDER_SECRET } from "../../packages/hub-client/src/credential-test.ts"; +import { + OLLAMA_PLACEHOLDER_SECRET, + ollamaOpenAICompatBaseURL, +} from "../../packages/hub-client/src/credential-test.ts"; import { api, e2eDatabaseUrl, @@ -53,13 +62,14 @@ import { type SpawnedApp, } from "./harness.ts"; -const databaseUrl = e2eDatabaseUrl(); -if (databaseUrl === undefined) { +const configuredDatabaseUrl = e2eDatabaseUrl(); +if (configuredDatabaseUrl === undefined) { throw new Error( "cl-6324-launch-proof: DATABASE_URL is not set. This suite proves a real " + "boot and has nothing honest to assert without one.", ); } +const databaseUrl: string = configuredDatabaseUrl; const OLLAMA_BASE_URL = process.env["OLLAMA_BASE_URL"]; if (process.env["E2E_PROVIDER"] !== "ollama" || OLLAMA_BASE_URL === undefined) { @@ -70,6 +80,25 @@ if (process.env["E2E_PROVIDER"] !== "ollama" || OLLAMA_BASE_URL === undefined) { } const ollamaBaseUrl = OLLAMA_BASE_URL; +// Named explicitly rather than taken from `CATALOG_SEEDS.ollama`: the +// curated seed lists models a given instance may simply not have pulled, +// and a deploy pinned at a model the instance cannot serve fails as an +// inference error that reads nothing like the thing being proved. +const OLLAMA_MODEL = process.env["E2E_OLLAMA_MODEL"]; +if (OLLAMA_MODEL === undefined || OLLAMA_MODEL === "") { + throw new Error( + "cl-6324-launch-proof: set E2E_OLLAMA_MODEL to a completion model the " + + "instance at OLLAMA_BASE_URL actually serves (see `ollama list`).", + ); +} +/** The model source every deploy in this proof pins, explicitly. */ +const proofModelSource = { + provider: "openai-compatible", + model: OLLAMA_MODEL, + baseURL: ollamaOpenAICompatBaseURL(ollamaBaseUrl), + apiKey: OLLAMA_PLACEHOLDER_SECRET, +} as const; + const TURN_TIMEOUT_MS = 300_000; const tracked: SpawnedApp[] = []; @@ -134,7 +163,11 @@ const timings: { label: string; ms: number }[] = []; async function timed(label: string, run: () => Promise): Promise { const t0 = Date.now(); const value = await run(); - timings.push({ label, ms: Date.now() - t0 }); + const ms = Date.now() - t0; + timings.push({ label, ms }); + // Printed as it lands, not only in the summary: a run that fails at a + // later proof still has to report what the earlier ones cost. + console.log(` TIMING — ${label}: ${(ms / 1000).toFixed(1)}s`); return value; } @@ -274,11 +307,7 @@ async function main(): Promise { principalId: tenant.principalId, domain: tenant.tenantDomain, }, - model: modelSourceFor( - "ollama", - OLLAMA_PLACEHOLDER_SECRET, - ollamaBaseUrl, - ), + model: proofModelSource, pushWorkflow, log: () => undefined, workflows: DEFAULT_WORKFLOWS, @@ -293,6 +322,93 @@ async function main(): Promise { }), ); + async function plantGrant(resource: string, action: string): Promise { + const granted = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenant.tenantId}/grants`, + { + principalId: tenant.principalId, + resource, + action, + effect: "allow", + origin: "system", + }, + user.cookies, + ); + if (granted.status !== 201 && granted.status !== 409) { + throw new Error( + `could not plant the ${resource}/${action} grant: ` + + `${String(granted.status)} ${JSON.stringify(granted.data)}`, + ); + } + } + + // A live Ollama connect seeds one catalog offering per pulled model, + // embedding models included, with no capability metadata to tell them + // apart (CL-6351). Default-model resolution then breaks the tie + // alphabetically, so `all-minilm` wins the bench default and every + // chat turn dies before it reaches a model. This proof pins ONE model + // on purpose, so it narrows the bench's own catalog to that model + // through the catalog API rather than leaving the turn's model to a + // coin flip the proof is not about. + await hop("narrow the bench catalog to the pinned model", async () => { + await plantGrant("model-offering:*", "read"); + await plantGrant("model-offering:*", "manage"); + await plantGrant("model:*", "read"); + + const models = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenant.tenantId}/catalog/models?limit=200`, + undefined, + user.cookies, + ); + expectStatus("list the bench catalog models", models, 200); + const modelRows = arrayField(models.data, "data", "catalog models") as { + id: string; + canonicalName: string; + }[]; + const pinned = modelRows.find( + (row) => row.canonicalName === proofModelSource.model, + ); + if (pinned === undefined) { + throw new Error( + `the bench catalog carries no model named ${proofModelSource.model}; ` + + `it has ${JSON.stringify(modelRows.map((m) => m.canonicalName))}`, + ); + } + + const offerings = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenant.tenantId}/catalog/offerings?limit=200`, + undefined, + user.cookies, + ); + expectStatus("list the bench model offerings", offerings, 200); + const offeringRows = arrayField( + offerings.data, + "data", + "model offerings", + ) as { id: string; modelId: string; disabled: boolean }[]; + for (const offering of offeringRows) { + if (offering.modelId === pinned.id || offering.disabled) continue; + const patched = await api( + hub.baseUrl, + "PATCH", + `/api/tenants/${tenant.tenantId}/catalog/offerings/${offering.id}`, + { disabled: true }, + user.cookies, + ); + expectStatus(`disable offering ${offering.id}`, patched, 200); + } + console.log( + ` TRANSCRIPT — bench catalog narrowed to ${proofModelSource.model} ` + + `(${String(offeringRows.length - 1)} other offerings disabled)`, + ); + }); + const assistantDefinitionId = await hop( "PROOF 1 — 'assistant' is invitable tenant-wide", async () => { @@ -402,6 +518,58 @@ async function main(): Promise { return (raw as { events: { seq: number; type: string }[] }).events; } + /** + * The run ids present in a deployment's workflow-run event repo — the + * anchor plus every child run that has committed an event. A + * section-mode occurrence shows up here as `turn__` the moment its + * first event lands. + */ + async function listDeploymentRunIds(anchorRunId: string): Promise { + const res = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenant.tenantId}/workflows/${anchorRunId}/runs`, + undefined, + user.cookies, + ); + if (res.status !== 200) return []; + const raw = res.data; + if ( + typeof raw !== "object" || + raw === null || + !Array.isArray((raw as Record)["runIds"]) + ) { + return []; + } + return (raw as { runIds: string[] }).runIds; + } + + /** + * The number of completed per-message brackets the hub has durably + * recorded for this tenant. `@corbits/insights`' latency tracker opens + * a row on the `message.run.started` AGENT event and commits it on + * `message.run.ended`, so a non-zero sample count is durable, + * HTTP-observable evidence that the bracket both opened and closed — + * the only such evidence a folded `step`-mode turn produces. + */ + async function completedTurnBrackets(): Promise { + const res = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenant.tenantId}/insights/latency`, + undefined, + user.cookies, + ); + expectStatus("read the turn-latency summary", res, 200); + const total = (res.data as { total?: { samples?: unknown } }).total; + if (typeof total?.samples !== "number") { + throw new Error( + `the latency summary carries no total.samples: ${JSON.stringify(res.data)}`, + ); + } + return total.samples; + } + async function listAgentMessages(): Promise<{ id: string; text: string }[]> { const res = await api( hub.baseUrl, @@ -430,9 +598,13 @@ async function main(): Promise { const seenIds = new Set(); - await timed("proof 2: greeting turn (deploy + first token)", () => + // The joining greeting is CANNED copy `@corbits/chat` posts from the + // agent's address (`workbench-service.ts`'s welcome line), not a model + // turn — so it times the room and the participant join, and nothing + // about inference. The deploy path's first real token is proof 3's. + await timed("proof 2: canned join greeting lands (room + participant)", () => hop( - "PROOF 2 — an agent-authored greeting lands with no user message sent", + "PROOF 2 — the minted chat carries its agent and its canned greeting", async () => { const deadline = Date.now() + TURN_TIMEOUT_MS; for (;;) { @@ -455,27 +627,296 @@ async function main(): Promise { ), ); + // A folded `step`-mode run is ONE unbounded step servicing every + // inbound mail, so its per-message bracket is the `message.run.started` + // AGENT event (`packages/folded-runs/src/agent-events.ts`) — an + // in-process sidecar frame the hub consumes and never commits to the + // run's durable workflow event log. Asserting a workflow-host + // `RunStarted` per message here would be asserting the section shape's + // contract against the step shape's run, which is why the earlier + // revision of this proof hung on it. + // + // What IS durable and HTTP-observable for a step-mode turn is the reply + // row the completed bracket wrote, already asserted above. What this + // step adds is the shape fact itself, stated as a falsifiable + // assertion rather than a footnote: a step-mode run brackets NO + // per-occurrence child run. `PROOF 2b` asserts the opposite for the + // section shape, and the two together are the real evidence. await hop( - "PROOF 2 — the run's own event log carries RunStarted", + "PROOF 2 — a step-mode run's durable bracket is its reply row, and it starts no per-occurrence child run", async () => { - const deadline = Date.now() + 120_000; - for (;;) { - const events = await readRunEvents(); - if (events.some((e) => e.type === "RunStarted")) { - console.log( - ` TRANSCRIPT — run ${agentRunId} events: ` + - JSON.stringify(events.map((e) => `${String(e.seq)}:${e.type}`)), + const events = await readRunEvents(); + const childRunIds = await listDeploymentRunIds(agentRunId); + console.log( + ` TRANSCRIPT — step-mode run ${agentRunId} workflow events: ` + + JSON.stringify(events.map((e) => `${String(e.seq)}:${e.type}`)), + ); + console.log( + ` TRANSCRIPT — step-mode run ${agentRunId} child run ids: ` + + JSON.stringify(childRunIds), + ); + const perOccurrence = childRunIds.filter((id) => /__\d+$/.test(id)); + if (perOccurrence.length > 0) { + throw new Error( + `a step-mode folded run started per-occurrence child runs ` + + `${JSON.stringify(perOccurrence)}; the folded shape is one ` + + `unbounded step and must not fan out per message`, + ); + } + }, + ); + + // ---- proof 2b: the section shape's true per-occurrence child run --- + // + // Also CL-6329's first live validation: `mode: "section"` has existed + // as a config argument since the agent-runtime cutover, but nothing had + // ever deployed or run one. Here one is deployed for real — rendered + // into its own source package, pushed as a workflow-kind asset, + // deployed by source-ref, and driven with real mail — and every message + // becomes an `onTrigger` occurrence with its own child run id and its + // own durable event log, which is the artefact the milestone's + // `RunStarted` assertion was always about. + const SECTION_ASSET_NAME = "cl6324-section"; + const SECTION_SOURCE_ID = "cl6324-section-source"; + const SECTION_TURN_TIMEOUT_MS = 180_000; + const sectionAddress = `${SECTION_ASSET_NAME}@${tenant.tenantDomain}`; + + const sectionDeploymentId = await timed( + "proof 2b: section-mode deploy (push + probe + freeze + deploy)", + () => + hop( + "PROOF 2b — a section-mode agent deploys from its own rendered source", + async () => { + const created = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenant.tenantId}/assets`, + { + kind: "workflow", + name: SECTION_ASSET_NAME, + displayName: "CL-6324 section-mode proof", + }, + user.cookies, ); - return; - } - if (Date.now() > deadline) { - throw new Error( - `run ${agentRunId} never recorded RunStarted; events seen: ` + - `${JSON.stringify(events)}\nhub output:\n${hub.output()}` + - `\nsidecar output:\n${sidecar.output()}`, + expectStatus("create the section-mode workflow asset", created, 201); + const assetId = stringField( + created.data, + "id", + "section-mode asset response", ); - } - await Bun.sleep(1000); + + const minted = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenant.tenantId}/git-tokens`, + { + name: `cl6324-section-push-${crypto.randomUUID().slice(0, 8)}`, + resource: "asset:*", + refPattern: "**", + actions: ["can_read", "can_push"], + expiresAt: new Date(Date.now() + 600_000).toISOString(), + }, + user.cookies, + ); + expectStatus("mint the section-mode push token", minted, 201); + const tokenSecret = stringField( + minted.data, + "secret", + "git token response", + ); + + const model = proofModelSource; + // The same config object every folded launch renders, with the + // one field that selects the shape flipped to `section`. No + // tool pins and no credential bindings: this proof is about the + // occurrence shape, and an empty pin set keeps the deploy off + // the tool-manifest and MCP-handle surfaces entirely. + const definition = buildAgentRuntimeWorkflow({ + workflowId: "wf_cl6324_section", + agentId: "cl6324-section-agent", + triggerAddress: sectionAddress, + systemPrompt: + "You are a terse assistant. Answer in one short sentence.", + inferencePreferences: [ + { provider: model.provider, model: model.model }, + ], + toolPackagePins: [], + credentialBindings: [], + mode: { kind: "section", turnTimeoutMs: SECTION_TURN_TIMEOUT_MS }, + }); + + const pushed = await pushWorkflow({ + remoteUrl: `${hub.baseUrl}/api/tenants/${tenant.tenantId}/assets/workflow/${SECTION_ASSET_NAME}.git`, + tokenSecret, + workflowJson: JSON.stringify(definition, null, 2), + packageName: SECTION_ASSET_NAME, + }); + + const deployed = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenant.tenantId}/workflows/deployments`, + { + source: { + kind: "asset", + assetId, + package: { format: "source", commitSha: pushed.commitSha }, + }, + entry: WORKFLOW_SOURCE_ENTRY, + sources: [ + { + id: SECTION_SOURCE_ID, + provider: model.provider, + baseURL: model.baseURL, + apiKey: model.apiKey, + model: model.model, + }, + ], + defaultSource: SECTION_SOURCE_ID, + }, + user.cookies, + ); + expectStatus("deploy the section-mode workflow", deployed, 201); + return stringField( + deployed.data, + "id", + "section-mode deployment response", + ); + }, + ), + ); + + /** Occurrence run ids the section has already produced. */ + const seenOccurrences = new Set(); + + const isOccurrenceRunId = (id: string) => /^turn__\d+$/.test(id); + + /** + * Drives one section occurrence: send real mail, then wait for a + * NEW child run to record `RunStarted` in its OWN event log. The + * runtime names an occurrence `__` + * (`agentRuntimeTurnRunId`), and the occurrence is discovered rather + * than assumed so a turn that died in the sidecar kill cannot shift + * every later index and turn a real pass into a false failure. + */ + async function driveSectionOccurrence( + text: string, + label: string, + ): Promise { + const t0 = Date.now(); + // A 409 here means the deployment's address is not routable yet — the + // state a restart leaves behind while the sidecar's reclaim settles. + // Retrying the trigger is the same bounded wait a caller would do. + const triggerDeadline = Date.now() + 60_000; + for (;;) { + const triggered = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenant.tenantId}/workflows/${sectionDeploymentId}/mail`, + { content: text }, + user.cookies, + ); + if (triggered.status === 202) break; + if (triggered.status !== 409 || Date.now() > triggerDeadline) { + expectStatus(`${label}: trigger the section`, triggered, 202); + } + await Bun.sleep(2000); + } + + const deadline = Date.now() + TURN_TIMEOUT_MS; + for (;;) { + if (sidecar.exited()) { + throw new Error( + `${label}: the sidecar exited while the section ran; output:\n${sidecar.output()}`, + ); + } + const runIds = await listDeploymentRunIds(sectionDeploymentId); + for (const turnRunId of runIds) { + if (!isOccurrenceRunId(turnRunId)) continue; + if (seenOccurrences.has(turnRunId)) continue; + const res = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenant.tenantId}/workflows/${sectionDeploymentId}/runs/${turnRunId}/events`, + undefined, + user.cookies, + ); + if (res.status !== 200) continue; + const events = arrayField( + res.data, + "events", + `${label}: section occurrence events`, + ) as { seq: number; type: string }[]; + if (!events.some((e) => e.type === "RunStarted")) continue; + seenOccurrences.add(turnRunId); + timings.push({ label: `${label}: RunStarted`, ms: Date.now() - t0 }); + console.log(` TRANSCRIPT — >>> (section) ${text}`); + console.log( + ` TRANSCRIPT — section occurrence ${turnRunId} events: ` + + JSON.stringify(events.map((e) => `${String(e.seq)}:${e.type}`)), + ); + return turnRunId; + } + if (Date.now() > deadline) { + throw new Error( + `${label}: no new section occurrence recorded RunStarted; ` + + `run ids present: ${JSON.stringify(runIds)}\n` + + `sidecar output:\n${sidecar.output()}`, + ); + } + await Bun.sleep(1000); + } + } + + const firstOccurrence = await timed( + "proof 2b: first section occurrence to RunStarted", + () => + hop( + "PROOF 2b — every message is an onTrigger occurrence with its own child run", + () => + driveSectionOccurrence( + "In one short sentence, what can you help me with?", + "proof 2b", + ), + ), + ); + + await hop( + "PROOF 2b — the first occurrence is the one the runtime's naming predicts", + async () => { + const expected = agentRuntimeTurnRunId(0); + if (firstOccurrence !== expected) { + throw new Error( + `the first section occurrence is ${firstOccurrence}, not the ` + + `${expected} the section's own id derivation predicts`, + ); + } + const parentEvents = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenant.tenantId}/workflows/${sectionDeploymentId}/runs/${sectionDeploymentId}/events`, + undefined, + user.cookies, + ); + expectStatus("read the section's parent run log", parentEvents, 200); + const events = arrayField( + parentEvents.data, + "events", + "section parent events", + ) as { seq: number; type: string; body?: { childRunId?: unknown } }[]; + console.log( + ` TRANSCRIPT — section parent run events: ` + + JSON.stringify(events.map((e) => `${String(e.seq)}:${e.type}`)), + ); + if ( + !events.some( + (e) => e.type === "ChildSpawned" && e.body?.childRunId === expected, + ) + ) { + throw new Error( + `the section's parent run log records no ChildSpawned for ` + + `${expected}: ${JSON.stringify(events)}`, + ); } }, ); @@ -506,17 +947,68 @@ async function main(): Promise { } } - async function sendAndAwaitReply(text: string, label: string): Promise { - const sent = await api( - hub.baseUrl, - "POST", - `/api/tenants/${tenant.tenantId}/chat/workbenches/${chatId}/messages`, - { parts: [{ kind: "text", text }] }, - user.cookies, - ); - expectStatus("send message", sent, 201); + /** + * Sends one message and waits for the agent's answer. + * + * `resendsAllowed` is the number of times the RETRYABLE undelivered + * notice ("send it again") may be answered by actually sending it + * again. It is the product's own instruction to the reader, so + * honouring it is the honest reading of "the next message is + * answered" — but only where a wake is genuinely racing (the + * post-restart send in proof 4). Every other caller passes zero, so a + * notice there is the failure it looks like. The credential notice is + * never retried: resending can never fix it. + */ + async function sendAndAwaitReply( + text: string, + label: string, + resendsAllowed = 0, + ): Promise { const t0 = Date.now(); - const deadline = t0 + TURN_TIMEOUT_MS; + let resendsLeft = resendsAllowed; + for (;;) { + const sent = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenant.tenantId}/chat/workbenches/${chatId}/messages`, + { parts: [{ kind: "text", text }] }, + user.cookies, + ); + expectStatus("send message", sent, 201); + const reply = await awaitFreshReply(label); + console.log(` TRANSCRIPT — >>> ${text}`); + console.log(` TRANSCRIPT — <<< ${reply}`); + const retryable = /didn't get that one/i.test(reply); + if (retryable && resendsLeft > 0) { + resendsLeft -= 1; + console.log( + ` TRANSCRIPT — retryable notice; resending (${String(resendsLeft)} resend(s) left)`, + ); + continue; + } + // Both undelivered notices are agent-authored room messages from + // the agent's own address, so they look exactly like a reply to + // the reader above. Neither is a turn. + if ( + /^\s*$/.test(reply) || + retryable || + /can't reach a model right now/i.test(reply) + ) { + throw new Error( + `${label}: the agent answered with the undelivered notice, not a ` + + `real turn: ${JSON.stringify(reply)}\n` + + `hub output:\n${hub.output()}\n` + + `sidecar output:\n${sidecar.output()}`, + ); + } + timings.push({ label: `${label}: first reply`, ms: Date.now() - t0 }); + return; + } + } + + /** Waits for the next agent-authored message this proof has not seen. */ + async function awaitFreshReply(label: string): Promise { + const deadline = Date.now() + TURN_TIMEOUT_MS; for (;;) { await autoApproveAll(); const fresh = (await listAgentMessages()).filter( @@ -524,18 +1016,7 @@ async function main(): Promise { ); if (fresh.length > 0) { for (const m of fresh) seenIds.add(m.id); - const reply = fresh.map((m) => m.text).join(" "); - timings.push({ label: `${label}: first reply`, ms: Date.now() - t0 }); - console.log(` TRANSCRIPT — >>> ${text}`); - console.log(` TRANSCRIPT — <<< ${reply}`); - if (/^\s*$/.test(reply) || /didn't get that one/i.test(reply)) { - throw new Error( - `${label}: the agent answered with the undelivered notice, not a ` + - `real turn: ${JSON.stringify(reply)}\n` + - `sidecar output:\n${sidecar.output()}`, - ); - } - return; + return fresh.map((m) => m.text).join(" "); } if (Date.now() > deadline) { throw new Error( @@ -554,6 +1035,40 @@ async function main(): Promise { ), ); + // The step shape's per-message bracket, asserted where a real turn has + // definitely happened. `@corbits/insights`' latency tracker opens its + // row on `message.run.started` and commits it on `message.run.ended`, + // so a committed sample IS the agent event reaching the hub — durably, + // over HTTP — which is the honest step-mode analogue of the section + // shape's `RunStarted`. + await hop( + "PROOF 2 (step mode) — the turn's message.run.started/ended bracket is durably recorded", + async () => { + // The latency summary is grant-gated and the seed's grant set does + // not cover it; planting it here keeps this a real read of the real + // route rather than a skipped check. + await plantGrant("insights:*", "read"); + + const deadline = Date.now() + 60_000; + for (;;) { + const brackets = await completedTurnBrackets(); + if (brackets > 0) { + console.log( + ` TRANSCRIPT — completed per-message brackets: ${String(brackets)}`, + ); + return; + } + if (Date.now() > deadline) { + throw new Error( + "a real reply landed but insights recorded zero turn-latency " + + "samples, so no message.run.started/ended pair reached the hub", + ); + } + await Bun.sleep(2000); + } + }, + ); + // ---- proof 4: kill the sidecar mid-turn, restart, keep talking ---- await hop("PROOF 4 — kill the sidecar mid-turn", async () => { const sent = await api( @@ -571,6 +1086,17 @@ async function main(): Promise { user.cookies, ); expectStatus("send the mid-turn message", sent, 201); + // The section deployment takes the same kill mid-occurrence, so the + // restart has to prove `onBodyFailure: "continue"` too: a section + // that retired on the dead body would never answer again. + const sectionSent = await api( + hub.baseUrl, + "POST", + `/api/tenants/${tenant.tenantId}/workflows/${sectionDeploymentId}/mail`, + { content: "Count slowly from one to twenty, one number per line." }, + user.cookies, + ); + expectStatus("send the mid-turn section message", sectionSent, 202); // Long enough that the turn is genuinely in flight — the child has // the mail and inference is running — but well short of a reply. await Bun.sleep(3000); @@ -602,10 +1128,26 @@ async function main(): Promise { undefined, user.cookies, ); - if (res.status === 200) return; + // The room surviving is a hub-only read and says nothing about + // the execution plane. The run's own health does: `liveness` + // is "ok" exactly when the sidecar has re-announced the + // address, which is what boot restore replaying the pin + // produces. Sending before that is sending into a window the + // product itself answers with "send it again". + const health = await api( + hub.baseUrl, + "GET", + `/api/tenants/${tenant.tenantId}/workflows/runs/${agentRunId}/health`, + undefined, + user.cookies, + ); + const liveness = (health.data as { liveness?: unknown }).liveness; + if (res.status === 200 && liveness === "ok") return; if (Date.now() > deadline) { throw new Error( - `the room did not survive the restart: ${JSON.stringify(res.data)}`, + `the room or its run did not come back after the restart ` + + `(messages ${String(res.status)}, liveness ${JSON.stringify(liveness)})\n` + + `sidecar output:\n${sidecar.output()}`, ); } await Bun.sleep(1000); @@ -617,9 +1159,40 @@ async function main(): Promise { // Whatever the killed turn produced (a partial reply, or nothing) is // not the proof; the proof is that the NEXT message is answered. for (const m of await listAgentMessages()) seenIds.add(m.id); + // Same rule for the section: the occurrence that died in the kill may + // already have committed its `RunStarted`, so it is not evidence that + // the section still answers. Only an occurrence started AFTER the + // restore counts. + for (const id of await listDeploymentRunIds(sectionDeploymentId)) { + if (isOccurrenceRunId(id)) seenOccurrences.add(id); + } + + // The section deployment rode the same kill. Boot restore replays its + // pin from the sidecar data dir exactly as it does the folded run's, + // and `onBodyFailure: "continue"` is what keeps the section subscribed + // when the killed occurrence died mid-body: a section that retired on + // that failure would never produce a second occurrence at all. + // + // Asserted BEFORE the step shape's half deliberately: the two shapes + // answer this question differently, and the section's answer must be + // on the record whatever the step shape does. + await timed("proof 4: section occurrence after the restart", () => + hop( + "PROOF 4 — the section survives the restart and runs its next occurrence", + async () => { + const occurrence = await driveSectionOccurrence( + "Are you still there? One sentence.", + "proof 4 (section)", + ); + console.log( + ` TRANSCRIPT — post-restart section occurrence: ${occurrence}`, + ); + }, + ), + ); await hop("PROOF 4 — the next message is answered after the restart", () => - sendAndAwaitReply("Are you still there? One sentence.", "proof 4"), + sendAndAwaitReply("Are you still there? One sentence.", "proof 4", 2), ); console.log("\n=== TIMINGS ===");