From 0638a330702b835250fe720d10761b1aaf442f12 Mon Sep 17 00:00:00 2001 From: Sawyer Date: Tue, 1 Sep 2026 23:21:16 -0700 Subject: [PATCH 1/6] Enforce authorization on routine targets (CL-7354) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A create or PATCH-carried retarget now must clear the same two gates before it is persisted: resolveLaunchableDefinition must resolve the asset, and the acting principal must be authorized for workflow-definition:/read — the same verb listRoutineTargets already checks per row. A denial is a typed 403 alongside the existing 400/404/409 target envelopes, on both the tenant-session and Myra's workflow-run-authenticated routine surfaces. Also routes a pre-existing catch in postRoutineEnabledNotice through reportError, since this change's diff now touches that line and check:report-error requires it. --- packages/routines/src/routes.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/packages/routines/src/routes.ts b/packages/routines/src/routes.ts index 8567d38a4..04bf85276 100644 --- a/packages/routines/src/routes.ts +++ b/packages/routines/src/routes.ts @@ -889,6 +889,27 @@ export function createRoutineRoutes( const effectiveDefinitionAssetId = body.definitionAssetId ?? existing.definitionAssetId; + if ( + body.definitionAssetId !== undefined && + body.definitionAssetId !== existing.definitionAssetId + ) { + const rejection = await rejectUnlaunchableTarget( + deps, + tenant.id, + principal.id, + body.definitionAssetId, + ); + if (rejection !== undefined) { + return c.json( + makeErrorEnvelope({ + code: rejection.code, + userMessage: rejection.userMessage, + }), + rejection.status, + ); + } + } + if ( body.trigger !== undefined && !(await webhookTriggerValid( From 4aaf48a8f369e726a17fe606838bc5801e1a4703 Mon Sep 17 00:00:00 2001 From: Sawyer Date: Tue, 1 Sep 2026 22:44:13 -0700 Subject: [PATCH 2/6] Add tests for workflow source authoring: tree validation, expectedHeadSha, source read, and the authoring tool bundle --- .../src/registry.test.ts | 204 ++++++++++++++++-- .../src/source-tree.test.ts | 118 ++++++++++ .../src/workflow-routes.test.ts | 72 ++++++- .../src/client.test.ts | 160 ++++++++++++++ .../workflow-authoring-tools/src/tool.test.ts | 180 ++++++++++++++++ workflows/assistant/test/definition.test.ts | 1 + 6 files changed, 722 insertions(+), 13 deletions(-) create mode 100644 packages/agent-workflow-authoring/src/source-tree.test.ts create mode 100644 packages/workflow-authoring-tools/src/client.test.ts create mode 100644 packages/workflow-authoring-tools/src/tool.test.ts diff --git a/packages/agent-workflow-authoring/src/registry.test.ts b/packages/agent-workflow-authoring/src/registry.test.ts index 25d299e27..59353fdb6 100644 --- a/packages/agent-workflow-authoring/src/registry.test.ts +++ b/packages/agent-workflow-authoring/src/registry.test.ts @@ -7,12 +7,38 @@ import type { import { AssetServiceError, type AssetService } from "@intx/hub-sessions"; import type { DB } from "@intx/db"; +import { WorkflowAuthorError } from "./errors"; import { createWorkflowAuthorRegistry, - WorkflowAuthorError, type CreateWorkflowAuthorRegistryDeps, + type WorkflowAuthorRepoReads, } from "./registry"; +const MANIFEST = JSON.stringify({ + name: "daily-digest", + version: "0.0.1", + type: "module", + interchange: { workflow: "./workflow.ts" }, +}); + +const ENTRY = "export default {};\n"; + +function sourceTree( + extra: Record = {}, +): Record { + return { "package.json": MANIFEST, "workflow.ts": ENTRY, ...extra }; +} + +function fakeRepoStore( + overrides: Partial = {}, +): WorkflowAuthorRepoReads { + return { + resolveRef: async () => "sha_head", + openCommittedReads: async () => null, + ...overrides, + }; +} + function allowGrant(action: string): GrantRule { return { id: `g_${action}`, @@ -86,7 +112,12 @@ function deps( return { db: fakeDb(undefined), assetService: fakeAssetService(), - grantStore: fakeGrantStore([allowGrant("create"), allowGrant("write")]), + repoStore: fakeRepoStore(), + grantStore: fakeGrantStore([ + allowGrant("create"), + allowGrant("write"), + allowGrant("read"), + ]), conditionRegistry, ...overrides, }; @@ -120,7 +151,7 @@ test("author publishes a workflow codebase as a workflow-kind asset", async () = const registry = createWorkflowAuthorRegistry(deps({ assetService })); const summary = await registry.author(caller, { name: "daily-digest", - files: { "package.json": '{"interchange":{"workflow":"index.ts"}}' }, + files: sourceTree(), }); expect(summary).toEqual({ @@ -143,7 +174,7 @@ test("author rejects a malformed name before ever calling the asset service", as const registry = createWorkflowAuthorRegistry(deps({ assetService })); await expect( - registry.author(caller, { name: "Not Kebab!", files: { "a.ts": "x" } }), + registry.author(caller, { name: "Not Kebab!", files: sourceTree() }), ).rejects.toMatchObject({ reason: "invalid" }); expect(called).toBe(false); }); @@ -161,30 +192,52 @@ test("author refuses when the principal's grants do not include asset:*/create", ); const err = await registry - .author(caller, { name: "daily-digest", files: { "a.ts": "x" } }) + .author(caller, { name: "daily-digest", files: sourceTree() }) .catch((e: unknown) => e); expect(err).toBeInstanceOf(WorkflowAuthorError); expect((err as WorkflowAuthorError).reason).toBe("forbidden"); expect(called).toBe(false); }); -test("author surfaces a rejected codebase (e.g. missing interchange.workflow entry) as an invalid-source error, not a raw throw", async () => { +test("author rejects a tree with no interchange.workflow entry before any asset is created", async () => { + let created = false; + const assetService = fakeAssetService({ + createAsset: async () => { + created = true; + throw new Error("must not be called"); + }, + }); + const registry = createWorkflowAuthorRegistry(deps({ assetService })); + + const err = await registry + .author(caller, { + name: "daily-digest", + files: { "package.json": '{"name":"x","version":"0.0.1"}' }, + }) + .catch((e: unknown) => e); + expect(err).toBeInstanceOf(WorkflowAuthorError); + expect((err as WorkflowAuthorError).reason).toBe("invalid"); + expect((err as Error).message).toMatch(/interchange\.workflow/); + expect(created).toBe(false); +}); + +test("author surfaces a substrate push rejection as an invalid-source error, not a raw throw", async () => { const assetService = fakeAssetService({ populateAsset: async () => { throw new AssetServiceError( "path_violation", - 'package.json must declare a non-empty "interchange.workflow" entry', + "a committed top-level node_modules directory is not allowed", ); }, }); const registry = createWorkflowAuthorRegistry(deps({ assetService })); const err = await registry - .author(caller, { name: "daily-digest", files: { "package.json": "{}" } }) + .author(caller, { name: "daily-digest", files: sourceTree() }) .catch((e: unknown) => e); expect(err).toBeInstanceOf(WorkflowAuthorError); expect((err as WorkflowAuthorError).reason).toBe("invalid"); - expect((err as Error).message).toMatch(/interchange\.workflow/); + expect((err as Error).message).toMatch(/node_modules/); }); test("republish refuses an asset id that does not resolve in the caller's own tenant", async () => { @@ -202,7 +255,7 @@ test("republish refuses an asset id that does not resolve in the caller's own te ); const err = await registry - .republish(caller, "asset_from_another_tenant", { files: { "a.ts": "x" } }) + .republish(caller, "asset_from_another_tenant", { files: sourceTree() }) .catch((e: unknown) => e); expect(err).toBeInstanceOf(WorkflowAuthorError); expect((err as WorkflowAuthorError).reason).toBe("not_found"); @@ -228,7 +281,7 @@ test("republish writes a new commit once the asset resolves in-tenant and the gr ); const summary = await registry.republish(caller, "asset_1", { - files: { "index.ts": "export {};" }, + files: sourceTree(), }); expect(summary).toEqual({ assetId: "asset_1", @@ -263,9 +316,136 @@ test("republish refuses when the grant store has no matching write grant", async ); const err = await registry - .republish(caller, "asset_1", { files: { "index.ts": "x" } }) + .republish(caller, "asset_1", { files: sourceTree() }) .catch((e: unknown) => e); expect(err).toBeInstanceOf(WorkflowAuthorError); expect((err as WorkflowAuthorError).reason).toBe("forbidden"); expect(populateCalled).toBe(false); }); + +const ownRow: AssetRow = { + id: "asset_1", + tenantId: "tenant_1", + kind: "workflow", + name: "daily-digest", +}; + +test("republish with a stale expectedHeadSha is refused as a conflict carrying the current head, and writes nothing", async () => { + let populateCalled = false; + const registry = createWorkflowAuthorRegistry( + deps({ + db: fakeDb(ownRow), + assetService: fakeAssetService({ + populateAsset: async () => { + populateCalled = true; + return { commitSha: "sha_new" }; + }, + }), + repoStore: fakeRepoStore({ resolveRef: async () => "sha_current" }), + }), + ); + + const err = await registry + .republish(caller, "asset_1", { + files: sourceTree(), + expectedHeadSha: "sha_stale", + }) + .catch((e: unknown) => e); + expect(err).toBeInstanceOf(WorkflowAuthorError); + expect((err as WorkflowAuthorError).reason).toBe("conflict"); + expect((err as WorkflowAuthorError).currentHeadSha).toBe("sha_current"); + expect(populateCalled).toBe(false); +}); + +test("republish with a matching expectedHeadSha proceeds", async () => { + const registry = createWorkflowAuthorRegistry( + deps({ + db: fakeDb(ownRow), + repoStore: fakeRepoStore({ resolveRef: async () => "sha_current" }), + }), + ); + const summary = await registry.republish(caller, "asset_1", { + files: sourceTree(), + expectedHeadSha: "sha_current", + }); + expect(summary.commitSha).toBe("sha_1"); +}); + +test("republish rejects a traversal path before the grant check or any write", async () => { + let authorized = false; + const registry = createWorkflowAuthorRegistry( + deps({ + db: fakeDb(ownRow), + grantStore: { + collectGrants: async () => { + authorized = true; + return [allowGrant("write")]; + }, + collectGrantsInChain: async () => [allowGrant("write")], + }, + }), + ); + const err = await registry + .republish(caller, "asset_1", { + files: sourceTree({ "../escape.ts": "x" }), + }) + .catch((e: unknown) => e); + expect((err as WorkflowAuthorError).reason).toBe("invalid"); + expect(authorized).toBe(false); +}); + +test("readSource walks the whole committed tree, including subdirectories, and reports the head sha", async () => { + const blobs: Record = { + oid_pkg: MANIFEST, + oid_entry: ENTRY, + oid_helper: "export const x = 1;\n", + }; + const registry = createWorkflowAuthorRegistry( + deps({ + db: fakeDb(ownRow), + repoStore: fakeRepoStore({ + resolveRef: async () => "sha_head", + openCommittedReads: async () => ({ + listDir: async (dir) => + dir === "" + ? [ + { name: "package.json", oid: "oid_pkg", type: "blob" }, + { name: "workflow.ts", oid: "oid_entry", type: "blob" }, + { name: "lib", oid: "oid_lib", type: "tree" }, + ] + : dir === "lib" + ? [{ name: "helper.ts", oid: "oid_helper", type: "blob" }] + : [], + readBlobByOid: async (oid) => + new TextEncoder().encode(blobs[oid] ?? ""), + treeOid: async () => null, + }), + }), + }), + ); + + const snapshot = await registry.readSource(caller, "asset_1"); + expect(snapshot).toEqual({ + assetId: "asset_1", + name: "daily-digest", + headSha: "sha_head", + files: { + "package.json": MANIFEST, + "workflow.ts": ENTRY, + "lib/helper.ts": "export const x = 1;\n", + }, + }); +}); + +test("readSource refuses without an asset read grant", async () => { + const registry = createWorkflowAuthorRegistry( + deps({ + db: fakeDb(ownRow), + grantStore: fakeGrantStore([allowGrant("write")]), + }), + ); + const err = await registry + .readSource(caller, "asset_1") + .catch((e: unknown) => e); + expect((err as WorkflowAuthorError).reason).toBe("forbidden"); +}); diff --git a/packages/agent-workflow-authoring/src/source-tree.test.ts b/packages/agent-workflow-authoring/src/source-tree.test.ts new file mode 100644 index 000000000..e0a79498c --- /dev/null +++ b/packages/agent-workflow-authoring/src/source-tree.test.ts @@ -0,0 +1,118 @@ +import { expect, test } from "bun:test"; + +import { WorkflowAuthorError } from "./errors"; +import { + MAX_SOURCE_FILE_BYTES, + MAX_SOURCE_TREE_BYTES, + validateWorkflowSourceTree, +} from "./source-tree"; + +const MANIFEST = JSON.stringify({ + name: "daily-digest", + version: "0.0.1", + type: "module", + interchange: { workflow: "./workflow.ts" }, +}); + +const ENTRY = + 'import { defineWorkflow } from "@intx/workflow";\nexport default defineWorkflow({});\n'; + +function validTree(): Record { + return { "package.json": MANIFEST, "workflow.ts": ENTRY }; +} + +function rejection(files: Record): WorkflowAuthorError { + try { + validateWorkflowSourceTree(files); + } catch (err) { + if (err instanceof WorkflowAuthorError) return err; + throw err; + } + throw new Error("expected validateWorkflowSourceTree to reject"); +} + +test("accepts a minimal package and resolves the normalized entry", () => { + const result = validateWorkflowSourceTree(validTree()); + expect(result.entry).toBe("workflow.ts"); +}); + +test.each([ + ["../escape.ts", /\.\./], + ["src/../../escape.ts", /\.\./], + ["/abs.ts", /repo-relative/], + ["src\\win.ts", /separators/], + [".git/config", /\.git/], + ["nested/.git/HEAD", /\.git/], + ["", /empty/], + ["src//double.ts", /empty segment/], + ["trailing/", /empty segment/], +])("rejects the path %p", (path, message) => { + const err = rejection({ ...validTree(), [path]: "x" }); + expect(err.reason).toBe("invalid"); + expect(err.message).toMatch(message); +}); + +test.each([ + ".env", + ".env.local", + "config/.env.production", + "certs/server.pem", + "keys/private.key", + "id_rsa", + ".ssh/id_rsa.pub", + "bundle.p12", +])("rejects the secret-like file %p", (path) => { + const err = rejection({ ...validTree(), [path]: "shh" }); + expect(err.message).toMatch(/looks like a secret/); +}); + +test("rejects a tree without package.json", () => { + expect(rejection({ "workflow.ts": ENTRY }).message).toMatch(/package\.json/); +}); + +test("rejects a package.json that does not parse", () => { + const err = rejection({ ...validTree(), "package.json": "{ nope" }); + expect(err.message).toMatch(/not valid JSON/); +}); + +test("rejects a package.json with no interchange.workflow entry", () => { + const err = rejection({ + ...validTree(), + "package.json": JSON.stringify({ name: "x", version: "0.0.1" }), + }); + expect(err.message).toMatch(/interchange\.workflow/); +}); + +test("rejects an entry that escapes the package", () => { + const err = rejection({ + ...validTree(), + "package.json": JSON.stringify({ + name: "x", + version: "0.0.1", + interchange: { workflow: "../outside.ts" }, + }), + }); + expect(err.message).toMatch(/escape/); +}); + +test("rejects an entry the tree does not carry", () => { + const err = rejection({ "package.json": MANIFEST, "other.ts": ENTRY }); + expect(err.message).toMatch(/no file at "workflow\.ts"/); +}); + +test("rejects a single file over the per-file cap", () => { + const err = rejection({ + ...validTree(), + "big.ts": "x".repeat(MAX_SOURCE_FILE_BYTES + 1), + }); + expect(err.message).toMatch(/per-file limit/); +}); + +test("rejects a tree whose total exceeds the tree cap even when every file is under the per-file cap", () => { + const files = validTree(); + const chunk = "x".repeat(MAX_SOURCE_FILE_BYTES); + for (let i = 0; i * MAX_SOURCE_FILE_BYTES <= MAX_SOURCE_TREE_BYTES; i++) { + files[`chunk-${i}.ts`] = chunk; + } + expect(rejection(files).message).toMatch(/source tree totals/); +}); diff --git a/packages/agent-workflow-authoring/src/workflow-routes.test.ts b/packages/agent-workflow-authoring/src/workflow-routes.test.ts index 0454d8a64..030125608 100644 --- a/packages/agent-workflow-authoring/src/workflow-routes.test.ts +++ b/packages/agent-workflow-authoring/src/workflow-routes.test.ts @@ -5,7 +5,8 @@ import { type WorkflowRunAuthenticator, type WorkflowRunScope, } from "./workflow-routes"; -import { WorkflowAuthorError, type WorkflowAuthorRegistry } from "./registry"; +import { WorkflowAuthorError } from "./errors"; +import type { WorkflowAuthorRegistry } from "./registry"; function fakeAuthenticator( scope: WorkflowRunScope | null, @@ -23,6 +24,9 @@ function fakeRegistry( republish: async () => { throw new Error("republish not stubbed"); }, + readSource: async () => { + throw new Error("readSource not stubbed"); + }, ...overrides, }; } @@ -147,3 +151,69 @@ test("a malformed request body is rejected 400 before the registry ever runs", a expect(res.status).toBe(400); expect(called).toBe(false); }); + +test("republish forwards expectedHeadSha and a conflict comes back 409 naming the current head", async () => { + let seenExpected: string | undefined; + const app = createWorkflowAuthorRoutes({ + authenticator: fakeAuthenticator({ + tenantId: "tenant_1", + principalId: "principal_1", + }), + registry: fakeRegistry({ + republish: async (_caller, _assetId, input) => { + seenExpected = input.expectedHeadSha; + throw new WorkflowAuthorError("conflict", "asset moved", { + currentHeadSha: "sha_current", + }); + }, + }), + }); + const res = await app.request( + req("/republish", { + assetId: "asset_1", + files: { "package.json": "{}" }, + expectedHeadSha: "sha_stale", + }), + ); + expect(res.status).toBe(409); + expect(seenExpected).toBe("sha_stale"); + const body = (await res.json()) as { + error: { code: string }; + currentHeadSha: string; + }; + expect(body.error.code).toBe("conflict"); + expect(body.currentHeadSha).toBe("sha_current"); +}); + +test("GET /:assetId/source returns the registry's snapshot for the authenticated scope", async () => { + let seen: { tenantId: string; assetId: string } | undefined; + const app = createWorkflowAuthorRoutes({ + authenticator: fakeAuthenticator({ + tenantId: "tenant_1", + principalId: "principal_1", + }), + registry: fakeRegistry({ + readSource: async (caller, assetId) => { + seen = { tenantId: caller.tenantId, assetId }; + return { + assetId, + name: "daily-digest", + headSha: "sha_head", + files: { "package.json": "{}" }, + }; + }, + }), + }); + const res = await app.request( + new Request("https://hub.example.com/asset_1/source", { + headers: { + authorization: "Bearer sc-token", + "x-workflow-run-address": "run_1@workflow", + }, + }), + ); + expect(res.status).toBe(200); + expect(seen).toEqual({ tenantId: "tenant_1", assetId: "asset_1" }); + const body = (await res.json()) as { data: { headSha: string } }; + expect(body.data.headSha).toBe("sha_head"); +}); diff --git a/packages/workflow-authoring-tools/src/client.test.ts b/packages/workflow-authoring-tools/src/client.test.ts new file mode 100644 index 000000000..fae392730 --- /dev/null +++ b/packages/workflow-authoring-tools/src/client.test.ts @@ -0,0 +1,160 @@ +import { expect, test } from "bun:test"; + +import { + authorWorkflow, + readWorkflowSource, + republishWorkflow, + WorkflowAuthoringRequestError, + type WorkflowAuthoringClientConfig, +} from "./client"; + +type Seen = { url: string; init: RequestInit | undefined }; + +function capture(respond: () => Response): { + config: WorkflowAuthoringClientConfig; + seen: Seen[]; +} { + const seen: Seen[] = []; + const fetchImpl = (async (url: string | URL, init?: RequestInit) => { + seen.push({ url: String(url), init }); + return respond(); + }) as unknown as typeof fetch; + return { + config: { + hubWorkflowAuthoringUrl: "https://hub.example.com", + sidecarToken: "sc-token", + address: "run_1@workflow", + fetchImpl, + }, + seen, + }; +} + +const FILES = { "package.json": "{}", "workflow.ts": "export default {};" }; + +test("authorWorkflow posts the tree to /author with the run's bearer token and address", async () => { + const { config, seen } = capture( + () => + new Response( + JSON.stringify({ + data: { + assetId: "asset_1", + name: "daily-digest", + commitSha: "sha_1", + }, + }), + { status: 201 }, + ), + ); + const summary = await authorWorkflow(config, { + name: "daily-digest", + files: FILES, + }); + expect(summary).toEqual({ + assetId: "asset_1", + name: "daily-digest", + commitSha: "sha_1", + }); + const [request] = seen; + expect(request?.url).toBe( + "https://hub.example.com/api/workflow-workflow-authoring/author", + ); + const headers = request?.init?.headers as Record; + expect(headers["authorization"]).toBe("Bearer sc-token"); + expect(headers["x-workflow-run-address"]).toBe("run_1@workflow"); + expect(JSON.parse(String(request?.init?.body))).toEqual({ + name: "daily-digest", + files: FILES, + }); +}); + +test("republishWorkflow forwards expectedHeadSha and surfaces a 409 with the current head", async () => { + const { config, seen } = capture( + () => + new Response( + JSON.stringify({ + error: { + code: "conflict", + userMessage: "asset moved", + refId: "ref_1", + }, + currentHeadSha: "sha_current", + }), + { status: 409 }, + ), + ); + const err = await republishWorkflow(config, { + assetId: "asset_1", + files: FILES, + expectedHeadSha: "sha_stale", + }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(WorkflowAuthoringRequestError); + expect((err as WorkflowAuthoringRequestError).code).toBe("conflict"); + expect((err as WorkflowAuthoringRequestError).currentHeadSha).toBe( + "sha_current", + ); + expect(JSON.parse(String(seen[0]?.init?.body))).toMatchObject({ + expectedHeadSha: "sha_stale", + }); +}); + +test("readWorkflowSource GETs /:assetId/source and returns the snapshot", async () => { + const { config, seen } = capture( + () => + new Response( + JSON.stringify({ + data: { + assetId: "asset_1", + name: "daily-digest", + headSha: "sha_head", + files: FILES, + }, + }), + ), + ); + const snapshot = await readWorkflowSource(config, "asset_1"); + expect(snapshot.headSha).toBe("sha_head"); + expect(snapshot.files).toEqual(FILES); + expect(seen[0]?.url).toBe( + "https://hub.example.com/api/workflow-workflow-authoring/asset_1/source", + ); + expect(seen[0]?.init?.method).toBeUndefined(); +}); + +test("a hub rejection with an error envelope becomes a WorkflowAuthoringRequestError carrying the hub's message", async () => { + const { config } = capture( + () => + new Response( + JSON.stringify({ + error: { + code: "invalid", + userMessage: 'file "../x" may not contain a ".." segment', + refId: "ref_1", + }, + }), + { status: 400 }, + ), + ); + const err = await authorWorkflow(config, { + name: "x", + files: { "../x": "" }, + }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(WorkflowAuthoringRequestError); + expect((err as Error).message).toMatch(/"\.\." segment/); +}); + +test("a non-envelope failure is an honest error naming the status, never a fabricated result", async () => { + const { config } = capture( + () => new Response("", { status: 502, statusText: "Bad Gateway" }), + ); + await expect(readWorkflowSource(config, "asset_1")).rejects.toThrow(/502/); +}); + +test("a success body of the wrong shape is rejected", async () => { + const { config } = capture( + () => new Response(JSON.stringify({ nonsense: true })), + ); + await expect( + authorWorkflow(config, { name: "x", files: FILES }), + ).rejects.toThrow(/expected shape/); +}); diff --git a/packages/workflow-authoring-tools/src/tool.test.ts b/packages/workflow-authoring-tools/src/tool.test.ts new file mode 100644 index 000000000..268dae8c4 --- /dev/null +++ b/packages/workflow-authoring-tools/src/tool.test.ts @@ -0,0 +1,180 @@ +import { expect, test } from "bun:test"; +import type { ToolCall } from "@intx/types/runtime"; + +import { + workflowAuthoringTools, + WORKFLOW_AUTHOR_TOOL, + WORKFLOW_REPUBLISH_TOOL, + WORKFLOW_SOURCE_READ_TOOL, + type WorkflowAuthoringEnv, +} from "./tool"; + +function testEnv(): WorkflowAuthoringEnv { + return { + hubWorkflowAuthoringUrl: "https://hub.example.com", + sidecarToken: "sc-token", + address: "run_1@workflow", + } as unknown as WorkflowAuthoringEnv; +} + +function call(name: string, args: Record): ToolCall { + return { id: "call_1", name, arguments: args }; +} + +async function withFetch( + impl: (url: string, init?: RequestInit) => Response, + body: () => Promise, +): Promise { + const original = globalThis.fetch; + globalThis.fetch = (async (url: string | URL, init?: RequestInit) => + impl(String(url), init)) as unknown as typeof fetch; + try { + return await body(); + } finally { + globalThis.fetch = original; + } +} + +test("declares the three authoring tools with no approval gate — writing source is not a side effect", () => { + expect(workflowAuthoringTools.definitions).toEqual([ + { name: WORKFLOW_AUTHOR_TOOL }, + { name: WORKFLOW_REPUBLISH_TOOL }, + { name: WORKFLOW_SOURCE_READ_TOOL }, + ]); + expect(workflowAuthoringTools.requires).toEqual([ + "hubWorkflowAuthoringUrl", + "sidecarToken", + "address", + ]); +}); + +test("every description tells the model the package shape and that deploy is a separate step", () => { + const bundle = workflowAuthoringTools(testEnv()); + const byName = new Map( + bundle.definitions.map((definition) => [ + definition.name, + (definition as unknown as { description: string }).description, + ]), + ); + for (const name of [WORKFLOW_AUTHOR_TOOL, WORKFLOW_REPUBLISH_TOOL]) { + const description = byName.get(name) ?? ""; + expect(description).toContain('"interchange": { "workflow"'); + expect(description).toContain("defineWorkflow"); + expect(description).toContain("@intx/workflow"); + expect(description).toMatch(/separate/); + } +}); + +test("workflow_author rejects a call missing files without calling the hub", async () => { + const bundle = workflowAuthoringTools(testEnv()); + await withFetch( + () => { + throw new Error("must not be called"); + }, + async () => { + await expect( + bundle.run( + call(WORKFLOW_AUTHOR_TOOL, { name: "daily-digest" }), + new AbortController().signal, + ), + ).rejects.toThrow(/invalid input/); + }, + ); +}); + +test("workflow_author posts to the authoring route and reports asset id and commit", async () => { + const bundle = workflowAuthoringTools(testEnv()); + let seenUrl: string | undefined; + const result = await withFetch( + (url) => { + seenUrl = url; + return new Response( + JSON.stringify({ + data: { + assetId: "asset_1", + name: "daily-digest", + commitSha: "sha_1", + }, + }), + { status: 201 }, + ); + }, + () => + bundle.run( + call(WORKFLOW_AUTHOR_TOOL, { + name: "daily-digest", + files: { "package.json": "{}", "workflow.ts": "" }, + }), + new AbortController().signal, + ), + ); + expect(seenUrl).toBe( + "https://hub.example.com/api/workflow-workflow-authoring/author", + ); + expect(result.isError).toBe(false); + expect(result.content).toContain("asset_1"); + expect(result.content).toContain("sha_1"); + expect(result.content).toMatch(/until deployed/); +}); + +test("workflow_republish surfaces a head conflict with the current sha in the thrown message", async () => { + const bundle = workflowAuthoringTools(testEnv()); + await withFetch( + () => + new Response( + JSON.stringify({ + error: { + code: "conflict", + userMessage: + "workflow asset asset_1 moved: expected head sha_stale but refs/heads/main is at sha_current", + refId: "ref_1", + }, + currentHeadSha: "sha_current", + }), + { status: 409 }, + ), + async () => { + await expect( + bundle.run( + call(WORKFLOW_REPUBLISH_TOOL, { + assetId: "asset_1", + files: { "workflow.ts": "" }, + expectedHeadSha: "sha_stale", + }), + new AbortController().signal, + ), + ).rejects.toThrow(/sha_current/); + }, + ); +}); + +test("workflow_source_read returns the snapshot as JSON the model can parse", async () => { + const bundle = workflowAuthoringTools(testEnv()); + const snapshot = { + assetId: "asset_1", + name: "daily-digest", + headSha: "sha_head", + files: { "package.json": "{}" }, + }; + const result = await withFetch( + (url) => { + expect(url).toBe( + "https://hub.example.com/api/workflow-workflow-authoring/asset_1/source", + ); + return new Response(JSON.stringify({ data: snapshot })); + }, + () => + bundle.run( + call(WORKFLOW_SOURCE_READ_TOOL, { assetId: "asset_1" }), + new AbortController().signal, + ), + ); + expect(JSON.parse(String(result.content))).toEqual(snapshot); +}); + +test("an unknown tool name rejects loudly, never a silent no-op", async () => { + const bundle = workflowAuthoringTools(testEnv()); + await expect( + bundle.run(call("delete_everything", {}), new AbortController().signal), + ).rejects.toThrow(/unknown tool/); +}); diff --git a/workflows/assistant/test/definition.test.ts b/workflows/assistant/test/definition.test.ts index 6a728793c..e177d57ce 100644 --- a/workflows/assistant/test/definition.test.ts +++ b/workflows/assistant/test/definition.test.ts @@ -126,6 +126,7 @@ test("the agent pins memory, capability, and the manager-tools bundles at the ve "@corbits/mcp-tools", "@corbits/interaction-tools", "@corbits/manus-tools", + "@corbits/workflow-authoring-tools", ]); // A pin the registry cannot resolve fails every assistant deploy, so // each one must name a version the workspace actually publishes. From 2622d15d30c0bac0e0906f8e469a4bb2e03c0a6c Mon Sep 17 00:00:00 2001 From: Sawyer Date: Tue, 1 Sep 2026 22:44:13 -0700 Subject: [PATCH 3/6] Let an agent author a workflow code package into a hub asset (CL-7360) agent-workflow-authoring: validate the source tree at the trust boundary (repo-relative paths, no secret-like names, package.json with an interchange.workflow entry the tree carries, size caps), honor an optional expectedHeadSha on republish (409 with the current head), and add GET /:assetId/source authorized as asset:/read. workflow-authoring-tools: a new @intx/agent bundle (workflow_author, workflow_republish, workflow_source_read) over those run-authenticated routes, published to the corbits-tools registry, pinned by the assistant, threaded hubWorkflowAuthoringUrl in the sidecar step env, and offered in the hub's tool-package inventory. --- apps/hub/src/index.ts | 9 + .../workflow-substrate-factory/step-env.ts | 5 + bun.lock | 17 +- .../agent-workflow-authoring/src/errors.ts | 22 ++ .../agent-workflow-authoring/src/index.ts | 12 +- .../agent-workflow-authoring/src/registry.ts | 214 ++++++++++----- .../src/source-tree.ts | 161 +++++++++++ .../src/workflow-routes.ts | 28 +- .../tool-registry-publish/src/registry.ts | 1 + packages/workflow-authoring-tools/LICENSE | 176 ++++++++++++ packages/workflow-authoring-tools/README.md | 66 +++++ .../workflow-authoring-tools/package.json | 24 ++ .../workflow-authoring-tools/src/client.ts | 188 +++++++++++++ .../workflow-authoring-tools/src/index.ts | 19 ++ packages/workflow-authoring-tools/src/tool.ts | 256 ++++++++++++++++++ .../workflow-authoring-tools/tsconfig.json | 22 ++ .../tsconfig.src.json | 20 ++ tsconfig.build.json | 3 + workflows/assistant/src/index.ts | 1 + 19 files changed, 1172 insertions(+), 72 deletions(-) create mode 100644 packages/agent-workflow-authoring/src/errors.ts create mode 100644 packages/agent-workflow-authoring/src/source-tree.ts create mode 100644 packages/workflow-authoring-tools/LICENSE create mode 100644 packages/workflow-authoring-tools/README.md create mode 100644 packages/workflow-authoring-tools/package.json create mode 100644 packages/workflow-authoring-tools/src/client.ts create mode 100644 packages/workflow-authoring-tools/src/index.ts create mode 100644 packages/workflow-authoring-tools/src/tool.ts create mode 100644 packages/workflow-authoring-tools/tsconfig.json create mode 100644 packages/workflow-authoring-tools/tsconfig.src.json diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index ad24db67e..4cccdd652 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -1875,6 +1875,7 @@ export async function createHub(config: HubConfig) { registry: createWorkflowAuthorRegistry({ db, assetService, + repoStore: agentRepoStore.repoStore, grantStore: chatGrantStore, conditionRegistry: chatConditionRegistry, }), @@ -3104,6 +3105,14 @@ export async function createHub(config: HubConfig) { connectorId: "interaction", credentialBinding: null, }); + // Workflow-source authoring needs no credential either: every write is + // authorized against the run's own asset grants by + // `/api/workflow-workflow-authoring` (mounted above). + entries.push({ + name: "@corbits/workflow-authoring-tools", + connectorId: "workflow-authoring", + credentialBinding: null, + }); return entries; } diff --git a/apps/sidecar/src/workflow-substrate-factory/step-env.ts b/apps/sidecar/src/workflow-substrate-factory/step-env.ts index 138a0a217..591f1ef66 100644 --- a/apps/sidecar/src/workflow-substrate-factory/step-env.ts +++ b/apps/sidecar/src/workflow-substrate-factory/step-env.ts @@ -367,6 +367,7 @@ export function createSidecarStepBuildEnv( hubCatalogUrl: string; hubAgentDirectoryUrl: string; hubChatUrl: string; + hubWorkflowAuthoringUrl: string; sidecarToken: string; definitionId: string; } = { @@ -421,6 +422,10 @@ export function createSidecarStepBuildEnv( hubCatalogUrl: deps.hubArtifactsUrl, hubAgentDirectoryUrl: deps.hubArtifactsUrl, hubChatUrl: deps.hubArtifactsUrl, + // And under the key `@corbits/workflow-authoring-tools` declares + // (`requires: ["hubWorkflowAuthoringUrl", "sidecarToken", "address"]`) + // for `@corbits/agent-workflow-authoring`'s run-authenticated routes. + hubWorkflowAuthoringUrl: deps.hubArtifactsUrl, sidecarToken: deps.sidecarToken, definitionId: deps.definitionId, }; diff --git a/bun.lock b/bun.lock index 91f5b39fe..e533133e2 100644 --- a/bun.lock +++ b/bun.lock @@ -1237,7 +1237,7 @@ }, "packages/routines-tools": { "name": "@corbits/routines-tools", - "version": "0.0.7", + "version": "0.0.8", "dependencies": { "@corbits/routines": "workspace:*", "@intx/agent": "workspace:*", @@ -1525,6 +1525,19 @@ "typescript": "catalog:", }, }, + "packages/workflow-authoring-tools": { + "name": "@corbits/workflow-authoring-tools", + "version": "0.0.1", + "dependencies": { + "@intx/agent": "workspace:*", + "@intx/types": "workspace:*", + "arktype": "catalog:", + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:", + }, + }, "packages/workflow-catalog": { "name": "@corbits/workflow-catalog", "version": "0.0.1", @@ -2363,6 +2376,8 @@ "@corbits/workbench-digest-workflow": ["@corbits/workbench-digest-workflow@workspace:workflows/workbench-digest"], + "@corbits/workflow-authoring-tools": ["@corbits/workflow-authoring-tools@workspace:packages/workflow-authoring-tools"], + "@corbits/workflow-catalog": ["@corbits/workflow-catalog@workspace:packages/workflow-catalog"], "@corbits/workflow-deploy-source": ["@corbits/workflow-deploy-source@workspace:packages/workflow-deploy-source"], diff --git a/packages/agent-workflow-authoring/src/errors.ts b/packages/agent-workflow-authoring/src/errors.ts new file mode 100644 index 000000000..216a48385 --- /dev/null +++ b/packages/agent-workflow-authoring/src/errors.ts @@ -0,0 +1,22 @@ +export type WorkflowAuthorErrorReason = + "forbidden" | "not_found" | "conflict" | "invalid"; + +export class WorkflowAuthorError extends Error { + readonly reason: WorkflowAuthorErrorReason; + /** Set on a `conflict` raised by an `expectedHeadSha` mismatch: the sha + * `refs/heads/main` actually points at, so the caller can re-read and + * retry against it. */ + readonly currentHeadSha?: string; + constructor( + reason: WorkflowAuthorErrorReason, + message: string, + options: { readonly currentHeadSha?: string } = {}, + ) { + super(message); + this.name = "WorkflowAuthorError"; + this.reason = reason; + if (options.currentHeadSha !== undefined) { + this.currentHeadSha = options.currentHeadSha; + } + } +} diff --git a/packages/agent-workflow-authoring/src/index.ts b/packages/agent-workflow-authoring/src/index.ts index 6402ada69..b9fb735ff 100644 --- a/packages/agent-workflow-authoring/src/index.ts +++ b/packages/agent-workflow-authoring/src/index.ts @@ -1,15 +1,23 @@ +export { WorkflowAuthorError, type WorkflowAuthorErrorReason } from "./errors"; export { createWorkflowAuthorRegistry, - WorkflowAuthorError, WORKFLOW_ASSET_NAME_PATTERN, type AuthorWorkflowInput, type CreateWorkflowAuthorRegistryDeps, type RepublishWorkflowInput, type WorkflowAssetSummary, type WorkflowAuthorCaller, - type WorkflowAuthorErrorReason, type WorkflowAuthorRegistry, + type WorkflowAuthorRepoReads, + type WorkflowSourceSnapshot, } from "./registry"; +export { + MAX_SOURCE_FILE_BYTES, + MAX_SOURCE_FILE_COUNT, + MAX_SOURCE_TREE_BYTES, + validateWorkflowSourceTree, + type ValidatedWorkflowSourceTree, +} from "./source-tree"; export { createWorkflowAuthorRoutes, type CreateWorkflowAuthorRoutesDeps, diff --git a/packages/agent-workflow-authoring/src/registry.ts b/packages/agent-workflow-authoring/src/registry.ts index 0a7c32553..3eac4451b 100644 --- a/packages/agent-workflow-authoring/src/registry.ts +++ b/packages/agent-workflow-authoring/src/registry.ts @@ -1,15 +1,17 @@ // The workflow-authoring registry: an agent's in-tenant surface for -// publishing a workflow codebase as a native `kind:"workflow"` hub asset -// and republishing it. Every write is gated by two independent checks — -// own-tenant scoping (resolved from the DB row, mirroring -// `@corbits/skills`' `requireOwnTenant`) and an explicit grant-store -// authorization call (`asset:*`/create for a new asset, `asset:`/write -// for a republish) — before anything reaches `RepoStore`. Deploying an -// authored asset is deliberately NOT this package's job: deploy stays on -// `@intx/hub-api`'s existing source-based `POST .../workflows/deployments` -// route (`WorkflowDefinitionSource` + `entry`), which already installs, -// probes, gates, and freezes the definition. Building a second deploy path -// here would duplicate that gating, not strengthen it. +// publishing a workflow codebase as a native `kind:"workflow"` hub asset, +// republishing it, and reading it back. Every write is gated by two +// independent checks — own-tenant scoping (resolved from the DB row, +// mirroring `@corbits/skills`' `requireOwnTenant`) and an explicit +// grant-store authorization call (`asset:*`/create for a new asset, +// `asset:`/write for a republish, `asset:`/read for a source read) +// — and by `validateWorkflowSourceTree` before anything reaches +// `RepoStore`. Deploying an authored asset is deliberately NOT this +// package's job: deploy stays on `@intx/hub-api`'s existing source-based +// `POST .../workflows/deployments` route (`WorkflowDefinitionSource` + +// `entry`), which already installs, probes, gates, and freezes the +// definition. Building a second deploy path here would duplicate that +// gating, not strengthen it. // // `populateAsset` is called with `principal: { kind: "hub" }`, the same // principal `@corbits/skills`' `writeSkillMd` uses. This is deliberate, @@ -21,20 +23,33 @@ // no fourth "workflow-run" principal kind the substrate understands, so a // real per-write authorization decision has to be made HERE, by this // registry, against the grant store and the resolved caller identity — -// exactly what the two checks below do — before the already-authorized -// write is handed to the substrate as a hub-mediated commit. +// exactly what the checks below do — before the already-authorized write +// is handed to the substrate as a hub-mediated commit. +// +// Head-sha reads (`expectedHeadSha`, `readSource`) go through `RepoStore` +// directly: `AssetService` exposes blob and directory reads pinned to a +// ref but never the sha that ref resolves to, and `listAssetBlobs` lists +// blobs only (no subtrees), so a full tree walk needs +// `RepoStore.openCommittedReads`. The repo id is the asset id under the +// `workflow` kind, exactly as `AssetService` composes it internally. import { authorize } from "@intx/authz"; import type { ConditionRegistry, GrantStore } from "@intx/types/authz"; import { AssetServiceError, DEFAULT_ASSET_REF, type AssetService, + type CommittedReads, + type RepoStore, } from "@intx/hub-sessions"; import type { DB } from "@intx/db"; import { asset as assetTable } from "@intx/db/schema"; import { and, eq } from "drizzle-orm"; +import { WorkflowAuthorError } from "./errors"; +import { validateWorkflowSourceTree } from "./source-tree"; + const WORKFLOW_ASSET_KIND = "workflow"; +const HUB_PRINCIPAL = { kind: "hub" } as const; export const WORKFLOW_ASSET_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; @@ -49,25 +64,19 @@ export type WorkflowAssetSummary = { readonly commitSha: string; }; -export type WorkflowAuthorErrorReason = - "forbidden" | "not_found" | "conflict" | "invalid"; - -export class WorkflowAuthorError extends Error { - readonly reason: WorkflowAuthorErrorReason; - constructor(reason: WorkflowAuthorErrorReason, message: string) { - super(message); - this.name = "WorkflowAuthorError"; - this.reason = reason; - } -} +export type WorkflowSourceSnapshot = { + readonly assetId: string; + readonly name: string; + readonly headSha: string; + /** Repo-relative path -> UTF-8 file contents, every blob on the head + * commit of `refs/heads/main`. */ + readonly files: Readonly>; +}; export type AuthorWorkflowInput = { readonly name: string; - /** Repo-relative path -> file contents. Must include a `package.json` - * declaring a non-empty `interchange.workflow` entry; the substrate's - * `workflowKindHandler.validatePush` rejects anything else, and that - * rejection surfaces here as a `WorkflowAuthorError("invalid", ...)`, - * never a 500. */ + /** Repo-relative path -> file contents; see `validateWorkflowSourceTree` + * for the rules a tree must satisfy before it is written. */ readonly files: Record; readonly message?: string; }; @@ -75,6 +84,9 @@ export type AuthorWorkflowInput = { export type RepublishWorkflowInput = { readonly files: Record; readonly message?: string; + /** When set, the write is refused with `conflict` (carrying the current + * head) unless `refs/heads/main` still points here. */ + readonly expectedHeadSha?: string; }; export type WorkflowAuthorRegistry = { @@ -87,11 +99,21 @@ export type WorkflowAuthorRegistry = { assetId: string, input: RepublishWorkflowInput, ): Promise; + readSource( + caller: WorkflowAuthorCaller, + assetId: string, + ): Promise; }; +export type WorkflowAuthorRepoReads = Pick< + RepoStore, + "resolveRef" | "openCommittedReads" +>; + export type CreateWorkflowAuthorRegistryDeps = { db: DB["db"]; assetService: AssetService; + repoStore: WorkflowAuthorRepoReads; grantStore: GrantStore; conditionRegistry: ConditionRegistry; }; @@ -103,7 +125,7 @@ async function requireAuthorized( >, caller: WorkflowAuthorCaller, resource: string, - action: "create" | "write", + action: "create" | "write" | "read", ): Promise { const verdict = await authorize( deps.grantStore, @@ -131,7 +153,11 @@ async function writeCodebase( return await assetService.populateAsset({ assetId, ref: DEFAULT_ASSET_REF, - principal: { kind: "hub" }, + principal: HUB_PRINCIPAL, + // `populateAsset` is additive (`RepoStore.writeTree` refuses a root + // `clearPrefix`), so a republish overwrites the paths it names and + // carries every other committed file forward; `readSource` shows the + // caller the whole resulting tree. tree: { files, message }, }); } catch (err) { @@ -145,10 +171,67 @@ async function writeCodebase( } } +async function resolveHeadSha( + repoStore: WorkflowAuthorRepoReads, + assetId: string, +): Promise { + const sha = await repoStore.resolveRef( + HUB_PRINCIPAL, + { kind: WORKFLOW_ASSET_KIND, id: assetId }, + DEFAULT_ASSET_REF, + ); + if (sha === null) { + throw new WorkflowAuthorError( + "not_found", + `workflow asset ${assetId} has no ${DEFAULT_ASSET_REF} yet`, + ); + } + return sha; +} + +async function collectTree( + reads: CommittedReads, + dir: string, + into: Record, +): Promise { + const decoder = new TextDecoder(); + for (const entry of await reads.listDir(dir)) { + const path = dir === "" ? entry.name : `${dir}/${entry.name}`; + if (entry.type === "tree") { + await collectTree(reads, path, into); + } else if (entry.type === "blob") { + into[path] = decoder.decode(await reads.readBlobByOid(entry.oid)); + } + } +} + export function createWorkflowAuthorRegistry( deps: CreateWorkflowAuthorRegistryDeps, ): WorkflowAuthorRegistry { - const { db, assetService } = deps; + const { db, assetService, repoStore } = deps; + + async function requireOwnWorkflowAsset( + caller: WorkflowAuthorCaller, + assetId: string, + ): Promise<{ id: string; name: string }> { + // Own-tenant scoping is resolved from the DB row BEFORE the grant + // check runs: an asset id from another tenant must read as + // "not_found", never leak a 403 that confirms the id exists. + const row = await db.query.asset.findFirst({ + where: and( + eq(assetTable.id, assetId), + eq(assetTable.tenantId, caller.tenantId), + eq(assetTable.kind, WORKFLOW_ASSET_KIND), + ), + }); + if (row === undefined) { + throw new WorkflowAuthorError( + "not_found", + `no workflow asset ${assetId} in this tenant`, + ); + } + return { id: row.id, name: row.name }; + } return { async author(caller, input) { @@ -160,12 +243,7 @@ export function createWorkflowAuthorRegistry( `workflow name ${JSON.stringify(input.name)} must be lowercase-kebab (letters, digits, hyphens; no leading or trailing hyphen)`, ); } - if (Object.keys(input.files).length === 0) { - throw new WorkflowAuthorError( - "invalid", - "author_workflow requires at least one file", - ); - } + const { files } = validateWorkflowSourceTree(input.files); let created; try { @@ -189,45 +267,57 @@ export function createWorkflowAuthorRegistry( const { commitSha } = await writeCodebase( assetService, created.id, - input.files, + { ...files }, input.message ?? `Author ${input.name}`, ); return { assetId: created.id, name: created.name, commitSha }; }, async republish(caller, assetId, input) { - // Own-tenant scoping is resolved from the DB row BEFORE the grant - // check runs: an asset id from another tenant must read as - // "not_found", never leak a 403 that confirms the id exists. - const row = await db.query.asset.findFirst({ - where: and( - eq(assetTable.id, assetId), - eq(assetTable.tenantId, caller.tenantId), - eq(assetTable.kind, WORKFLOW_ASSET_KIND), - ), - }); - if (row === undefined) { - throw new WorkflowAuthorError( - "not_found", - `no workflow asset ${assetId} in this tenant`, - ); - } - if (Object.keys(input.files).length === 0) { - throw new WorkflowAuthorError( - "invalid", - "republish_workflow requires at least one file", - ); - } + const row = await requireOwnWorkflowAsset(caller, assetId); + const { files } = validateWorkflowSourceTree(input.files); await requireAuthorized(deps, caller, `asset:${assetId}`, "write"); + if (input.expectedHeadSha !== undefined) { + const currentHeadSha = await resolveHeadSha(repoStore, assetId); + if (currentHeadSha !== input.expectedHeadSha) { + throw new WorkflowAuthorError( + "conflict", + `workflow asset ${assetId} moved: expected head ${input.expectedHeadSha} but ${DEFAULT_ASSET_REF} is at ${currentHeadSha}; re-read the source and retry`, + { currentHeadSha }, + ); + } + } + const { commitSha } = await writeCodebase( assetService, assetId, - input.files, + { ...files }, input.message ?? `Update ${row.name}`, ); return { assetId, name: row.name, commitSha }; }, + + async readSource(caller, assetId) { + const row = await requireOwnWorkflowAsset(caller, assetId); + await requireAuthorized(deps, caller, `asset:${assetId}`, "read"); + + const headSha = await resolveHeadSha(repoStore, assetId); + const reads = await repoStore.openCommittedReads( + HUB_PRINCIPAL, + { kind: WORKFLOW_ASSET_KIND, id: assetId }, + DEFAULT_ASSET_REF, + ); + if (reads === null) { + throw new WorkflowAuthorError( + "not_found", + `workflow asset ${assetId} has no readable ${DEFAULT_ASSET_REF}`, + ); + } + const files: Record = {}; + await collectTree(reads, "", files); + return { assetId, name: row.name, headSha, files }; + }, }; } diff --git a/packages/agent-workflow-authoring/src/source-tree.ts b/packages/agent-workflow-authoring/src/source-tree.ts new file mode 100644 index 000000000..078df6438 --- /dev/null +++ b/packages/agent-workflow-authoring/src/source-tree.ts @@ -0,0 +1,161 @@ +// The trust-boundary validator for a workflow source tree an agent hands +// the authoring registry. The substrate's `workflowKindHandler.validatePush` +// already checks the manifest's shape once bytes are staged; this module +// runs BEFORE any write so a traversal path, a secret-looking filename, an +// oversize tree, or an entry that names a file the tree does not carry is +// rejected without touching git — and with a message the model can act on. +import path from "node:path"; +import { type } from "arktype"; +import { isContainedEntryPath, PackageJSON } from "@intx/types/package-json"; + +import { WorkflowAuthorError } from "./errors"; + +export const MAX_SOURCE_FILE_BYTES = 256 * 1024; +export const MAX_SOURCE_TREE_BYTES = 2 * 1024 * 1024; +export const MAX_SOURCE_FILE_COUNT = 200; +export const PACKAGE_JSON_PATH = "package.json"; + +const SECRET_LIKE_BASENAME_PATTERNS: readonly RegExp[] = [ + /^\.env(?:\..+)?$/, + /\.pem$/, + /\.key$/, + /^id_rsa/, + /\.p12$/, +]; + +const FORBIDDEN_SEGMENTS = new Set([".", "..", ".git"]); + +export type ValidatedWorkflowSourceTree = { + readonly files: Readonly>; + /** The `interchange.workflow` entry, normalized to a repo-relative path + * (no leading `./`). */ + readonly entry: string; +}; + +function invalid(message: string): WorkflowAuthorError { + return new WorkflowAuthorError("invalid", message); +} + +/** Normalizes `./workflow.ts` (or `src/../workflow.ts`) to the + * repo-relative key the tree is addressed by. */ +export function normalizeEntryPath(entry: string): string { + return path.posix.normalize(entry); +} + +export function assertRepoRelativePath(path: string): void { + if (path === "") throw invalid("a file path must not be empty"); + if (path.includes("\\")) { + throw invalid(`file path ${JSON.stringify(path)} must use "/" separators`); + } + if (path.startsWith("/")) { + throw invalid(`file path ${JSON.stringify(path)} must be repo-relative`); + } + if (path.includes("\0")) { + throw invalid(`file path ${JSON.stringify(path)} contains a NUL byte`); + } + const segments = path.split("/"); + for (const segment of segments) { + if (segment === "") { + throw invalid( + `file path ${JSON.stringify(path)} has an empty segment (trailing or doubled "/")`, + ); + } + if (FORBIDDEN_SEGMENTS.has(segment)) { + throw invalid( + `file path ${JSON.stringify(path)} may not contain a ${JSON.stringify(segment)} segment`, + ); + } + } + const basename = segments[segments.length - 1] ?? ""; + if (SECRET_LIKE_BASENAME_PATTERNS.some((pattern) => pattern.test(basename))) { + throw invalid( + `file ${JSON.stringify(path)} looks like a secret (.env*, *.pem, *.key, id_rsa*, *.p12) and cannot be committed to a workflow asset`, + ); + } +} + +function utf8ByteLength(text: string): number { + return new TextEncoder().encode(text).byteLength; +} + +function parsePackageJson(raw: string): { + readonly interchange?: { readonly workflow?: string }; +} { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (cause) { + throw invalid( + `${PACKAGE_JSON_PATH} is not valid JSON: ${cause instanceof Error ? cause.message : String(cause)}`, + ); + } + const manifest = PackageJSON(parsed); + if (manifest instanceof type.errors) { + throw invalid( + `${PACKAGE_JSON_PATH} failed validation: ${manifest.summary}`, + ); + } + return manifest; +} + +/** + * Validates a whole source tree and returns it with the resolved entry. + * Throws `WorkflowAuthorError("invalid", ...)` naming the first violation. + */ +export function validateWorkflowSourceTree( + files: Readonly>, +): ValidatedWorkflowSourceTree { + const paths = Object.keys(files); + if (paths.length === 0) { + throw invalid("a workflow source tree needs at least one file"); + } + if (paths.length > MAX_SOURCE_FILE_COUNT) { + throw invalid( + `a workflow source tree may carry at most ${MAX_SOURCE_FILE_COUNT} files (got ${paths.length})`, + ); + } + + let totalBytes = 0; + for (const path of paths) { + assertRepoRelativePath(path); + const bytes = utf8ByteLength(files[path] ?? ""); + if (bytes > MAX_SOURCE_FILE_BYTES) { + throw invalid( + `file ${JSON.stringify(path)} is ${bytes} bytes; the per-file limit is ${MAX_SOURCE_FILE_BYTES}`, + ); + } + totalBytes += bytes; + } + if (totalBytes > MAX_SOURCE_TREE_BYTES) { + throw invalid( + `the source tree totals ${totalBytes} bytes; the limit is ${MAX_SOURCE_TREE_BYTES}`, + ); + } + + const manifestSource = files[PACKAGE_JSON_PATH]; + if (manifestSource === undefined) { + throw invalid( + `a workflow source tree must carry a top-level ${PACKAGE_JSON_PATH} declaring "interchange.workflow"`, + ); + } + const manifest = parsePackageJson(manifestSource); + const declaredEntry = manifest.interchange?.workflow; + if (declaredEntry === undefined || declaredEntry === "") { + throw invalid( + `${PACKAGE_JSON_PATH} must declare a non-empty "interchange.workflow" entry`, + ); + } + if (!isContainedEntryPath(declaredEntry)) { + throw invalid( + `"interchange.workflow" entry ${JSON.stringify(declaredEntry)} must be a package-relative path that does not escape the package`, + ); + } + const entry = normalizeEntryPath(declaredEntry); + if (!(entry in files)) { + throw invalid( + `"interchange.workflow" names ${JSON.stringify(declaredEntry)} but the tree has no file at ${JSON.stringify(entry)}`, + ); + } + + return { files, entry }; +} diff --git a/packages/agent-workflow-authoring/src/workflow-routes.ts b/packages/agent-workflow-authoring/src/workflow-routes.ts index 38dc74d0d..8f034a339 100644 --- a/packages/agent-workflow-authoring/src/workflow-routes.ts +++ b/packages/agent-workflow-authoring/src/workflow-routes.ts @@ -1,5 +1,5 @@ -// The sanctioned path for a workflow-process child to author or republish -// a workflow-kind asset, mirroring `@corbits/skills`' own +// The sanctioned path for a workflow-process child to author, republish, +// or read back a workflow-kind asset, mirroring `@corbits/skills`' own // `createWorkflowSkillRoutes`: a workflow child has no browser session, // only its sidecar bearer token and the run's address, so it // authenticates through a `WorkflowRunAuthenticator` rather than the @@ -17,7 +17,8 @@ import { type } from "arktype"; import { Hono } from "hono"; import { makeErrorEnvelope } from "@workbench/hub-client"; -import { WorkflowAuthorError, type WorkflowAuthorRegistry } from "./registry"; +import { WorkflowAuthorError } from "./errors"; +import type { WorkflowAuthorRegistry } from "./registry"; export type WorkflowRunScope = { readonly tenantId: string; @@ -44,6 +45,7 @@ const RepublishBody = type({ assetId: "string", files: FilesInput, "message?": "string", + "expectedHeadSha?": "string", }); function statusFor( @@ -73,11 +75,14 @@ export function createWorkflowAuthorRoutes( app.onError((err, c) => { if (err instanceof WorkflowAuthorError) { + const envelope = makeErrorEnvelope({ + code: err.reason, + userMessage: err.message, + }); return c.json( - makeErrorEnvelope({ - code: err.reason, - userMessage: err.message, - }), + err.currentHeadSha === undefined + ? envelope + : { ...envelope, currentHeadSha: err.currentHeadSha }, statusFor(err.reason), ); } @@ -137,5 +142,14 @@ export function createWorkflowAuthorRoutes( return c.json({ data: summary }); }); + app.get("/:assetId/source", async (c) => { + const scope = c.get("workflowRunScope"); + const snapshot = await deps.registry.readSource( + scope, + c.req.param("assetId"), + ); + return c.json({ data: snapshot }); + }); + return app; } diff --git a/packages/tool-registry-publish/src/registry.ts b/packages/tool-registry-publish/src/registry.ts index bdf222e1c..f1be22a75 100644 --- a/packages/tool-registry-publish/src/registry.ts +++ b/packages/tool-registry-publish/src/registry.ts @@ -38,6 +38,7 @@ export const CORBITS_TOOL_PACKAGE_DIRS: readonly string[] = [ new URL("../../granola-tools", import.meta.url).pathname, new URL("../../manus-tools", import.meta.url).pathname, new URL("../../linear-tools", import.meta.url).pathname, + new URL("../../workflow-authoring-tools", import.meta.url).pathname, // Scout's own artifact-save/list tool bundle (`scoutArtifactTools`) and // Jimmy's `gif_search` bundle: each package pins itself in its own // `toolPackagePins` (`SCOUT_TOOL_PACKAGE_PINS`, `JIMMY_TOOL_PACKAGE_PINS`), diff --git a/packages/workflow-authoring-tools/LICENSE b/packages/workflow-authoring-tools/LICENSE new file mode 100644 index 000000000..c6487f4fd --- /dev/null +++ b/packages/workflow-authoring-tools/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-authoring-tools/README.md b/packages/workflow-authoring-tools/README.md new file mode 100644 index 000000000..0f6eb1dba --- /dev/null +++ b/packages/workflow-authoring-tools/README.md @@ -0,0 +1,66 @@ +# @corbits/workflow-authoring-tools + +The `@intx/agent` tool bundle over `@corbits/agent-workflow-authoring`'s +workflow-run-authenticated routes (CL-7360): an agent writes an ordinary +workflow code package into a `kind: "workflow"` hub asset, republishes it, +and reads it back. See [docs/workflow-source-authoring.md](../../docs/workflow-source-authoring.md) +for the contract this implements. + +## The tools + +None of the three is `approval: "ask"`: storing source is not a side effect. +Deploying an asset so it can run is a separate, human-approved step +(`workflow_deploy`, CL-7362), never this bundle's job. + +- `workflow_author({ name, files, message? })` — creates the asset and + commits the tree; returns `{ assetId, name, commitSha }`. `name` is + lowercase-kebab and unique per tenant (a duplicate is a 409). +- `workflow_republish({ assetId, files, message?, expectedHeadSha? })` — + commits a new version of the whole package. With `expectedHeadSha`, a + moved `refs/heads/main` is refused with 409 and the current head; the + agent re-reads and retries. Writes are additive: a path omitted keeps its + committed content. +- `workflow_source_read({ assetId })` — every file on `refs/heads/main` plus + `headSha`, as JSON. + +Every request carries the run's own sidecar bearer token and +`x-workflow-run-address`; the hub resolves tenant and principal from the run +and authorizes `asset:*`/`create`, `asset:`/`write`, or +`asset:`/`read` against the grant store before anything reaches git. The +hub also validates the tree at the boundary (repo-relative paths, no +secret-like filenames, `package.json` declaring an `interchange.workflow` +entry the tree carries, size caps) and returns a message the model can act +on. + +## Routes and client + +| Tool | Route | Client function | +| ---------------------- | ------------------------------------------------------ | -------------------- | +| `workflow_author` | `POST /api/workflow-workflow-authoring/author` | `authorWorkflow` | +| `workflow_republish` | `POST /api/workflow-workflow-authoring/republish` | `republishWorkflow` | +| `workflow_source_read` | `GET /api/workflow-workflow-authoring/:assetId/source` | `readWorkflowSource` | + +A hub refusal surfaces as `WorkflowAuthoringRequestError` (`status`, `code`, +`currentHeadSha` on a conflict); the bundle lets it throw, and +`@intx/agent`'s tool runner turns the message into an `isError` result. + +## Env + +`requires: ["hubWorkflowAuthoringUrl", "sidecarToken", "address"]` — +`hubWorkflowAuthoringUrl` is threaded in +`apps/sidecar/src/workflow-substrate-factory/step-env.ts` exactly like +`hubCapabilitiesUrl`. + +## Bundle id + +`@corbits/workflow_authoring/wf`, not `@corbits/workflow-authoring-tools/…`: +the qualified `:` must fit OpenAI's 64-character wire cap after +`encodeToolName` escapes `@`, `/`, `:` and `-` to three characters each. + +## Running tests + +```sh +cd packages/workflow-authoring-tools && bun test +``` + +Tests run against a mocked fetch; no `DATABASE_URL` or live hub is required. diff --git a/packages/workflow-authoring-tools/package.json b/packages/workflow-authoring-tools/package.json new file mode 100644 index 000000000..93e6ac518 --- /dev/null +++ b/packages/workflow-authoring-tools/package.json @@ -0,0 +1,24 @@ +{ + "name": "@corbits/workflow-authoring-tools", + "private": true, + "description": "Myra's workflow-authoring tool bundle (workflow_author, workflow_republish, workflow_source_read): an @intx/agent tool bundle calling @corbits/agent-workflow-authoring's workflow-run-authenticated routes so an agent can write a workflow code package into a kind:\"workflow\" hub asset and read it back; deploying that asset is a separate, approval-gated step", + "version": "0.0.1", + "license": "LGPL-2.1-or-later", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "dependencies": { + "@intx/agent": "workspace:*", + "@intx/types": "workspace:*", + "arktype": "catalog:" + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:" + } +} diff --git a/packages/workflow-authoring-tools/src/client.ts b/packages/workflow-authoring-tools/src/client.ts new file mode 100644 index 000000000..bbfeb5900 --- /dev/null +++ b/packages/workflow-authoring-tools/src/client.ts @@ -0,0 +1,188 @@ +// A minimal client for the workflow-run-authenticated authoring surface +// (`@corbits/agent-workflow-authoring`'s `createWorkflowAuthorRoutes`, +// mounted in `apps/hub` at `/api/workflow-workflow-authoring`). Every +// call carries the run's own sidecar bearer token and run address — +// the same two headers `@corbits/capability-tools` sends — so the hub +// resolves tenant and principal from the run, never from an argument. +import { type } from "arktype"; + +export interface WorkflowAuthoringClientConfig { + /** The hub's plain HTTP origin, the same value every other tool + * bundle's `hub*Url` env key carries. */ + readonly hubWorkflowAuthoringUrl: string; + readonly sidecarToken: string; + readonly address: string; + /** Override for tests; defaults to the global `fetch`. */ + readonly fetchImpl?: typeof fetch; +} + +export type WorkflowSourceFiles = Readonly>; + +export type AuthorWorkflowRequest = { + readonly name: string; + readonly files: WorkflowSourceFiles; + readonly message?: string; +}; + +export type RepublishWorkflowRequest = { + readonly assetId: string; + readonly files: WorkflowSourceFiles; + readonly message?: string; + readonly expectedHeadSha?: string; +}; + +export type WorkflowAssetSummary = { + readonly assetId: string; + readonly name: string; + readonly commitSha: string; +}; + +export type WorkflowSourceSnapshot = { + readonly assetId: string; + readonly name: string; + readonly headSha: string; + readonly files: WorkflowSourceFiles; +}; + +/** The hub refused the request with a canonical error envelope. `code` + * is the envelope's code (`invalid`, `forbidden`, `not_found`, + * `conflict`, ...); `currentHeadSha` is set on a republish `conflict` so + * the caller can re-read and retry. */ +export class WorkflowAuthoringRequestError extends Error { + readonly status: number; + readonly code: string; + readonly currentHeadSha?: string; + constructor( + status: number, + code: string, + message: string, + currentHeadSha?: string, + ) { + super(message); + this.name = "WorkflowAuthoringRequestError"; + this.status = status; + this.code = code; + if (currentHeadSha !== undefined) this.currentHeadSha = currentHeadSha; + } +} + +const ErrorResponse = type({ + error: { code: "string", userMessage: "string" }, + "currentHeadSha?": "string", +}); + +const SummaryResponse = type({ + data: { assetId: "string", name: "string", commitSha: "string" }, +}); + +const SnapshotResponse = type({ + data: { + assetId: "string", + name: "string", + headSha: "string", + files: "Record", + }, +}); + +function authHeaders( + config: WorkflowAuthoringClientConfig, +): Record { + return { + authorization: `Bearer ${config.sidecarToken}`, + "x-workflow-run-address": config.address, + }; +} + +function endpoint(config: WorkflowAuthoringClientConfig, path: string): string { + return `${config.hubWorkflowAuthoringUrl}/api/workflow-workflow-authoring${path}`; +} + +async function throwForFailure( + response: Response, + operation: string, +): Promise { + const body: unknown = await response.json().catch(() => undefined); + const parsed = ErrorResponse(body); + if (parsed instanceof type.errors) { + throw new Error( + `${operation} failed: ${response.status} ${response.statusText}`, + ); + } + throw new WorkflowAuthoringRequestError( + response.status, + parsed.error.code, + parsed.error.userMessage, + parsed.currentHeadSha, + ); +} + +function parseOrThrow( + schema: (value: unknown) => T | type.errors, + body: unknown, + operation: string, +): T { + const parsed = schema(body); + if (parsed instanceof type.errors) { + throw new Error( + `${operation} response did not match the expected shape: ${parsed.summary}`, + ); + } + return parsed; +} + +export async function authorWorkflow( + config: WorkflowAuthoringClientConfig, + input: AuthorWorkflowRequest, +): Promise { + const doFetch = config.fetchImpl ?? fetch; + const response = await doFetch(endpoint(config, "/author"), { + method: "POST", + headers: { ...authHeaders(config), "content-type": "application/json" }, + body: JSON.stringify(input), + }); + if (!response.ok) await throwForFailure(response, "Authoring a workflow"); + return parseOrThrow( + SummaryResponse, + await response.json(), + "Authoring a workflow", + ).data; +} + +export async function republishWorkflow( + config: WorkflowAuthoringClientConfig, + input: RepublishWorkflowRequest, +): Promise { + const doFetch = config.fetchImpl ?? fetch; + const response = await doFetch(endpoint(config, "/republish"), { + method: "POST", + headers: { ...authHeaders(config), "content-type": "application/json" }, + body: JSON.stringify(input), + }); + if (!response.ok) { + await throwForFailure(response, "Republishing a workflow"); + } + return parseOrThrow( + SummaryResponse, + await response.json(), + "Republishing a workflow", + ).data; +} + +export async function readWorkflowSource( + config: WorkflowAuthoringClientConfig, + assetId: string, +): Promise { + const doFetch = config.fetchImpl ?? fetch; + const response = await doFetch( + endpoint(config, `/${encodeURIComponent(assetId)}/source`), + { headers: authHeaders(config) }, + ); + if (!response.ok) { + await throwForFailure(response, "Reading a workflow's source"); + } + return parseOrThrow( + SnapshotResponse, + await response.json(), + "Reading a workflow's source", + ).data; +} diff --git a/packages/workflow-authoring-tools/src/index.ts b/packages/workflow-authoring-tools/src/index.ts new file mode 100644 index 000000000..5f33bdbf1 --- /dev/null +++ b/packages/workflow-authoring-tools/src/index.ts @@ -0,0 +1,19 @@ +export { + authorWorkflow, + readWorkflowSource, + republishWorkflow, + WorkflowAuthoringRequestError, + type AuthorWorkflowRequest, + type RepublishWorkflowRequest, + type WorkflowAssetSummary, + type WorkflowAuthoringClientConfig, + type WorkflowSourceFiles, + type WorkflowSourceSnapshot, +} from "./client"; +export { + workflowAuthoringTools, + WORKFLOW_AUTHOR_TOOL, + WORKFLOW_REPUBLISH_TOOL, + WORKFLOW_SOURCE_READ_TOOL, + type WorkflowAuthoringEnv, +} from "./tool"; diff --git a/packages/workflow-authoring-tools/src/tool.ts b/packages/workflow-authoring-tools/src/tool.ts new file mode 100644 index 000000000..a77d9f3a1 --- /dev/null +++ b/packages/workflow-authoring-tools/src/tool.ts @@ -0,0 +1,256 @@ +// The `@corbits/workflow-authoring-tools` bundle: `workflow_author`, +// `workflow_republish`, and `workflow_source_read` — an agent's way to +// write a workflow code package into a `kind: "workflow"` hub asset and +// read it back. None of the three carries `approval: "ask"`: writing +// source is not a side effect (docs/workflow-model.md, "Authority +// boundaries"). Deploying the asset is a separate, approval-gated step +// owned by the `workflow_deploy` tool, never by this bundle. +// +// A thrown error here is the honest result: `@intx/agent`'s tool runner +// converts a rejected `run` into `ToolResult { isError: true }` carrying +// the message, so the model sees exactly what the hub refused and why. +import { defineTool } from "@intx/agent"; +import type { BaseEnv } from "@intx/agent"; +import type { ToolCall, ToolResult } from "@intx/types/runtime"; +import { type } from "arktype"; + +import { + authorWorkflow, + readWorkflowSource, + republishWorkflow, + type WorkflowAuthoringClientConfig, +} from "./client"; + +export const WORKFLOW_AUTHOR_TOOL = "workflow_author"; +export const WORKFLOW_REPUBLISH_TOOL = "workflow_republish"; +export const WORKFLOW_SOURCE_READ_TOOL = "workflow_source_read"; + +/** Env this bundle needs beyond `BaseEnv`: the hub origin under its own + * key plus the run's bearer token and address, threaded by + * `apps/sidecar/src/workflow-substrate-factory/step-env.ts` exactly the + * way `@corbits/capability-tools`' `hubCapabilitiesUrl` is. */ +export interface WorkflowAuthoringEnv extends BaseEnv { + readonly hubWorkflowAuthoringUrl: string; + readonly sidecarToken: string; + readonly address: string; +} + +const Files = type("Record"); + +const AuthorInput = type({ + name: "string > 0", + files: Files, + "message?": "string > 0", +}); + +const RepublishInput = type({ + assetId: "string > 0", + files: Files, + "message?": "string > 0", + "expectedHeadSha?": "string > 0", +}); + +const SourceReadInput = type({ assetId: "string > 0" }); + +const PACKAGE_SHAPE_DESCRIPTION = + "The package is an ordinary code package: a top-level package.json " + + 'with name, version, "type": "module", and ' + + '"interchange": { "workflow": "./workflow.ts" }; the entry module ' + + "default-exports defineWorkflow({ ... }) imported from " + + '"@intx/workflow"; plus any files the entry imports. File paths are ' + + 'repo-relative with "/" separators (no leading "/", no "..", no ' + + ".git/); secret-like names (.env*, *.pem, *.key, id_rsa*, *.p12) are " + + "refused, and never put credentials in source. "; + +const FILES_PROPERTY = { + type: "object", + additionalProperties: { type: "string" }, + description: + "Map of repo-relative file path to UTF-8 file contents, e.g. " + + '{ "package.json": "...", "workflow.ts": "..." }.', +} as const; + +function clientConfig( + env: WorkflowAuthoringEnv, +): WorkflowAuthoringClientConfig { + return { + hubWorkflowAuthoringUrl: env.hubWorkflowAuthoringUrl, + sidecarToken: env.sidecarToken, + address: env.address, + }; +} + +function invalidInput(tool: string, errors: type.errors): Error { + return new Error(`${tool} received invalid input: ${errors.summary}`); +} + +function textResult(callId: string, content: string): ToolResult { + return { callId, isError: false, content }; +} + +async function runAuthor( + env: WorkflowAuthoringEnv, + call: ToolCall, +): Promise { + const input = AuthorInput(call.arguments); + if (input instanceof type.errors) { + throw invalidInput(WORKFLOW_AUTHOR_TOOL, input); + } + const summary = await authorWorkflow(clientConfig(env), input); + return textResult( + call.id, + `Authored workflow "${summary.name}" as asset ${summary.assetId} at commit ${summary.commitSha}. ` + + "It is source only until deployed.", + ); +} + +async function runRepublish( + env: WorkflowAuthoringEnv, + call: ToolCall, +): Promise { + const input = RepublishInput(call.arguments); + if (input instanceof type.errors) { + throw invalidInput(WORKFLOW_REPUBLISH_TOOL, input); + } + const summary = await republishWorkflow(clientConfig(env), input); + return textResult( + call.id, + `Republished workflow "${summary.name}" (asset ${summary.assetId}) at commit ${summary.commitSha}. ` + + "A deployed copy keeps running the previously deployed commit until redeployed.", + ); +} + +async function runSourceRead( + env: WorkflowAuthoringEnv, + call: ToolCall, +): Promise { + const input = SourceReadInput(call.arguments); + if (input instanceof type.errors) { + throw invalidInput(WORKFLOW_SOURCE_READ_TOOL, input); + } + const snapshot = await readWorkflowSource(clientConfig(env), input.assetId); + return textResult(call.id, JSON.stringify(snapshot)); +} + +/** + * The bundle id's middle segment is not the package name, unlike every + * other `@corbits/*-tools` bundle: `:` is what goes on the + * provider wire, `@`, `/`, `:` and `-` each encode to three characters + * there (`@intx/inference`'s `encodeToolName`), and + * `@corbits/workflow-authoring-tools/:workflow_source_read` + * cannot fit OpenAI's 64-character cap. `defineTool` only requires the + * `@scope/pkg/name` shape; `packages/tool-registry-publish`'s + * tool-name-limits test is what this id satisfies. + */ +export const workflowAuthoringTools = defineTool({ + id: "@corbits/workflow_authoring/wf", + requires: ["hubWorkflowAuthoringUrl", "sidecarToken", "address"], + definitions: [ + { name: WORKFLOW_AUTHOR_TOOL }, + { name: WORKFLOW_REPUBLISH_TOOL }, + { name: WORKFLOW_SOURCE_READ_TOOL }, + ], + factory: (env) => ({ + definitions: [ + { + name: WORKFLOW_AUTHOR_TOOL, + description: + "Write a new workflow code package into this workbench as a " + + "workflow asset and commit it. " + + PACKAGE_SHAPE_DESCRIPTION + + "Returns the asset id and commit sha. This only stores source: " + + "deploying the asset so it can run is a separate step that a " + + "human approves. The name must be unique in the workbench; a " + + "duplicate name is refused, so republish the existing asset " + + "instead.", + inputSchema: { + type: "object", + properties: { + name: { + type: "string", + description: + "Lowercase-kebab asset name (letters, digits, hyphens), " + + 'e.g. "daily-digest".', + }, + files: FILES_PROPERTY, + message: { + type: "string", + description: "Optional commit message.", + }, + }, + required: ["name", "files"], + }, + }, + { + name: WORKFLOW_REPUBLISH_TOOL, + description: + "Commit a new version of an existing workflow asset's source. " + + "Send the whole package (package.json and the entry module " + + "included): each file overwrites the same path, and a path you " + + "omit keeps its committed content — this tool cannot delete " + + "files. " + + PACKAGE_SHAPE_DESCRIPTION + + "Pass expectedHeadSha (the headSha from workflow_source_read) " + + "so a concurrent change is refused instead of overwritten; on a " + + "conflict, read the source again and retry. Returns the new " + + "commit sha. Deploying the new commit is a separate, " + + "human-approved step.", + inputSchema: { + type: "object", + properties: { + assetId: { + type: "string", + description: "The workflow asset id to update.", + }, + files: FILES_PROPERTY, + message: { + type: "string", + description: "Optional commit message.", + }, + expectedHeadSha: { + type: "string", + description: + "The head commit sha you last read; the write is refused " + + "if the asset has moved since.", + }, + }, + required: ["assetId", "files"], + }, + }, + { + name: WORKFLOW_SOURCE_READ_TOOL, + description: + "Read a workflow asset's committed source: every file on its " + + "main branch plus the head commit sha. Use it before " + + "workflow_republish to see the current tree and to obtain " + + "expectedHeadSha.", + inputSchema: { + type: "object", + properties: { + assetId: { + type: "string", + description: "The workflow asset id to read.", + }, + }, + required: ["assetId"], + }, + }, + ], + run: (call: ToolCall, _signal: AbortSignal) => { + switch (call.name) { + case WORKFLOW_AUTHOR_TOOL: + return runAuthor(env, call); + case WORKFLOW_REPUBLISH_TOOL: + return runRepublish(env, call); + case WORKFLOW_SOURCE_READ_TOOL: + return runSourceRead(env, call); + default: + return Promise.reject( + new Error( + `@corbits/workflow-authoring-tools: unknown tool "${call.name}"`, + ), + ); + } + }, + }), +}); diff --git a/packages/workflow-authoring-tools/tsconfig.json b/packages/workflow-authoring-tools/tsconfig.json new file mode 100644 index 000000000..50b7d0045 --- /dev/null +++ b/packages/workflow-authoring-tools/tsconfig.json @@ -0,0 +1,22 @@ +{ + "extends": "./tsconfig.src.json", + "compilerOptions": { + "composite": false, + "noEmit": true, + "disableSourceOfProjectReferenceRedirect": true, + "declaration": false, + "declarationMap": false, + "emitDeclarationOnly": false, + "rootDir": "../.." + }, + "include": ["src"], + "exclude": [], + "references": [ + { + "path": "../../vendor/intx/agent/tsconfig.src.json" + }, + { + "path": "../../vendor/intx/types/tsconfig.src.json" + } + ] +} diff --git a/packages/workflow-authoring-tools/tsconfig.src.json b/packages/workflow-authoring-tools/tsconfig.src.json new file mode 100644 index 000000000..3959f6247 --- /dev/null +++ b/packages/workflow-authoring-tools/tsconfig.src.json @@ -0,0 +1,20 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "package.json", "src/**/*.json"], + "exclude": ["src/**/*.test.ts", "src/**/*.test.tsx"], + "compilerOptions": { + "types": ["bun"], + "composite": true, + "emitDeclarationOnly": true, + "outDir": "dist", + "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo" + }, + "references": [ + { + "path": "../../vendor/intx/agent/tsconfig.src.json" + }, + { + "path": "../../vendor/intx/types/tsconfig.src.json" + } + ] +} diff --git a/tsconfig.build.json b/tsconfig.build.json index a327150f4..569a3ad69 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -145,6 +145,9 @@ { "path": "./packages/web-search-tools/tsconfig.src.json" }, + { + "path": "./packages/workflow-authoring-tools/tsconfig.src.json" + }, { "path": "./packages/workflow-deploy-source/tsconfig.src.json" }, diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 53d5fbda4..24df9bf01 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -54,6 +54,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/mcp-tools", version: "0.0.10" }, { name: "@corbits/interaction-tools", version: "0.0.4" }, { name: "@corbits/manus-tools", version: "0.0.11" }, + { name: "@corbits/workflow-authoring-tools", version: "0.0.1" }, ]; /** From 245ab2de1f37642da232d0dd23f5c64357e8e1f5 Mon Sep 17 00:00:00 2001 From: Sawyer Date: Tue, 1 Sep 2026 22:44:13 -0700 Subject: [PATCH 4/6] Update docs: workflow source authoring seams, source read, and republish conflict semantics --- docs/workflow-source-authoring.md | 32 +++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/docs/workflow-source-authoring.md b/docs/workflow-source-authoring.md index f9d1c26e5..26a79bd52 100644 --- a/docs/workflow-source-authoring.md +++ b/docs/workflow-source-authoring.md @@ -37,6 +37,7 @@ not what an agent authors by hand. | ---- | ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------- | | 1 | `POST /api/workflow-workflow-authoring/author` (`@corbits/agent-workflow-authoring`) → `AssetService.createAsset` + `populateAsset` | Run bearer + run address → tenant/principal; `asset:*`/`create` | `{ assetId, name, commitSha }` | | 1' | `.../republish` → `populateAsset` on `refs/heads/main` | `asset:`/`write`, own-tenant row check first | `{ assetId, name, commitSha }` | +| 1'' | `GET .../:assetId/source` → `RepoStore.resolveRef` + `openCommittedReads` on `refs/heads/main` | `asset:`/`read`, own-tenant row check first | `{ assetId, name, headSha, files }` | | 2 | Preview: native probe with empty `ApprovalSet`, no freeze | Same run scope | `{ wireHash, grants[] }` or an invalid-package error | | 3 | `POST /api/tenants/:tenantId/workflows/deployments` | `workflow:*`/`create`; parked on `approval: "ask"` when agent-initiated | `WorkflowDeploymentResponse { id, definitionAssetId, status }` | | 4 | Human resolves the parked approval (native `approvals` route) | `approval:*`/`resolve` | Deploy continues or is rejected | @@ -77,8 +78,16 @@ recorded initiating principal. - Asset identity is the asset id; the human-readable name is unique per tenant (`duplicate_asset` → 409 conflict). - A republish carries `expectedHeadSha`. If the ref moved, the write is - rejected with 409 and the current head; the caller re-reads and retries. - Nothing is silently overwritten. + rejected with 409 and the current head (`currentHeadSha` beside the error + envelope); the caller re-reads and retries. Nothing is silently + overwritten. The check is a read-then-write against `RepoStore.resolveRef` + rather than a compare-and-set inside `writeTree` — `receivePack` has CAS, + `writeTree` does not — so two republishes racing inside that window are + serialized by the repo lock, not refused. +- `populateAsset` is additive. A republish overwrites the paths it names and + carries every other committed file forward; `workflow_source_read` shows + the whole resulting tree. Deleting a file needs a seam that does not exist + yet. - Writing an identical tree is a no-op commit (content-aware, like the CLI pusher). Retrying an `author` after a network failure hits `duplicate_asset`; the caller then republishes. @@ -119,13 +128,24 @@ sequenceDiagram R-->>H: definition selectable as routine target ``` +## Seams that exist + +- `@corbits/workflow-authoring-tools` (CL-7360): `workflow_author`, + `workflow_republish`, `workflow_source_read` over the routes above, + pinned into Myra's `ASSISTANT_TOOL_PACKAGE_PINS` and published to the + `corbits-tools` registry. +- Path/package validation in `agent-workflow-authoring`'s registry + (`validateWorkflowSourceTree`, CL-7360): runs before any grant check or + write; caps are `MAX_SOURCE_FILE_BYTES`, `MAX_SOURCE_TREE_BYTES`, + `MAX_SOURCE_FILE_COUNT`. + ## Seams that do not exist yet (and where they go) -- An `@intx/agent` tool bundle over the authoring routes - (`@corbits/workflow-authoring-tools`): CL-7360. - A run-authenticated preview route and the `workflow_deploy` tool: CL-7361, CL-7362. -- Path/package validation in `agent-workflow-authoring`'s registry: - CL-7360. +- Deleting a file from an authored asset (a `writeTreeDelta`-backed + republish, or a `clearPrefix` the substrate accepts at the root). +- A compare-and-set republish (`expectedHeadSha` enforced under the repo + lock rather than before it). Nothing here adds a repository, compiler, probe, freezer, or approval store. From 5baf0b6bc0cfa52569513a95b10bce3da6b9d344 Mon Sep 17 00:00:00 2001 From: Sawyer Date: Wed, 2 Sep 2026 01:30:07 -0700 Subject: [PATCH 5/6] Address review findings (CL-7360) --- packages/agent-workflow-authoring/src/registry.test.ts | 3 ++- packages/agent-workflow-authoring/src/registry.ts | 9 ++++++--- packages/agent-workflow-authoring/src/source-tree.ts | 8 +++++++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/agent-workflow-authoring/src/registry.test.ts b/packages/agent-workflow-authoring/src/registry.test.ts index 59353fdb6..cbd4f18e8 100644 --- a/packages/agent-workflow-authoring/src/registry.test.ts +++ b/packages/agent-workflow-authoring/src/registry.test.ts @@ -35,6 +35,7 @@ function fakeRepoStore( return { resolveRef: async () => "sha_head", openCommittedReads: async () => null, + openCommittedReadsAtCommit: async () => null, ...overrides, }; } @@ -405,7 +406,7 @@ test("readSource walks the whole committed tree, including subdirectories, and r db: fakeDb(ownRow), repoStore: fakeRepoStore({ resolveRef: async () => "sha_head", - openCommittedReads: async () => ({ + openCommittedReadsAtCommit: async () => ({ listDir: async (dir) => dir === "" ? [ diff --git a/packages/agent-workflow-authoring/src/registry.ts b/packages/agent-workflow-authoring/src/registry.ts index 3eac4451b..8c8c64158 100644 --- a/packages/agent-workflow-authoring/src/registry.ts +++ b/packages/agent-workflow-authoring/src/registry.ts @@ -107,7 +107,7 @@ export type WorkflowAuthorRegistry = { export type WorkflowAuthorRepoReads = Pick< RepoStore, - "resolveRef" | "openCommittedReads" + "resolveRef" | "openCommittedReads" | "openCommittedReadsAtCommit" >; export type CreateWorkflowAuthorRegistryDeps = { @@ -303,11 +303,14 @@ export function createWorkflowAuthorRegistry( const row = await requireOwnWorkflowAsset(caller, assetId); await requireAuthorized(deps, caller, `asset:${assetId}`, "read"); + // Resolve the head sha and open the tree read from the SAME ref + // resolution so a concurrent republish landing between two separate + // calls can never produce a headSha/files mismatch. const headSha = await resolveHeadSha(repoStore, assetId); - const reads = await repoStore.openCommittedReads( + const reads = await repoStore.openCommittedReadsAtCommit( HUB_PRINCIPAL, { kind: WORKFLOW_ASSET_KIND, id: assetId }, - DEFAULT_ASSET_REF, + headSha, ); if (reads === null) { throw new WorkflowAuthorError( diff --git a/packages/agent-workflow-authoring/src/source-tree.ts b/packages/agent-workflow-authoring/src/source-tree.ts index 078df6438..43c52d1da 100644 --- a/packages/agent-workflow-authoring/src/source-tree.ts +++ b/packages/agent-workflow-authoring/src/source-tree.ts @@ -21,6 +21,12 @@ const SECRET_LIKE_BASENAME_PATTERNS: readonly RegExp[] = [ /\.key$/, /^id_rsa/, /\.p12$/, + /\.pfx$/, + /\.ppk$/, + /^credentials\.json$/, + /^service-account.*\.json$/, + /^\.npmrc$/, + /^\.netrc$/, ]; const FORBIDDEN_SEGMENTS = new Set([".", "..", ".git"]); @@ -60,7 +66,7 @@ export function assertRepoRelativePath(path: string): void { `file path ${JSON.stringify(path)} has an empty segment (trailing or doubled "/")`, ); } - if (FORBIDDEN_SEGMENTS.has(segment)) { + if (FORBIDDEN_SEGMENTS.has(segment.toLowerCase())) { throw invalid( `file path ${JSON.stringify(path)} may not contain a ${JSON.stringify(segment)} segment`, ); From 5ea5e91805e9265102a9c3b6607d3b3cef345315 Mon Sep 17 00:00:00 2001 From: Sawyer Date: Wed, 2 Sep 2026 03:49:17 -0700 Subject: [PATCH 6/6] Remove duplicated retarget-authorization check (CL-7360) --- packages/routines/src/routes.ts | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/packages/routines/src/routes.ts b/packages/routines/src/routes.ts index 04bf85276..8567d38a4 100644 --- a/packages/routines/src/routes.ts +++ b/packages/routines/src/routes.ts @@ -889,27 +889,6 @@ export function createRoutineRoutes( const effectiveDefinitionAssetId = body.definitionAssetId ?? existing.definitionAssetId; - if ( - body.definitionAssetId !== undefined && - body.definitionAssetId !== existing.definitionAssetId - ) { - const rejection = await rejectUnlaunchableTarget( - deps, - tenant.id, - principal.id, - body.definitionAssetId, - ); - if (rejection !== undefined) { - return c.json( - makeErrorEnvelope({ - code: rejection.code, - userMessage: rejection.userMessage, - }), - rejection.status, - ); - } - } - if ( body.trigger !== undefined && !(await webhookTriggerValid(