From 719b9d44adbd895c38666d6001a6a064f933b9ab Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 16:45:13 -0700 Subject: [PATCH 01/75] Add tests for a Manus tool package --- .../src/persist-credential.test.ts | 24 +++ packages/connections/src/probes.test.ts | 34 ++++ packages/connections/src/registry.test.ts | 17 +- .../src/http-x-manus-api-key-provider.test.ts | 124 ++++++++++++ packages/manus-tools/src/client.test.ts | 102 ++++++++++ packages/manus-tools/src/manifest.test.ts | 22 +++ packages/manus-tools/src/tool.test.ts | 179 ++++++++++++++++++ packages/plugins-ui/test/plugin-meta.test.ts | 12 ++ .../src/connections-pinned-by.test.ts | 4 + workflows/assistant/test/definition.test.ts | 15 ++ 10 files changed, 530 insertions(+), 3 deletions(-) create mode 100644 packages/credential-providers/src/http-x-manus-api-key-provider.test.ts create mode 100644 packages/manus-tools/src/client.test.ts create mode 100644 packages/manus-tools/src/manifest.test.ts create mode 100644 packages/manus-tools/src/tool.test.ts create mode 100644 packages/plugins-ui/test/plugin-meta.test.ts diff --git a/packages/connections/src/persist-credential.test.ts b/packages/connections/src/persist-credential.test.ts index f7f403d90..712ffbc05 100644 --- a/packages/connections/src/persist-credential.test.ts +++ b/packages/connections/src/persist-credential.test.ts @@ -89,6 +89,29 @@ describe("persistConnectorCredential", () => { expect(result.credentialId).toBe("cred_prv_github"); }); + test("manus persists the production API origin so origin-pin can resolve", async () => { + const { providers, seeds, fns } = recordingFns(); + await persistConnectorCredential({ + api: noApi as never, + cookies: [], + tenantId: "tnt_1", + descriptor: descriptorOrThrow("manus"), + secret: "manus_key", + log: () => undefined, + ...fns, + }); + + expect(providers).toEqual([ + { + tenantId: "tnt_1", + name: "manus", + plugin: "http-x-manus-api-key", + apiBaseUrl: "https://api.manus.ai", + }, + ]); + expect(seeds).toEqual([]); + }); + test("an inference provider seeds its catalog under the same credential name", async () => { const { credentials, seeds, fns } = recordingFns(); await persistConnectorCredential({ @@ -166,6 +189,7 @@ describe("isInferenceProvider", () => { expect(isInferenceProvider("openrouter")).toBe(true); expect(isInferenceProvider("github")).toBe(false); expect(isInferenceProvider("linear")).toBe(false); + expect(isInferenceProvider("manus")).toBe(false); }); }); diff --git a/packages/connections/src/probes.test.ts b/packages/connections/src/probes.test.ts index 9ceedea8f..6939000af 100644 --- a/packages/connections/src/probes.test.ts +++ b/packages/connections/src/probes.test.ts @@ -9,6 +9,7 @@ import { testGitHubCredential, testGranolaCredential, testLinearCredential, + testManusCredential, testScrapeCreatorsCredential, } from "./probes"; @@ -126,3 +127,36 @@ describe("testLinearCredential", () => { expect(result.ok).toBe(true); }); }); + +describe("testManusCredential", () => { + test("rejects a 401", async () => { + const result = await testManusCredential("test-key", fakeFetch(401)); + expect(result.ok).toBe(false); + }); + + test("accepts a 200", async () => { + const result = await testManusCredential( + "test-key", + fakeFetch(200, JSON.stringify({ ok: true, skills: [] })), + ); + expect(result.ok).toBe(true); + }); + + test("sends x-manus-api-key to skill.list", async () => { + const requested: { url: string; key: string | null }[] = []; + const fetchImpl: FetchLike = async (input, init) => { + requested.push({ + url: String(input), + key: + (init?.headers as Headers | undefined)?.get("x-manus-api-key") ?? + null, + }); + return new Response(JSON.stringify({ ok: true }), { status: 200 }); + }; + const result = await testManusCredential("manus_key", fetchImpl); + expect(result.ok).toBe(true); + expect(requested).toEqual([ + { url: "https://api.manus.ai/v2/skill.list", key: "manus_key" }, + ]); + }); +}); diff --git a/packages/connections/src/registry.test.ts b/packages/connections/src/registry.test.ts index 1dfa07f94..d77b30eaf 100644 --- a/packages/connections/src/registry.test.ts +++ b/packages/connections/src/registry.test.ts @@ -113,10 +113,18 @@ describe("CONNECTOR_REGISTRY", () => { expect(descriptor?.feedsTools).toEqual([]); }); - test("includes the five tool connectors with the right feedsTools", () => { + test("includes the tool connectors with the right feedsTools", () => { expect(CONNECTOR_REGISTRY["granola"]?.feedsTools).toEqual([ "@corbits/granola-tools", ]); + expect(CONNECTOR_REGISTRY["manus"]?.feedsTools).toEqual([ + "@corbits/manus-tools", + ]); + expect(CONNECTOR_REGISTRY["manus"]?.credentialPlugin).toBe( + "http-x-manus-api-key", + ); + expect(CONNECTOR_REGISTRY["manus"]?.authKind).toBe("api-key"); + expect(CONNECTOR_REGISTRY["manus"]?.icon).toBeUndefined(); expect(CONNECTOR_REGISTRY["exa"]?.feedsTools).toEqual([ "@corbits/web-search-tools", ]); @@ -161,9 +169,12 @@ describe("connectorDescriptors", () => { expect(CONNECTOR_REGISTRY["scrapecreators"]?.credentialPlugin).toBe( "http-x-api-key", ); - const bearerConnectors = new Set(["linear", "exa", "scrapecreators"]); + expect(CONNECTOR_REGISTRY["manus"]?.credentialPlugin).toBe( + "http-x-manus-api-key", + ); + const nonBearer = new Set(["linear", "exa", "scrapecreators", "manus"]); for (const [id, descriptor] of Object.entries(CONNECTOR_REGISTRY)) { - if (bearerConnectors.has(id)) continue; + if (nonBearer.has(id)) continue; expect(descriptor.credentialPlugin).toBe("http"); } }); diff --git a/packages/credential-providers/src/http-x-manus-api-key-provider.test.ts b/packages/credential-providers/src/http-x-manus-api-key-provider.test.ts new file mode 100644 index 000000000..7a7da95b9 --- /dev/null +++ b/packages/credential-providers/src/http-x-manus-api-key-provider.test.ts @@ -0,0 +1,124 @@ +import { expect, test } from "bun:test"; + +import { + createHttpXManusApiKeyCredentialProvider, + HTTP_X_MANUS_API_KEY_PROVIDER_KEY, +} from "./http-x-manus-api-key-provider"; + +const ORIGIN = "https://api.manus.ai"; + +function materialSource(secret: string): { current: string } { + return { current: secret }; +} + +test("key is http-x-manus-api-key", () => { + expect(createHttpXManusApiKeyCredentialProvider().key).toBe( + HTTP_X_MANUS_API_KEY_PROVIDER_KEY, + ); +}); + +test("sends the secret in x-manus-api-key, not authorization or x-api-key", async () => { + const captured: { + manusKey: string | null; + apiKey: string | null; + auth: string | null; + } = { + manusKey: null, + apiKey: null, + auth: null, + }; + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async (_input, init) => { + const headers = init?.headers as Headers | undefined; + captured.manusKey = headers?.get("x-manus-api-key") ?? null; + captured.apiKey = headers?.get("x-api-key") ?? null; + captured.auth = headers?.get("authorization") ?? null; + return new Response("{}", { status: 200 }); + }, + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: "manus_real_key" }), + }); + + await mediated.fetch(`${ORIGIN}/v2/skill.list`); + + expect(captured.manusKey).toBe("manus_real_key"); + expect(captured.apiKey).toBeNull(); + expect(captured.auth).toBeNull(); +}); + +test("re-reads the material source per call, reflecting a rotation", async () => { + const manusKeys: string[] = []; + const material = materialSource("original-key"); + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async (_input, init) => { + manusKeys.push( + (init?.headers as Headers | undefined)?.get("x-manus-api-key") ?? "", + ); + return new Response("{}", { status: 200 }); + }, + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: material.current }), + }); + + await mediated.fetch(`${ORIGIN}/v2/skill.list`); + material.current = "rotated-key"; + await mediated.fetch(`${ORIGIN}/v2/skill.list`); + + expect(manusKeys).toEqual(["original-key", "rotated-key"]); +}); + +test("refuses a cross-origin request rather than leaking the secret off the pinned origin", async () => { + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async () => new Response("{}", { status: 200 }), + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: "manus_real_key" }), + }); + + await expect( + mediated.fetch("https://evil.example.com/v2/skill.list"), + ).rejects.toThrow(/refusing cross-origin request/); +}); + +test("forces redirect: manual so a same-origin 3xx never auto-follows off the handle", async () => { + const captured: { redirect: string | undefined } = { redirect: undefined }; + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async (_input, init) => { + captured.redirect = init?.redirect; + return new Response("{}", { status: 200 }); + }, + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: "manus_real_key" }), + }); + + await mediated.fetch(`${ORIGIN}/v2/skill.list`); + + expect(captured.redirect).toBe("manual"); +}); + +test("also mediates a Request input, preserving its own headers", async () => { + const captured: { manusKey: string | null } = { manusKey: null }; + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async (request) => { + captured.manusKey = (request as Request).headers.get("x-manus-api-key"); + return new Response("{}", { status: 200 }); + }, + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: "manus_real_key" }), + }); + + await mediated.fetch( + new Request(`${ORIGIN}/v2/task.create`, { method: "POST" }), + ); + + expect(captured.manusKey).toBe("manus_real_key"); +}); diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts new file mode 100644 index 000000000..d0855a6f3 --- /dev/null +++ b/packages/manus-tools/src/client.test.ts @@ -0,0 +1,102 @@ +import { expect, test } from "bun:test"; + +import { createTask, listTaskMessages, manusRequest } from "./client"; + +test("createTask posts to /v2/task.create and parses the ok envelope", async () => { + const captured: { url: string; headers: Headers | null; body: string } = { + url: "", + headers: null, + body: "", + }; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + captured.url = String(input); + captured.headers = + init?.headers instanceof Headers + ? init.headers + : new Headers(init?.headers); + captured.body = typeof init?.body === "string" ? init.body : ""; + return new Response( + JSON.stringify({ + ok: true, + request_id: "req_1", + task_id: "task_1", + task_title: "Deck", + task_url: "https://manus.im/app/task_1", + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + const created = await createTask({ fetchImpl }, { content: "Make slides" }); + expect(captured.url).toBe("https://api.manus.ai/v2/task.create"); + expect(captured.headers?.get("x-manus-api-key")).toBeNull(); + expect(captured.headers?.get("authorization")).toBeNull(); + expect(captured.headers?.get("x-api-key")).toBeNull(); + expect(JSON.parse(captured.body)).toEqual({ + message: { content: "Make slides" }, + }); + expect(created.task_id).toBe("task_1"); + expect(created.task_url).toBe("https://manus.im/app/task_1"); +}); + +test("listTaskMessages GETs /v2/task.listMessages without an auth header", async () => { + const captured: { url: string; headers: Headers | null } = { + url: "", + headers: null, + }; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + captured.url = String(input); + captured.headers = + init?.headers instanceof Headers + ? init.headers + : init?.headers !== undefined + ? new Headers(init.headers) + : null; + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + const listed = await listTaskMessages({ fetchImpl }, { task_id: "task_1" }); + expect(captured.url).toBe( + "https://api.manus.ai/v2/task.listMessages?task_id=task_1", + ); + expect(captured.headers?.get("x-manus-api-key") ?? null).toBeNull(); + expect(listed.messages?.[0]?.status_update?.agent_status).toBe("stopped"); +}); + +test("maps a non-ok HTTP body with a Manus error envelope", async () => { + const fetchImpl = (async () => + new Response( + JSON.stringify({ + ok: false, + error: { code: "permission_denied", message: "bad key" }, + }), + { status: 401 }, + )) as unknown as typeof fetch; + + await expect( + manusRequest({ fetchImpl }, { method: "GET", path: "/v2/skill.list" }), + ).rejects.toThrow(/permission_denied: bad key/); +}); + +test("throws when a 200 body is not an ok envelope", async () => { + const fetchImpl = (async () => + new Response(JSON.stringify({ notes: [] }), { + status: 200, + })) as unknown as typeof fetch; + + await expect( + manusRequest({ fetchImpl }, { method: "GET", path: "/v2/skill.list" }), + ).rejects.toThrow(/did not match the expected shape/); +}); diff --git a/packages/manus-tools/src/manifest.test.ts b/packages/manus-tools/src/manifest.test.ts new file mode 100644 index 000000000..0f36b5454 --- /dev/null +++ b/packages/manus-tools/src/manifest.test.ts @@ -0,0 +1,22 @@ +// Proves this package's own `package.json` satisfies the vendored +// `PackageJSON` manifest schema with an `interchange.credentials` +// declaration the deploy-time `ToolPackageManifest` harvests. +import { expect, test } from "bun:test"; +import { type } from "arktype"; +import { PackageJSON } from "@intx/types/package-json"; + +import packageJson from "../package.json"; + +test("package.json parses against the vendored PackageJSON manifest schema", () => { + const parsed = PackageJSON(packageJson); + expect(parsed instanceof type.errors).toBe(false); +}); + +test("declares exactly one credential handle: manus", () => { + const parsed = PackageJSON(packageJson); + if (parsed instanceof type.errors) { + throw new Error(parsed.summary); + } + expect(parsed.interchange?.credentials).toEqual([{ handle: "manus" }]); + expect(parsed.version).toBe("0.0.1"); +}); diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts new file mode 100644 index 000000000..b6b0875a4 --- /dev/null +++ b/packages/manus-tools/src/tool.test.ts @@ -0,0 +1,179 @@ +import { expect, test } from "bun:test"; +import type { ToolCall } from "@intx/types/runtime"; +import type { CredentialCapability, MediatedCredential } from "@intx/types"; + +import { + CREATE_SLIDES_TOOL, + MANUS_ENDPOINTS, + MANUS_NOT_CONNECTED, + manusTools, +} from "./tool"; +import type { ManusEnv } from "./tool"; + +const CREATE_SLIDES_CALL: ToolCall = { + id: "call_1", + name: CREATE_SLIDES_TOOL, + arguments: { prompt: "Make a five-slide deck about onboarding" }, +}; + +function fakeCredentials(secret: string | undefined): CredentialCapability { + return { + resolve(handle: string): Promise { + if (secret === undefined) { + return Promise.reject( + new Error(`no credential is bound to handle "${handle}"`), + ); + } + return Promise.resolve({ + kind: "http", + fetch: (input, init) => fetch(input as string | URL, init), + dispose: () => {}, + }); + }, + }; +} + +function fakeEnv(credentials: CredentialCapability | undefined): ManusEnv { + return { credentials } as unknown as ManusEnv; +} + +const STOPPED_WITH_DECK = { + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + { + type: "assistant_message", + assistant_message: { + content: "Here is the deck.", + attachments: [ + { + type: "slides", + filename: "onboarding.pdf", + url: "https://files.manus.ai/onboarding.pdf", + id: "file_deck_1", + content_type: "application/pdf", + }, + ], + }, + }, + ], +}; + +test("declares create_slides plus thin tools covering the v2 surface", () => { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const names = bundle.definitions.map((d) => d.name); + expect(names).toContain(CREATE_SLIDES_TOOL); + expect(names).toContain("task_create"); + expect(names).toContain("task_list_msgs"); + expect(names).toContain("file_upload"); + expect(names).toContain("skill_list"); + expect(names).toContain("project_list"); + expect(names).toContain("agent_list"); + expect(names).toContain("webhook_list"); + expect(names).toContain("usage_credits"); + expect(names).toContain("connector_list"); + expect(names).toContain("browser_online"); + expect(names).toContain("website_status"); + expect(names.length).toBe(MANUS_ENDPOINTS.length + 1); +}); + +test("degrades to a non-throwing 'not connected' error when no credential is bound", async () => { + const bundle = manusTools(fakeEnv(fakeCredentials(undefined))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toBe(MANUS_NOT_CONNECTED); +}); + +test("degrades the same way when the step carries no credentials capability at all", async () => { + const bundle = manusTools(fakeEnv(undefined)); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toBe(MANUS_NOT_CONNECTED); +}); + +test("create_slides creates a task, polls messages, and surfaces the presentation file", async () => { + const originalFetch = globalThis.fetch; + const urls: string[] = []; + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + const url = String(input); + urls.push(url); + if (url.includes("/v2/task.create")) { + expect(init?.method).toBe("POST"); + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + task_title: "Onboarding", + task_url: "https://manus.im/app/task_1", + }), + { status: 200 }, + ); + } + if (url.includes("/v2/task.listMessages")) { + return new Response(JSON.stringify(STOPPED_WITH_DECK), { status: 200 }); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBeUndefined(); + const parsed = JSON.parse(result.content as string) as { + task_id: string; + agent_status: string; + files: readonly { + filename: string; + url: string; + id: string; + type: string; + content_type: string; + }[]; + }; + expect(parsed.task_id).toBe("task_1"); + expect(parsed.agent_status).toBe("stopped"); + expect(parsed.files).toEqual([ + { + filename: "onboarding.pdf", + url: "https://files.manus.ai/onboarding.pdf", + id: "file_deck_1", + type: "slides", + content_type: "application/pdf", + }, + ]); + expect(urls.some((url) => url.includes("/v2/task.create"))).toBe(true); + expect(urls.some((url) => url.includes("/v2/task.listMessages"))).toBe( + true, + ); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("degrades to an error result (never throws) when the underlying call fails", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => + new Response("nope", { status: 500 })) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + } finally { + globalThis.fetch = originalFetch; + } +}); diff --git a/packages/plugins-ui/test/plugin-meta.test.ts b/packages/plugins-ui/test/plugin-meta.test.ts new file mode 100644 index 000000000..9b64056c9 --- /dev/null +++ b/packages/plugins-ui/test/plugin-meta.test.ts @@ -0,0 +1,12 @@ +import { expect, test } from "bun:test"; +import { Stack } from "@corbits/icons"; + +import { pluginCategory, pluginIcon, pluginOutcome } from "../src/plugin-meta"; + +test("manus is a Productivity plugin whose outcome names tasks and slide-deck files", () => { + expect(pluginCategory("manus")).toBe("Productivity"); + expect(pluginOutcome("manus", "Manus")).toBe( + "Lets agents run Manus tasks and retrieve files — including slide decks.", + ); + expect(pluginIcon("manus")).toBe(Stack); +}); diff --git a/packages/settings-ui/src/connections-pinned-by.test.ts b/packages/settings-ui/src/connections-pinned-by.test.ts index b07ed95d1..2161d2e07 100644 --- a/packages/settings-ui/src/connections-pinned-by.test.ts +++ b/packages/settings-ui/src/connections-pinned-by.test.ts @@ -54,4 +54,8 @@ describe("connections pinned-by", () => { "reddit-opportunity-scanner", ]); }); + + test("manus pins the assistant", () => { + expect(CONNECTOR_PINNED_WORKFLOWS.manus).toEqual(["assistant"]); + }); }); diff --git a/workflows/assistant/test/definition.test.ts b/workflows/assistant/test/definition.test.ts index ab6ddc5b8..b4fc6899a 100644 --- a/workflows/assistant/test/definition.test.ts +++ b/workflows/assistant/test/definition.test.ts @@ -7,6 +7,7 @@ import { expect, test } from "bun:test"; import type { StepPrimitive, WorkflowDefinition } from "@intx/workflow"; import { + ASSISTANT_CREDENTIAL_BINDINGS, ASSISTANT_STEP_ID, ASSISTANT_SYSTEM_PROMPT, ASSISTANT_TOOL_PACKAGE_PINS, @@ -125,6 +126,7 @@ test("the agent pins memory, capability, and the manager-tools bundles at the ve "@corbits/skills-tools", "@corbits/mcp-tools", "@corbits/interaction-tools", + "@corbits/manus-tools", ]); // A pin the registry cannot resolve fails every assistant deploy, so // each one must name a version the workspace actually publishes. @@ -149,6 +151,19 @@ test("the prompt tells Myra to discover an MCP server's tools before calling one expect(ASSISTANT_SYSTEM_PROMPT).toContain("never guess a tool name"); }); +test("the workflow binds the Manus credential handle to a tenant-owned provider", () => { + const definition = buildAssistantWorkflow(INPUT); + expect(definition.credentialBindings).toEqual(ASSISTANT_CREDENTIAL_BINDINGS); + expect(ASSISTANT_CREDENTIAL_BINDINGS).toEqual([ + { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant", + }, + ]); +}); + test("the definition survives the workflow-asset JSON round-trip", () => { const definition = buildAssistantWorkflow(INPUT); const revived: unknown = JSON.parse(serializeAssistantWorkflow(definition)); From d4b574868082757bfcab9e480e4f1dddb5fce69a Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 16:45:20 -0700 Subject: [PATCH 02/75] Add a Manus plugin covering API v2 --- .../src/workflow-substrate-factory/index.ts | 11 +- bun.lock | 27 +- packages/connections/src/descriptor.ts | 14 +- packages/connections/src/index.ts | 1 + .../connections/src/persist-credential.ts | 17 +- packages/connections/src/probes.ts | 10 + packages/connections/src/registry.ts | 12 + .../src/http-x-manus-api-key-provider.ts | 121 +++ packages/credential-providers/src/index.ts | 6 + packages/manus-tools/LICENSE | 176 +++++ packages/manus-tools/package.json | 31 + packages/manus-tools/src/client.ts | 381 ++++++++++ packages/manus-tools/src/index.ts | 28 + packages/manus-tools/src/tool.ts | 706 ++++++++++++++++++ packages/manus-tools/tsconfig.json | 7 + packages/plugins-ui/src/plugin-meta.ts | 5 + .../settings-ui/src/connections-pinned-by.ts | 1 + .../tool-registry-publish/src/registry.ts | 1 + workflows/assistant/src/index.ts | 19 + 19 files changed, 1548 insertions(+), 26 deletions(-) create mode 100644 packages/credential-providers/src/http-x-manus-api-key-provider.ts create mode 100644 packages/manus-tools/LICENSE create mode 100644 packages/manus-tools/package.json create mode 100644 packages/manus-tools/src/client.ts create mode 100644 packages/manus-tools/src/index.ts create mode 100644 packages/manus-tools/src/tool.ts create mode 100644 packages/manus-tools/tsconfig.json diff --git a/apps/sidecar/src/workflow-substrate-factory/index.ts b/apps/sidecar/src/workflow-substrate-factory/index.ts index 737320c0a..b7aa7b657 100644 --- a/apps/sidecar/src/workflow-substrate-factory/index.ts +++ b/apps/sidecar/src/workflow-substrate-factory/index.ts @@ -35,6 +35,7 @@ import { import { createHttpRawAuthorizationCredentialProvider, createHttpXApiKeyCredentialProvider, + createHttpXManusApiKeyCredentialProvider, createMcpStreamableHttpCredentialProvider, } from "@corbits/credential-providers"; import { loadAdapterRegistry } from "@intx/inference/providers"; @@ -377,15 +378,17 @@ export function createSidecarSubstrateFactory( // with no `Bearer ` prefix -- Linear's convention) and // `http-x-api-key` plugin (for a provider row whose API expects the // secret in an `x-api-key` header -- Exa's and ScrapeCreators' - // convention), both from `@corbits/credential-providers` rather than - // forking or reaching around the vendored plugin. Fixed for the - // child's lifetime -- unlike the per-step wiring below, the set of - // provider plugins is not something a rotation or + // convention) and `http-x-manus-api-key` plugin (for Manus, which + // expects `x-manus-api-key`), all from `@corbits/credential-providers` + // rather than forking or reaching around the vendored plugin. Fixed + // for the child's lifetime -- unlike the per-step wiring below, the + // set of provider plugins is not something a rotation or // `credentials-updated` frame changes. const credentialProviders = createCredentialProviderRegistry([ ...builtinCredentialProviders(), createHttpRawAuthorizationCredentialProvider(), createHttpXApiKeyCredentialProvider(), + createHttpXManusApiKeyCredentialProvider(), createMcpStreamableHttpCredentialProvider(), ]); diff --git a/bun.lock b/bun.lock index 9bc93fec9..b9803c372 100644 --- a/bun.lock +++ b/bun.lock @@ -965,6 +965,19 @@ "typescript": "catalog:", }, }, + "packages/manus-tools": { + "name": "@corbits/manus-tools", + "version": "0.0.1", + "dependencies": { + "@intx/agent": "0.3.0", + "@intx/types": "0.3.0", + "arktype": "catalog:", + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:", + }, + }, "packages/mcp-tools": { "name": "@corbits/mcp-tools", "version": "0.0.8", @@ -2092,6 +2105,8 @@ "@corbits/mailbox": ["@corbits/mailbox@github:corbitsdev/corbits-mailbox#caa5214", { "dependencies": { "@hono/standard-validator": "0.2.3", "@standard-community/standard-json": "0.3.5", "@standard-community/standard-openapi": "0.2.9", "arktype": "2.1.29", "hono-openapi": "1.3.1" }, "peerDependencies": { "@intx/log": "^0.2.2", "@intx/mime": "^0.2.2", "@intx/types": "^0.2.2", "drizzle-orm": "^0.45.2", "hono": "^4.12.0", "postgres": "^3.4.0" } }, "corbitsdev-corbits-mailbox-caa5214", "sha512-z8DRBFgA4ukM8p29COeaMjfKZYe5jAUF4OBMiaIQFuW592+DGD/y6Ws6SjGlXmR9azkHNWh8oTzjlWlRP24vsQ=="], + "@corbits/manus-tools": ["@corbits/manus-tools@workspace:packages/manus-tools"], + "@corbits/mcp-tools": ["@corbits/mcp-tools@workspace:packages/mcp-tools"], "@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], @@ -3438,16 +3453,6 @@ "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - "@corbits/artifact-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/chat-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/context-menu/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/plugins-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - - "@corbits/settings-ui/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], @@ -3470,8 +3475,6 @@ "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.6", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="], - "@workbench/web/@corbits/react-ui": ["@corbits/react-ui@github:corbitsdev/react-ui#3b12281", { "dependencies": { "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "tailwind-merge": "^3.3.1" }, "peerDependencies": { "@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-tooltip": "^1.2.8", "@tanstack/react-query": "^5.90.2", "lucide-react": "^0.545.0 || ^1.0.0", "react": "^18.2.0 || ^19.0.0", "react-dom": "^18.2.0 || ^19.0.0", "sonner": "^2.0.7" }, "optionalPeers": ["@tanstack/react-query"] }, "corbitsdev-react-ui-3b12281", "sha512-Abvm/DO0Gqg0ITHGT9355ZxyKRPMVJLSSQSjpd3a8qt4JPrSMOLIOS4sX8ZMNNaArIbnY9F+VKrOWkUJUyO4Nw=="], - "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "better-call/@better-auth/utils": ["@better-auth/utils@0.5.0", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="], diff --git a/packages/connections/src/descriptor.ts b/packages/connections/src/descriptor.ts index 7a89a2bad..53dfb35f7 100644 --- a/packages/connections/src/descriptor.ts +++ b/packages/connections/src/descriptor.ts @@ -98,13 +98,17 @@ export interface ConnectorDescriptor { /** * Which credential-provider plugin mediates this connector's secret at * run time — the sidecar registers `"http"` (Bearer), `"http-raw-authorization"` - * (raw `authorization` header, e.g. Linear), and `"http-x-api-key"` - * (`x-api-key` header, e.g. Exa, ScrapeCreators). Provider rows are - * seeded with this key; an unknown key means no mediated fetch resolves - * at capability time. + * (raw `authorization` header, e.g. Linear), `"http-x-api-key"` + * (`x-api-key` header, e.g. Exa, ScrapeCreators), and + * `"http-x-manus-api-key"` (`x-manus-api-key` header, Manus). Provider + * rows are seeded with this key; an unknown key means no mediated fetch + * resolves at capability time. */ readonly credentialPlugin: - "http" | "http-raw-authorization" | "http-x-api-key"; + | "http" + | "http-raw-authorization" + | "http-x-api-key" + | "http-x-manus-api-key"; /** Tool packages this connector's credential feeds — the settings card's * "Pinned by" line. Empty for inference-provider connectors, which feed * workflow deployments, not a specific tool package. */ diff --git a/packages/connections/src/index.ts b/packages/connections/src/index.ts index 5e4718585..23750297f 100644 --- a/packages/connections/src/index.ts +++ b/packages/connections/src/index.ts @@ -31,6 +31,7 @@ export { testGitHubCredential, testGranolaCredential, testLinearCredential, + testManusCredential, testScrapeCreatorsCredential, } from "./probes"; export { diff --git a/packages/connections/src/persist-credential.ts b/packages/connections/src/persist-credential.ts index bf99a30f8..eb33e864f 100644 --- a/packages/connections/src/persist-credential.ts +++ b/packages/connections/src/persist-credential.ts @@ -105,11 +105,18 @@ export async function persistConnectorCredential( plugin: args.descriptor.credentialPlugin, apiBaseUrl: args.baseURLOverride, } - : { - tenantId: args.tenantId, - name: args.descriptor.id, - plugin: args.descriptor.credentialPlugin, - }; + : args.descriptor.id === "manus" + ? { + tenantId: args.tenantId, + name: args.descriptor.id, + plugin: args.descriptor.credentialPlugin, + apiBaseUrl: "https://api.manus.ai", + } + : { + tenantId: args.tenantId, + name: args.descriptor.id, + plugin: args.descriptor.credentialPlugin, + }; const providerId = await runEnsureProvider( args.api, args.cookies, diff --git a/packages/connections/src/probes.ts b/packages/connections/src/probes.ts index cc4b401d3..fefec4ab9 100644 --- a/packages/connections/src/probes.ts +++ b/packages/connections/src/probes.ts @@ -120,3 +120,13 @@ export function testLinearCredential( body: JSON.stringify({ query: "{ viewer { id } } " }), }); } + +export function testManusCredential( + apiKey: string, + fetchImpl: FetchLike = fetch, +): Promise { + return probe("Manus", fetchImpl, "https://api.manus.ai/v2/skill.list", { + method: "GET", + headers: { "x-manus-api-key": apiKey }, + }); +} diff --git a/packages/connections/src/registry.ts b/packages/connections/src/registry.ts index aafdf1dc4..15cdea538 100644 --- a/packages/connections/src/registry.ts +++ b/packages/connections/src/registry.ts @@ -78,6 +78,7 @@ import { testGitHubCredential, testGranolaCredential, testLinearCredential, + testManusCredential, testScrapeCreatorsCredential, } from "./probes"; @@ -273,6 +274,17 @@ export const CONNECTOR_REGISTRY: Readonly> = probe: (apiKey) => testGranolaCredential(apiKey), description: "Pull meeting notes and transcripts into your agents.", }, + manus: { + id: "manus", + credentialPlugin: "http-x-manus-api-key", + displayName: "Manus", + authKind: "api-key", + docsUrl: "https://open.manus.ai/docs/v2/introduction", + feedsTools: ["@corbits/manus-tools"], + probe: (apiKey) => testManusCredential(apiKey), + description: + "Have Manus run tasks and produce files — including slide decks.", + }, exa: { id: "exa", // Exa authenticates via an `x-api-key` header, not `authorization` — diff --git a/packages/credential-providers/src/http-x-manus-api-key-provider.ts b/packages/credential-providers/src/http-x-manus-api-key-provider.ts new file mode 100644 index 000000000..9ef5147a6 --- /dev/null +++ b/packages/credential-providers/src/http-x-manus-api-key-provider.ts @@ -0,0 +1,121 @@ +// A workbench-owned `CredentialProvider`, sibling to +// `http-x-api-key-provider.ts`. Manus authenticates via `x-manus-api-key`, +// not `x-api-key` (Exa/ScrapeCreators) and not `authorization` in any +// shape. Registering this as its own plugin, keyed `http-x-manus-api-key`, +// lets a tenant's Manus provider row opt into the header its API actually +// wants without changing the existing `http-x-api-key` plugin. +// +// Every protection the sibling providers enforce is mirrored exactly: the +// handle is pinned to the credential's origin at shape time, every request +// is re-checked against that origin (a cross-origin target is refused), and +// every outbound request forces `redirect: "manual"` so a 3xx never lets a +// server redirect the key to a foreign host -- only the injected header +// NAME differs. + +import type { + CredentialProvider, + CredentialShapeContext, + HttpMediatedCredential, +} from "@intx/types"; + +/** + * The minimal call signature the shaped handle needs from `fetch`. Mirrors + * `@intx/harness`'s `FetchLike` so a caller can inject a stub in tests + * without pulling the full `fetch` type's extra members. + */ +export type FetchLike = ( + input: string | URL | Request, + init?: RequestInit, +) => Promise; + +export interface HttpXManusApiKeyCredentialProviderOptions { + /** + * The `fetch` the shaped handle delegates to once the request is + * origin-checked and the header is injected. Defaults to the global + * `fetch`; injectable so origin-pinning can be exercised without a + * network. + */ + fetch?: FetchLike; +} + +/** + * Provider plugin key a `credential` row's `plugin` column names to opt a + * binding into an `x-manus-api-key` header shape. + */ +export const HTTP_X_MANUS_API_KEY_PROVIDER_KEY = "http-x-manus-api-key"; + +/** + * Build the `http-x-manus-api-key` credential provider: an + * `HttpMediatedCredential` whose `fetch` sends the secret in the + * `x-manus-api-key` header. Register it alongside `@intx/harness`'s + * `builtinCredentialProviders()` in a `CredentialProviderRegistry` and + * point a provider row's `plugin` column at + * `HTTP_X_MANUS_API_KEY_PROVIDER_KEY` to opt that credential's bindings + * into this header shape. + */ +export function createHttpXManusApiKeyCredentialProvider( + opts?: HttpXManusApiKeyCredentialProviderOptions, +): CredentialProvider { + const fetchImpl: FetchLike = opts?.fetch ?? globalThis.fetch; + + return { + key: HTTP_X_MANUS_API_KEY_PROVIDER_KEY, + shape(context: CredentialShapeContext): HttpMediatedCredential { + const pinnedOrigin = new URL(context.origin).origin; + + return { + kind: "http", + async fetch( + input: string | URL | Request, + init?: RequestInit, + ): Promise { + const target = resolveTargetUrl(input, pinnedOrigin); + if (target.origin !== pinnedOrigin) { + throw new Error( + `http-x-manus-api-key credential is pinned to ${pinnedOrigin}; refusing cross-origin request to ${target.origin}`, + ); + } + + // Read the secret fresh on every call so a rotation of the + // underlying material cell reaches this handle without a rebuild. + const { secret } = context.readCurrentMaterial(); + + if (input instanceof Request) { + const headers = new Headers(input.headers); + headers.set("x-manus-api-key", secret); + return fetchImpl( + new Request(input, { headers, redirect: "manual" }), + ); + } + + const headers = new Headers(init?.headers); + headers.set("x-manus-api-key", secret); + return fetchImpl(target, { ...init, headers, redirect: "manual" }); + }, + dispose(): void { + // An x-manus-api-key http handle allocates no resources; nothing + // to release. + }, + }; + }, + }; +} + +/** + * Resolve the URL a request targets, matching `@intx/harness`'s own + * `resolveTargetUrl`: a relative string resolves against the pinned + * origin, an absolute string or URL keeps its own origin (refused above if + * it differs), and a `Request` already carries an absolute URL. + */ +function resolveTargetUrl( + input: string | URL | Request, + pinnedOrigin: string, +): URL { + if (typeof input === "string") { + return new URL(input, pinnedOrigin); + } + if (input instanceof URL) { + return input; + } + return new URL(input.url); +} diff --git a/packages/credential-providers/src/index.ts b/packages/credential-providers/src/index.ts index a7726317c..906346c41 100644 --- a/packages/credential-providers/src/index.ts +++ b/packages/credential-providers/src/index.ts @@ -13,6 +13,12 @@ export { } from "./http-x-api-key-provider"; export type { HttpXApiKeyCredentialProviderOptions } from "./http-x-api-key-provider"; +export { + createHttpXManusApiKeyCredentialProvider, + HTTP_X_MANUS_API_KEY_PROVIDER_KEY, +} from "./http-x-manus-api-key-provider"; +export type { HttpXManusApiKeyCredentialProviderOptions } from "./http-x-manus-api-key-provider"; + export { deriveResolvedBindings } from "./resolved-bindings"; export { diff --git a/packages/manus-tools/LICENSE b/packages/manus-tools/LICENSE new file mode 100644 index 000000000..c6487f4fd --- /dev/null +++ b/packages/manus-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/manus-tools/package.json b/packages/manus-tools/package.json new file mode 100644 index 000000000..ffd17b9af --- /dev/null +++ b/packages/manus-tools/package.json @@ -0,0 +1,31 @@ +{ + "name": "@corbits/manus-tools", + "private": true, + "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", + "version": "0.0.1", + "license": "LGPL-2.1-or-later", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "interchange": { + "credentials": [ + { + "handle": "manus" + } + ] + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "dependencies": { + "@intx/agent": "0.3.0", + "@intx/types": "0.3.0", + "arktype": "catalog:" + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:" + } +} diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts new file mode 100644 index 000000000..a9d92478c --- /dev/null +++ b/packages/manus-tools/src/client.ts @@ -0,0 +1,381 @@ +// A Manus OpenAPI v2 client. Every workbench consumer of Manus goes +// through the same parsed, validated shape. Callers that need graceful +// degradation (the tool bundle) catch at their own boundary rather than +// this client silently swallowing errors. +// +// Auth is never attached here: a mediated credential's `fetch` injects +// `x-manus-api-key` per call (see `@corbits/credential-providers`'s +// `http-x-manus-api-key` plugin). Tests inject a `fetchImpl` and assert +// that this module does not add an auth header of its own. +import { type } from "arktype"; + +export const DEFAULT_MANUS_BASE_URL = "https://api.manus.ai"; + +export interface ManusClientConfig { + /** Override for tests; defaults to the real Manus API host. */ + readonly baseUrl?: string; + readonly fetchImpl?: typeof fetch; +} + +const ManusErrorEnvelope = type({ + ok: "false", + "request_id?": "string", + error: { + code: "string", + message: "string", + }, +}); + +const ManusOkEnvelope = type({ + ok: "true", + "request_id?": "string", +}); + +const TaskAttachment = type({ + "type?": "string", + "filename?": "string", + "url?": "string", + "id?": "string", + "content_type?": "string", +}); +export type TaskAttachment = typeof TaskAttachment.infer; + +const TaskEvent = type({ + "id?": "string", + "type?": "string", + "timestamp?": "number", + "assistant_message?": { + "content?": "string", + "attachments?": TaskAttachment.array(), + }, + "status_update?": { + "agent_status?": "string", + "brief?": "string", + "description?": "string", + }, + "error_message?": { + "error_type?": "string", + "content?": "string", + }, +}); +export type TaskEvent = typeof TaskEvent.infer; + +export const CreateTaskResponse = type({ + ok: "true", + "request_id?": "string", + task_id: "string", + "task_title?": "string", + "task_url?": "string", + "share_url?": "string", + "share_visibility?": "string", +}); +export type CreateTaskResponse = typeof CreateTaskResponse.infer; + +export const ListMessagesResponse = type({ + ok: "true", + "request_id?": "string", + "task_id?": "string", + "messages?": TaskEvent.array(), + "has_more?": "boolean", + "next_cursor?": "string", +}); +export type ListMessagesResponse = typeof ListMessagesResponse.infer; + +export type ManusHttpMethod = "GET" | "POST"; + +export type OutputFile = { + readonly filename?: string; + readonly url?: string; + readonly id?: string; + readonly type?: string; + readonly content_type?: string; +}; + +function jsonHeaders(): Record { + return { "content-type": "application/json" }; +} + +function throwManusFailure( + status: number, + statusText: string, + body: unknown, +): never { + const parsed = ManusErrorEnvelope(body); + if (!(parsed instanceof type.errors)) { + throw new Error( + `Manus request failed: ${parsed.error.code}: ${parsed.error.message}`, + ); + } + throw new Error(`Manus request failed: ${status} ${statusText}`); +} + +function parseOkBody(body: unknown): Record { + const error = ManusErrorEnvelope(body); + if (!(error instanceof type.errors)) { + throw new Error( + `Manus request failed: ${error.error.code}: ${error.error.message}`, + ); + } + const parsed = ManusOkEnvelope(body); + if (parsed instanceof type.errors) { + throw new Error( + `Manus response did not match the expected shape: ${parsed.summary}`, + ); + } + if (typeof body !== "object" || body === null || Array.isArray(body)) { + throw new Error( + "Manus response did not match the expected shape: not an object", + ); + } + return body as Record; +} + +function queryString(params: Readonly>): string { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined || value === null) continue; + if ( + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + search.set(key, String(value)); + } + } + const encoded = search.toString(); + return encoded === "" ? "" : `?${encoded}`; +} + +/** + * Calls one Manus v2 RPC path. GET arguments become query params; POST + * arguments become a JSON body. Throws on transport, HTTP, `ok: false`, + * or envelope-shape failure. + */ +export async function manusRequest( + config: ManusClientConfig, + args: { + readonly method: ManusHttpMethod; + readonly path: string; + readonly params?: Readonly>; + }, +): Promise> { + const doFetch = config.fetchImpl ?? fetch; + const base = config.baseUrl ?? DEFAULT_MANUS_BASE_URL; + const params = args.params ?? {}; + const url = + args.method === "GET" + ? `${base}${args.path}${queryString(params)}` + : `${base}${args.path}`; + const response = + args.method === "GET" + ? await doFetch(url, { method: "GET" }) + : await doFetch(url, { + method: "POST", + headers: jsonHeaders(), + body: JSON.stringify(params), + }); + let body: unknown; + try { + body = await response.json(); + } catch (cause) { + throw new Error( + `Manus request failed: ${response.status} ${response.statusText}`, + { cause }, + ); + } + if (!response.ok) { + throwManusFailure(response.status, response.statusText, body); + } + return parseOkBody(body); +} + +export type CreateTaskParams = { + readonly content: string; + readonly title?: string; + readonly project_id?: string; + readonly locale?: string; + readonly interactive_mode?: boolean; + readonly hide_in_task_list?: boolean; + readonly share_visibility?: string; + readonly agent_profile?: string; +}; + +export async function createTask( + config: ManusClientConfig, + params: CreateTaskParams, +): Promise { + const body: Record = { + message: { content: params.content }, + }; + if (params.title !== undefined) body["title"] = params.title; + if (params.project_id !== undefined) body["project_id"] = params.project_id; + if (params.locale !== undefined) body["locale"] = params.locale; + if (params.interactive_mode !== undefined) { + body["interactive_mode"] = params.interactive_mode; + } + if (params.hide_in_task_list !== undefined) { + body["hide_in_task_list"] = params.hide_in_task_list; + } + if (params.share_visibility !== undefined) { + body["share_visibility"] = params.share_visibility; + } + if (params.agent_profile !== undefined) { + body["agent_profile"] = params.agent_profile; + } + const raw = await manusRequest(config, { + method: "POST", + path: "/v2/task.create", + params: body, + }); + const parsed = CreateTaskResponse(raw); + if (parsed instanceof type.errors) { + throw new Error( + `Manus create-task response did not match the expected shape: ${parsed.summary}`, + ); + } + return parsed; +} + +export type ListMessagesParams = { + readonly task_id: string; + readonly limit?: number; + readonly cursor?: string; + readonly order?: string; + readonly verbose?: boolean; + readonly slides_format?: string; +}; + +export async function listTaskMessages( + config: ManusClientConfig, + params: ListMessagesParams, +): Promise { + const query: Record = { task_id: params.task_id }; + if (params.limit !== undefined) query["limit"] = params.limit; + if (params.cursor !== undefined) query["cursor"] = params.cursor; + if (params.order !== undefined) query["order"] = params.order; + if (params.verbose !== undefined) query["verbose"] = params.verbose; + if (params.slides_format !== undefined) { + query["slides_format"] = params.slides_format; + } + const raw = await manusRequest(config, { + method: "GET", + path: "/v2/task.listMessages", + params: query, + }); + const parsed = ListMessagesResponse(raw); + if (parsed instanceof type.errors) { + throw new Error( + `Manus list-messages response did not match the expected shape: ${parsed.summary}`, + ); + } + return parsed; +} + +export function latestAgentStatus( + messages: readonly TaskEvent[] | undefined, +): string | undefined { + if (messages === undefined) return undefined; + let status: string | undefined; + for (const event of messages) { + const next = event.status_update?.agent_status; + if (next !== undefined) status = next; + } + return status; +} + +export function extractOutputFiles( + messages: readonly TaskEvent[] | undefined, +): readonly OutputFile[] { + if (messages === undefined) return []; + const files: OutputFile[] = []; + for (const event of messages) { + const attachments = event.assistant_message?.attachments ?? []; + for (const attachment of attachments) { + if ( + attachment.filename === undefined && + attachment.url === undefined && + attachment.id === undefined + ) { + continue; + } + const file: { + filename?: string; + url?: string; + id?: string; + type?: string; + content_type?: string; + } = {}; + if (attachment.filename !== undefined) + file.filename = attachment.filename; + if (attachment.url !== undefined) file.url = attachment.url; + if (attachment.id !== undefined) file.id = attachment.id; + if (attachment.type !== undefined) file.type = attachment.type; + if (attachment.content_type !== undefined) { + file.content_type = attachment.content_type; + } + files.push(file); + } + } + return files; +} + +const TERMINAL_STATUSES = new Set(["stopped", "error"]); + +export type CreateSlideDeckParams = CreateTaskParams & { + readonly pollIntervalMs?: number; + readonly maxPolls?: number; +}; + +/** + * Creates a task whose prompt asks Manus to produce a slide deck, then + * polls `task.listMessages` until the agent stops (or errors) and returns + * any output files so a caller can retrieve them. + */ +export async function createSlideDeck( + config: ManusClientConfig, + params: CreateSlideDeckParams, +): Promise<{ + readonly task_id: string; + readonly task_title?: string; + readonly task_url?: string; + readonly agent_status?: string; + readonly files: readonly OutputFile[]; + readonly error?: string; +}> { + const created = await createTask(config, params); + const pollIntervalMs = params.pollIntervalMs ?? 1500; + const maxPolls = params.maxPolls ?? 40; + let messages: ListMessagesResponse | undefined; + for (let i = 0; i < maxPolls; i += 1) { + messages = await listTaskMessages(config, { + task_id: created.task_id, + slides_format: "pdf", + }); + const status = latestAgentStatus(messages.messages); + if (status !== undefined && TERMINAL_STATUSES.has(status)) break; + if (i < maxPolls - 1 && pollIntervalMs > 0) { + await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + } + } + const status = latestAgentStatus(messages?.messages); + const files = extractOutputFiles(messages?.messages); + const errorEvent = messages?.messages?.find((event) => event.error_message); + const result: { + task_id: string; + task_title?: string; + task_url?: string; + agent_status?: string; + files: readonly OutputFile[]; + error?: string; + } = { + task_id: created.task_id, + files, + }; + if (created.task_title !== undefined) result.task_title = created.task_title; + if (created.task_url !== undefined) result.task_url = created.task_url; + if (status !== undefined) result.agent_status = status; + if (errorEvent?.error_message?.content !== undefined) { + result.error = errorEvent.error_message.content; + } + return result; +} diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts new file mode 100644 index 000000000..44a342d21 --- /dev/null +++ b/packages/manus-tools/src/index.ts @@ -0,0 +1,28 @@ +export { + CreateTaskResponse, + ListMessagesResponse, + createSlideDeck, + createTask, + extractOutputFiles, + latestAgentStatus, + listTaskMessages, + manusRequest, + DEFAULT_MANUS_BASE_URL, +} from "./client"; +export type { + CreateSlideDeckParams, + CreateTaskParams, + ListMessagesParams, + ManusClientConfig, + OutputFile, + TaskAttachment, + TaskEvent, +} from "./client"; +export { + CREATE_SLIDES_TOOL, + MANUS_CREDENTIAL_HANDLE, + MANUS_ENDPOINTS, + MANUS_NOT_CONNECTED, + manusTools, +} from "./tool"; +export type { ManusEnv } from "./tool"; diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts new file mode 100644 index 000000000..996d26d89 --- /dev/null +++ b/packages/manus-tools/src/tool.ts @@ -0,0 +1,706 @@ +// The Manus tool bundle: an agent-facing wrapper around `./client.ts` +// that never throws. A missing credential or a failed call both come +// back as a completed `ToolResult` with `isError: true`. +import { defineTool } from "@intx/agent"; +import type { BaseEnv } from "@intx/agent"; +import type { CredentialCapability } from "@intx/types"; +import type { ToolCall, ToolResult } from "@intx/types/runtime"; + +import { + createSlideDeck, + createTask, + listTaskMessages, + manusRequest, + type ManusClientConfig, + type ManusHttpMethod, +} from "./client"; + +/** The handle this package declares in `interchange.credentials`. */ +export const MANUS_CREDENTIAL_HANDLE = "manus"; + +export const MANUS_NOT_CONNECTED = "Manus is not connected for this user."; + +export const CREATE_SLIDES_TOOL = "create_slides"; + +type JsonSchemaProperty = { + readonly type: string; + readonly description: string; +}; + +type EndpointSpec = { + readonly name: string; + readonly method: ManusHttpMethod; + readonly path: string; + readonly description: string; + readonly required: readonly string[]; + readonly properties: Readonly>; +}; + +const STRING = (description: string): JsonSchemaProperty => ({ + type: "string", + description, +}); +const NUMBER = (description: string): JsonSchemaProperty => ({ + type: "number", + description, +}); +const BOOLEAN = (description: string): JsonSchemaProperty => ({ + type: "boolean", + description, +}); +const OBJECT = (description: string): JsonSchemaProperty => ({ + type: "object", + description, +}); + +export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ + { + name: "task_create", + method: "POST", + path: "/v2/task.create", + description: + "Creates a Manus task. Pass content as the prompt text (sent as message.content). Poll task_list_msgs for progress.", + required: ["content"], + properties: { + content: STRING("Prompt text that starts the task."), + title: STRING("Optional custom task title."), + project_id: STRING("Project to associate this task with."), + locale: STRING("Output locale, e.g. en or zh-CN."), + interactive_mode: BOOLEAN( + "When true, the agent may pause to ask questions.", + ), + hide_in_task_list: BOOLEAN( + "When true, hide the task from the Manus task list.", + ), + share_visibility: STRING("private, team, or public."), + agent_profile: STRING("manus-1.6, manus-1.6-lite, or manus-1.6-max."), + }, + }, + { + name: "task_detail", + method: "GET", + path: "/v2/task.detail", + description: "Fetches one Manus task by task_id.", + required: ["task_id"], + properties: { task_id: STRING("Task id.") }, + }, + { + name: "task_list", + method: "GET", + path: "/v2/task.list", + description: "Lists Manus tasks.", + required: [], + properties: { + limit: NUMBER("Page size."), + cursor: STRING("Pagination cursor."), + order: STRING("Sort order."), + scope: STRING("List scope."), + agent_id: STRING("Filter by agent id."), + project_id: STRING("Filter by project id."), + }, + }, + { + name: "task_update", + method: "POST", + path: "/v2/task.update", + description: + "Updates a Manus task's title, visibility, or list visibility.", + required: ["task_id"], + properties: { + task_id: STRING("Task id."), + title: STRING("New title."), + share_visibility: STRING("private, team, or public."), + enable_visible_in_task_list: BOOLEAN( + "Show the task in the Manus task list.", + ), + }, + }, + { + name: "task_stop", + method: "POST", + path: "/v2/task.stop", + description: "Stops a running Manus task.", + required: ["task_id"], + properties: { task_id: STRING("Task id.") }, + }, + { + name: "task_delete", + method: "POST", + path: "/v2/task.delete", + description: "Deletes a Manus task.", + required: ["task_id"], + properties: { task_id: STRING("Task id.") }, + }, + { + name: "task_send_msg", + method: "POST", + path: "/v2/task.sendMessage", + description: "Sends a follow-up message to an existing Manus task.", + required: ["task_id", "content"], + properties: { + task_id: STRING("Task id."), + content: STRING("Follow-up prompt text (sent as message.content)."), + agent_profile: STRING("Optional agent profile override."), + }, + }, + { + name: "task_list_msgs", + method: "GET", + path: "/v2/task.listMessages", + description: + "Lists messages and status events for a Manus task. Poll until agent_status is stopped. Output files appear as assistant_message attachments.", + required: ["task_id"], + properties: { + task_id: STRING("Task id."), + limit: NUMBER("Page size."), + cursor: STRING("Pagination cursor."), + order: STRING("Sort order."), + verbose: BOOLEAN("Include tool/plan events."), + slides_format: STRING("Preferred slides download format, e.g. pdf."), + }, + }, + { + name: "task_confirm", + method: "POST", + path: "/v2/task.confirmAction", + description: + "Confirms a waiting Manus task action (event_id from a waiting status).", + required: ["task_id", "event_id"], + properties: { + task_id: STRING("Task id."), + event_id: STRING("Waiting event id."), + input: OBJECT("Optional confirmation input object."), + }, + }, + { + name: "project_create", + method: "POST", + path: "/v2/project.create", + description: "Creates a Manus project.", + required: ["name"], + properties: { + name: STRING("Project name."), + instruction: STRING("Optional project instruction."), + }, + }, + { + name: "project_list", + method: "GET", + path: "/v2/project.list", + description: "Lists Manus projects.", + required: [], + properties: {}, + }, + { + name: "skill_list", + method: "GET", + path: "/v2/skill.list", + description: "Lists available Manus skills.", + required: [], + properties: { project_id: STRING("Optional project id to scope skills.") }, + }, + { + name: "agent_list", + method: "GET", + path: "/v2/agent.list", + description: "Lists Manus agents.", + required: [], + properties: {}, + }, + { + name: "agent_detail", + method: "GET", + path: "/v2/agent.detail", + description: "Fetches one Manus agent by agent_id.", + required: ["agent_id"], + properties: { agent_id: STRING("Agent id.") }, + }, + { + name: "agent_update", + method: "POST", + path: "/v2/agent.update", + description: "Updates a Manus agent's nickname or about text.", + required: ["agent_id"], + properties: { + agent_id: STRING("Agent id."), + nickname: STRING("New nickname."), + about: STRING("New about text."), + }, + }, + { + name: "file_upload", + method: "POST", + path: "/v2/file.upload", + description: + "Creates a pending Manus file and returns a presigned upload_url. PUT the file bytes to that URL before it expires.", + required: ["filename"], + properties: { filename: STRING("File name to upload.") }, + }, + { + name: "file_detail", + method: "GET", + path: "/v2/file.detail", + description: "Fetches one Manus file by file_id.", + required: ["file_id"], + properties: { file_id: STRING("File id.") }, + }, + { + name: "file_delete", + method: "POST", + path: "/v2/file.delete", + description: "Deletes a Manus file.", + required: ["file_id"], + properties: { file_id: STRING("File id.") }, + }, + { + name: "webhook_create", + method: "POST", + path: "/v2/webhook.create", + description: "Creates a Manus webhook.", + required: ["url"], + properties: { url: STRING("Webhook callback URL.") }, + }, + { + name: "webhook_list", + method: "GET", + path: "/v2/webhook.list", + description: "Lists Manus webhooks.", + required: [], + properties: {}, + }, + { + name: "webhook_delete", + method: "POST", + path: "/v2/webhook.delete", + description: "Deletes a Manus webhook.", + required: ["webhook_id"], + properties: { webhook_id: STRING("Webhook id.") }, + }, + { + name: "webhook_pubkey", + method: "GET", + path: "/v2/webhook.publicKey", + description: "Returns the Manus webhook signing public key.", + required: [], + properties: {}, + }, + { + name: "usage_list", + method: "GET", + path: "/v2/usage.list", + description: "Lists Manus usage records.", + required: [], + properties: { + limit: NUMBER("Page size."), + cursor: STRING("Pagination cursor."), + }, + }, + { + name: "usage_credits", + method: "GET", + path: "/v2/usage.availableCredits", + description: "Returns available Manus credits.", + required: [], + properties: {}, + }, + { + name: "usage_team_stat", + method: "GET", + path: "/v2/usage.teamStatistic", + description: "Returns Manus team usage statistics.", + required: [], + properties: { + start_date: NUMBER("Start date as a unix timestamp."), + end_date: NUMBER("End date as a unix timestamp."), + }, + }, + { + name: "usage_team_log", + method: "GET", + path: "/v2/usage.teamLog", + description: "Returns the Manus team usage log.", + required: [], + properties: { + limit: NUMBER("Page size."), + cursor: STRING("Pagination cursor."), + start_date: NUMBER("Start date as a unix timestamp."), + end_date: NUMBER("End date as a unix timestamp."), + sort_by: STRING("Sort field."), + is_asc: BOOLEAN("Sort ascending when true."), + }, + }, + { + name: "connector_list", + method: "GET", + path: "/v2/connector.list", + description: "Lists Manus connectors available to this account.", + required: [], + properties: {}, + }, + { + name: "browser_online", + method: "GET", + path: "/v2/browser.onlineList", + description: "Lists online Manus browser clients.", + required: [], + properties: {}, + }, + { + name: "website_status", + method: "GET", + path: "/v2/website.status", + description: "Returns Manus website publish status for a task or website.", + required: [], + properties: { + task_id: STRING("Task id."), + website_id: STRING("Website id."), + }, + }, + { + name: "website_publish", + method: "POST", + path: "/v2/website.publish", + description: "Publishes a Manus website.", + required: [], + properties: { + task_id: STRING("Task id."), + website_id: STRING("Website id."), + visibility: STRING("Visibility."), + }, + }, + { + name: "website_update", + method: "POST", + path: "/v2/website.update", + description: "Updates a Manus website title or visibility.", + required: [], + properties: { + task_id: STRING("Task id."), + website_id: STRING("Website id."), + title: STRING("New title."), + visibility: STRING("Visibility."), + }, + }, + { + name: "website_ckpts", + method: "GET", + path: "/v2/website.listCheckpoints", + description: "Lists Manus website checkpoints.", + required: [], + properties: { + task_id: STRING("Task id."), + website_id: STRING("Website id."), + }, + }, +]; + +export interface ManusEnv extends BaseEnv { + readonly credentials?: CredentialCapability; +} + +function notConnectedResult(callId: string): ToolResult { + return { + callId, + content: MANUS_NOT_CONNECTED, + isError: true, + }; +} + +async function resolveManusCredential( + env: ManusEnv, +): Promise<{ fetchImpl: typeof fetch } | null> { + if (env.credentials === undefined) return null; + try { + const mediated = await env.credentials.resolve(MANUS_CREDENTIAL_HANDLE); + return { fetchImpl: mediated.fetch as unknown as typeof fetch }; + } catch { + return null; + } +} + +function asClientConfig(credential: { + fetchImpl: typeof fetch; +}): ManusClientConfig { + return { fetchImpl: credential.fetchImpl }; +} + +function stringArg(call: ToolCall, key: string): string | undefined { + const value = call.arguments[key]; + return typeof value === "string" ? value : undefined; +} + +function pickParams( + call: ToolCall, + keys: readonly string[], +): Record { + const params: Record = {}; + for (const key of keys) { + const value = call.arguments[key]; + if (value !== undefined) params[key] = value; + } + return params; +} + +function missingRequired( + call: ToolCall, + required: readonly string[], +): string | undefined { + for (const key of required) { + const value = call.arguments[key]; + if (value === undefined || value === "") return key; + } + return undefined; +} + +function errorResult(callId: string, err: unknown): ToolResult { + return { + callId, + content: err instanceof Error ? err.message : String(err), + isError: true, + }; +} + +async function runEndpoint( + env: ManusEnv, + call: ToolCall, + spec: EndpointSpec, +): Promise { + const credential = await resolveManusCredential(env); + if (credential === null) return notConnectedResult(call.id); + const missing = missingRequired(call, spec.required); + if (missing !== undefined) { + return { + callId: call.id, + content: `${spec.name} requires a non-empty ${missing} argument`, + isError: true, + }; + } + const params = pickParams(call, Object.keys(spec.properties)); + if (spec.name === "task_create") { + const content = stringArg(call, "content"); + if (content === undefined || content === "") { + return { + callId: call.id, + content: "task_create requires a non-empty content argument", + isError: true, + }; + } + try { + const created = await createTask(asClientConfig(credential), { + content, + ...optionalCreateFields(call), + }); + return { callId: call.id, content: JSON.stringify(created) }; + } catch (err) { + return errorResult(call.id, err); + } + } + if (spec.name === "task_send_msg") { + const content = stringArg(call, "content"); + const taskId = stringArg(call, "task_id"); + if (content === undefined || taskId === undefined) { + return { + callId: call.id, + content: "task_send_msg requires task_id and content", + isError: true, + }; + } + const body: Record = { + task_id: taskId, + message: { content }, + }; + const profile = stringArg(call, "agent_profile"); + if (profile !== undefined) body["agent_profile"] = profile; + try { + const result = await manusRequest(asClientConfig(credential), { + method: spec.method, + path: spec.path, + params: body, + }); + return { callId: call.id, content: JSON.stringify(result) }; + } catch (err) { + return errorResult(call.id, err); + } + } + if (spec.name === "task_list_msgs") { + const taskId = stringArg(call, "task_id"); + if (taskId === undefined || taskId === "") { + return { + callId: call.id, + content: "task_list_msgs requires a non-empty task_id argument", + isError: true, + }; + } + try { + const listed = await listTaskMessages(asClientConfig(credential), { + task_id: taskId, + ...optionalListMessageFields(call), + }); + return { callId: call.id, content: JSON.stringify(listed) }; + } catch (err) { + return errorResult(call.id, err); + } + } + try { + const result = await manusRequest(asClientConfig(credential), { + method: spec.method, + path: spec.path, + params, + }); + return { callId: call.id, content: JSON.stringify(result) }; + } catch (err) { + return errorResult(call.id, err); + } +} + +function optionalCreateFields(call: ToolCall): { + title?: string; + project_id?: string; + locale?: string; + interactive_mode?: boolean; + hide_in_task_list?: boolean; + share_visibility?: string; + agent_profile?: string; +} { + const fields: { + title?: string; + project_id?: string; + locale?: string; + interactive_mode?: boolean; + hide_in_task_list?: boolean; + share_visibility?: string; + agent_profile?: string; + } = {}; + const title = stringArg(call, "title"); + if (title !== undefined) fields.title = title; + const projectId = stringArg(call, "project_id"); + if (projectId !== undefined) fields.project_id = projectId; + const locale = stringArg(call, "locale"); + if (locale !== undefined) fields.locale = locale; + if (typeof call.arguments["interactive_mode"] === "boolean") { + fields.interactive_mode = call.arguments["interactive_mode"]; + } + if (typeof call.arguments["hide_in_task_list"] === "boolean") { + fields.hide_in_task_list = call.arguments["hide_in_task_list"]; + } + const visibility = stringArg(call, "share_visibility"); + if (visibility !== undefined) fields.share_visibility = visibility; + const profile = stringArg(call, "agent_profile"); + if (profile !== undefined) fields.agent_profile = profile; + return fields; +} + +function optionalListMessageFields(call: ToolCall): { + limit?: number; + cursor?: string; + order?: string; + verbose?: boolean; + slides_format?: string; +} { + const fields: { + limit?: number; + cursor?: string; + order?: string; + verbose?: boolean; + slides_format?: string; + } = {}; + if (typeof call.arguments["limit"] === "number") { + fields.limit = call.arguments["limit"]; + } + const cursor = stringArg(call, "cursor"); + if (cursor !== undefined) fields.cursor = cursor; + const order = stringArg(call, "order"); + if (order !== undefined) fields.order = order; + if (typeof call.arguments["verbose"] === "boolean") { + fields.verbose = call.arguments["verbose"]; + } + const slidesFormat = stringArg(call, "slides_format"); + if (slidesFormat !== undefined) fields.slides_format = slidesFormat; + return fields; +} + +async function runCreateSlides( + env: ManusEnv, + call: ToolCall, +): Promise { + const credential = await resolveManusCredential(env); + if (credential === null) return notConnectedResult(call.id); + const prompt = stringArg(call, "prompt"); + if (prompt === undefined || prompt === "") { + return { + callId: call.id, + content: `${CREATE_SLIDES_TOOL} requires a non-empty prompt argument`, + isError: true, + }; + } + const title = stringArg(call, "title"); + try { + const result = await createSlideDeck(asClientConfig(credential), { + content: prompt, + ...(title !== undefined ? { title } : {}), + }); + return { callId: call.id, content: JSON.stringify(result) }; + } catch (err) { + return errorResult(call.id, err); + } +} + +const CREATE_SLIDES_DEFINITION = { + name: CREATE_SLIDES_TOOL, + description: + "Creates a Manus task that produces a slide deck from a prompt, waits until the agent stops, and returns output files (filename, url, id) so they can be retrieved.", + inputSchema: { + type: "object", + properties: { + prompt: { + type: "string", + description: "What the slide deck should cover.", + }, + title: { + type: "string", + description: "Optional task title.", + }, + }, + required: ["prompt"], + }, +} as const; + +/** + * The `@corbits/manus-tools` bundle factory. The bundle id's local + * segment is kept short — the wire encoding of `:` must + * fit the 64-char OpenAI function-name cap. + */ +export const manusTools = defineTool({ + id: "@corbits/manus-tools/mn", + requires: ["credentials"], + definitions: [ + { name: CREATE_SLIDES_TOOL }, + ...MANUS_ENDPOINTS.map((spec) => ({ name: spec.name })), + ], + factory: (env) => ({ + definitions: [ + CREATE_SLIDES_DEFINITION, + ...MANUS_ENDPOINTS.map((spec) => ({ + name: spec.name, + description: spec.description, + inputSchema: { + type: "object", + properties: spec.properties, + ...(spec.required.length > 0 ? { required: [...spec.required] } : {}), + }, + })), + ], + run: (call, _signal) => { + if (call.name === CREATE_SLIDES_TOOL) return runCreateSlides(env, call); + const spec = MANUS_ENDPOINTS.find((entry) => entry.name === call.name); + if (spec === undefined) { + return Promise.resolve({ + callId: call.id, + content: `Unknown Manus tool: ${call.name}`, + isError: true, + }); + } + return runEndpoint(env, call, spec); + }, + }), +}); diff --git a/packages/manus-tools/tsconfig.json b/packages/manus-tools/tsconfig.json new file mode 100644 index 000000000..12ec9a862 --- /dev/null +++ b/packages/manus-tools/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["bun"] + }, + "include": ["src"] +} diff --git a/packages/plugins-ui/src/plugin-meta.ts b/packages/plugins-ui/src/plugin-meta.ts index 6fa64d63d..fd8b93524 100644 --- a/packages/plugins-ui/src/plugin-meta.ts +++ b/packages/plugins-ui/src/plugin-meta.ts @@ -13,6 +13,7 @@ import { type Icon, MagnifyingGlass, Microphone, + Stack, } from "@corbits/icons"; export type PluginCategory = @@ -32,6 +33,7 @@ export const PLUGIN_CATEGORY_ORDER: readonly PluginCategory[] = [ const CATEGORY_BY_ID: Readonly> = { granola: "Productivity", + manus: "Productivity", notion: "Productivity", zoom: "Communication", slack: "Communication", @@ -68,6 +70,8 @@ const OUTCOME_BY_ID: Readonly> = { huggingface: "Routes your agents' inference through Hugging Face-hosted models.", granola: "Lets agents read your Granola call notes and post-call summaries.", + manus: + "Lets agents run Manus tasks and retrieve files — including slide decks.", exa: "Lets agents run live web search and research lookups.", scrapecreators: "Lets agents pull Reddit threads and creator content.", linear: "Lets agents read and update your Linear issues.", @@ -79,6 +83,7 @@ const OUTCOME_BY_ID: Readonly> = { // than reaching for a third-party brand icon set. const ICON_BY_ID: Readonly> = { granola: Microphone, + manus: Stack, exa: MagnifyingGlass, scrapecreators: ChatCircle, linear: GitBranch, diff --git a/packages/settings-ui/src/connections-pinned-by.ts b/packages/settings-ui/src/connections-pinned-by.ts index 8c6d73534..a14777a5b 100644 --- a/packages/settings-ui/src/connections-pinned-by.ts +++ b/packages/settings-ui/src/connections-pinned-by.ts @@ -22,4 +22,5 @@ export const CONNECTOR_PINNED_WORKFLOWS: Readonly< attio: ["attio-task-agent"], scrapecreators: ["reddit-opportunity-scanner"], github: ["code-review"], + manus: ["assistant"], }; diff --git a/packages/tool-registry-publish/src/registry.ts b/packages/tool-registry-publish/src/registry.ts index 9911d9214..bdf222e1c 100644 --- a/packages/tool-registry-publish/src/registry.ts +++ b/packages/tool-registry-publish/src/registry.ts @@ -36,6 +36,7 @@ export const CORBITS_TOOL_PACKAGE_DIRS: readonly string[] = [ new URL("../../github-tools", import.meta.url).pathname, new URL("../../web-search-tools", import.meta.url).pathname, new URL("../../granola-tools", import.meta.url).pathname, + new URL("../../manus-tools", import.meta.url).pathname, new URL("../../linear-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 diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index b683eb6d6..663354fec 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -25,6 +25,7 @@ import type { AgentDefinition, InferencePreference } from "@intx/agent"; import { defineWorkflow, step } from "@intx/workflow"; import type { WorkflowDefinition } from "@intx/workflow"; import type { ToolPackagePin } from "@intx/types/tool-packages"; +import type { CredentialBinding } from "@intx/types"; export const ASSISTANT_WORKFLOW_ID = "wf_assistant"; export const ASSISTANT_STEP_ID = "assistant"; @@ -50,6 +51,23 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, + { name: "@corbits/manus-tools", version: "0.0.1" }, +]; + +/** + * Binds `@corbits/manus-tools`' declared "manus" handle to a tenant-owned + * Manus credential. The launch resolves this against + * `buildCredentialDelivery`, materializing a consumer-scoped grant for + * the pinned package so Myra can call Manus when the connector is + * connected. + */ +export const ASSISTANT_CREDENTIAL_BINDINGS: readonly CredentialBinding[] = [ + { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant", + }, ]; /** @@ -268,6 +286,7 @@ export function buildAssistantWorkflow( return defineWorkflow({ id: ASSISTANT_WORKFLOW_ID, trigger: { type: "mail", to: input.triggerAddress }, + credentialBindings: ASSISTANT_CREDENTIAL_BINDINGS, steps: { assistant: step({ agent: { From 366d1c611447674eff9e508843c4fa07753dc63e Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 16:45:28 -0700 Subject: [PATCH 03/75] Update docs: Manus plugin --- docs/credential-wiring.md | 24 ++++++++++----- packages/credential-providers/README.md | 8 +++++ packages/manus-tools/README.md | 40 +++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) create mode 100644 packages/manus-tools/README.md diff --git a/docs/credential-wiring.md b/docs/credential-wiring.md index 32faf5db1..8cf35968f 100644 --- a/docs/credential-wiring.md +++ b/docs/credential-wiring.md @@ -1,7 +1,7 @@ # Credential wiring: from connect to tool call (CL-6032) How a tenant's connected credential (Settings · Connections) reaches the -tool call a workflow step makes, and the two `CredentialProvider` plugins +tool call a workflow step makes, and the `CredentialProvider` plugins that shape it. ## The chain @@ -36,8 +36,8 @@ step-agent-tools.ts`) derives each tool factory's consumer identity ## Provider plugins A credential's `provider` row names a `plugin` -- the `CredentialProvider` -key its bindings shape through. Two are registered in the sidecar's -`CredentialProviderRegistry`: +key its bindings shape through. The sidecar's `CredentialProviderRegistry` +registers: - **`http`** -- `@intx/harness`'s vendored `createHttpCredentialProvider`. Sends `authorization: Bearer `. The default for any bearer-token @@ -47,14 +47,24 @@ key its bindings shape through. Two are registered in the sidecar's verbatim in `authorization`, no `Bearer ` prefix. Linear's API expects this raw-key convention, not a bearer token, so a Linear provider row MUST set `plugin: "http-raw-authorization"` -- seeding it as `"http"` - sends the wrong header shape and Linear rejects the call. Both plugins - mirror the same origin-pinning and `redirect: "manual"` protections; - only the injected header value differs. + sends the wrong header shape and Linear rejects the call. +- **`http-x-api-key`** -- `@corbits/credential-providers`'s + `createHttpXApiKeyCredentialProvider`. Sends the secret in `x-api-key`. + Exa and ScrapeCreators expect this header, not `authorization`. +- **`http-x-manus-api-key`** -- `@corbits/credential-providers`'s + `createHttpXManusApiKeyCredentialProvider`. Sends the secret in + `x-manus-api-key`. A Manus provider row MUST set this plugin -- seeding + it as `"http"` or `"http-x-api-key"` sends the wrong header name and + Manus rejects the call. + +All four plugins mirror the same origin-pinning and `redirect: "manual"` +protections; only the injected header differs. `packages/connections` (the Connections-surface registry) is the other place this plugin id needs to be correct: whatever seeds or registers a Linear provider row there must set `plugin: "http-raw-authorization"`, -matching this doc, not the `"http"` default other connectors use. +and a Manus row must set `plugin: "http-x-manus-api-key"`, matching this +doc, not the `"http"` default other connectors use. ## Trust boundary diff --git a/packages/credential-providers/README.md b/packages/credential-providers/README.md index 93f9e3aaf..372b4b8c3 100644 --- a/packages/credential-providers/README.md +++ b/packages/credential-providers/README.md @@ -43,6 +43,14 @@ same origin-pinning and `redirect: "manual"` protections; only the injected header name differs. A tenant's Exa or ScrapeCreators provider row must set `plugin: "http-x-api-key"`. +## `http-x-manus-api-key` + +Manus authenticates via `x-manus-api-key`, not `x-api-key` and not +`authorization` in any shape. `createHttpXManusApiKeyCredentialProvider` +(key `http-x-manus-api-key`) mirrors the same origin-pinning and +`redirect: "manual"` protections; only the injected header name differs. +A tenant's Manus provider row must set `plugin: "http-x-manus-api-key"`. + ## `resolved-bindings` `deriveResolvedBindings` reshapes a launch-time `CredentialDelivery` diff --git a/packages/manus-tools/README.md b/packages/manus-tools/README.md new file mode 100644 index 000000000..219937af3 --- /dev/null +++ b/packages/manus-tools/README.md @@ -0,0 +1,40 @@ +# @corbits/manus-tools + +Manus OpenAPI v2 integration: a typed client and an `@intx/agent` tool +bundle covering tasks, files, skills, projects, agents, webhooks, usage, +connectors, browser, and website endpoints. Slide-deck creation is the +passing demo — `create_slides` starts a task, polls messages until the +agent stops, and surfaces output files (filename, url, id). + +## Credential + +The bundle's env carries `credentials`, the harness's consumer-gated +`CredentialCapability`. When it is absent, or `credentials.resolve("manus")` +throws, the tool never throws itself: it returns a completed result with +`isError: true` and content `"Manus is not connected for this user."` + +This package declares one credential handle, `manus`, in +`package.json`'s `interchange.credentials`. Connect Manus once in Settings +· Connections (API key via `x-manus-api-key`). The client never attaches +that header — the `http-x-manus-api-key` credential plugin injects it. +The assistant workflow pins `@corbits/manus-tools` so the tools exist; it +does not require a Manus credential binding. An unconnected tenant +degrades at tool time to "Manus is not connected for this user." like +Granola, rather than failing launch. + +## Usage + +```ts +import { manusTools } from "@corbits/manus-tools"; + +const agent = defineAgent({ + // ... + tools: [manusTools], +}); +``` + +## Running tests + +``` +cd packages/manus-tools && bun test +``` From 8487d54aaf01b76195b29c88a6f0d872655df040 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:07:57 -0700 Subject: [PATCH 04/75] Drop required Manus credential binding from the assistant --- workflows/assistant/src/index.ts | 18 ------------------ workflows/assistant/test/definition.test.ts | 16 +++++----------- 2 files changed, 5 insertions(+), 29 deletions(-) diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 663354fec..da9ebbaf0 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -25,7 +25,6 @@ import type { AgentDefinition, InferencePreference } from "@intx/agent"; import { defineWorkflow, step } from "@intx/workflow"; import type { WorkflowDefinition } from "@intx/workflow"; import type { ToolPackagePin } from "@intx/types/tool-packages"; -import type { CredentialBinding } from "@intx/types"; export const ASSISTANT_WORKFLOW_ID = "wf_assistant"; export const ASSISTANT_STEP_ID = "assistant"; @@ -54,22 +53,6 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/manus-tools", version: "0.0.1" }, ]; -/** - * Binds `@corbits/manus-tools`' declared "manus" handle to a tenant-owned - * Manus credential. The launch resolves this against - * `buildCredentialDelivery`, materializing a consumer-scoped grant for - * the pinned package so Myra can call Manus when the connector is - * connected. - */ -export const ASSISTANT_CREDENTIAL_BINDINGS: readonly CredentialBinding[] = [ - { - package: "@corbits/manus-tools", - handle: "manus", - provider: "manus", - locator: "tenant", - }, -]; - /** * WELCOME: how Myra introduces herself when asked. Said once, briefly — * an offer, not a menu. The opening hello itself is canned and posted @@ -286,7 +269,6 @@ export function buildAssistantWorkflow( return defineWorkflow({ id: ASSISTANT_WORKFLOW_ID, trigger: { type: "mail", to: input.triggerAddress }, - credentialBindings: ASSISTANT_CREDENTIAL_BINDINGS, steps: { assistant: step({ agent: { diff --git a/workflows/assistant/test/definition.test.ts b/workflows/assistant/test/definition.test.ts index b4fc6899a..7a9ee0f80 100644 --- a/workflows/assistant/test/definition.test.ts +++ b/workflows/assistant/test/definition.test.ts @@ -7,7 +7,6 @@ import { expect, test } from "bun:test"; import type { StepPrimitive, WorkflowDefinition } from "@intx/workflow"; import { - ASSISTANT_CREDENTIAL_BINDINGS, ASSISTANT_STEP_ID, ASSISTANT_SYSTEM_PROMPT, ASSISTANT_TOOL_PACKAGE_PINS, @@ -151,17 +150,12 @@ test("the prompt tells Myra to discover an MCP server's tools before calling one expect(ASSISTANT_SYSTEM_PROMPT).toContain("never guess a tool name"); }); -test("the workflow binds the Manus credential handle to a tenant-owned provider", () => { +test("the workflow pins manus-tools and does not require a Manus credential binding", () => { const definition = buildAssistantWorkflow(INPUT); - expect(definition.credentialBindings).toEqual(ASSISTANT_CREDENTIAL_BINDINGS); - expect(ASSISTANT_CREDENTIAL_BINDINGS).toEqual([ - { - package: "@corbits/manus-tools", - handle: "manus", - provider: "manus", - locator: "tenant", - }, - ]); + expect(ASSISTANT_TOOL_PACKAGE_PINS.map((pin) => pin.name)).toContain( + "@corbits/manus-tools", + ); + expect(definition.credentialBindings ?? []).toEqual([]); }); test("the definition survives the workflow-asset JSON round-trip", () => { From 65cfee3b84372cd841ad7d0b280afd1b24609588 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:08:01 -0700 Subject: [PATCH 05/75] Wait for Manus slide decks without pdf or stale status --- packages/manus-tools/src/client.test.ts | 179 +++++++++++++++++++++++- packages/manus-tools/src/client.ts | 83 +++++++++-- packages/manus-tools/src/index.ts | 3 + packages/manus-tools/src/tool.test.ts | 69 ++++++++- packages/manus-tools/src/tool.ts | 10 +- 5 files changed, 323 insertions(+), 21 deletions(-) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index d0855a6f3..ae8b42e6f 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -1,6 +1,15 @@ import { expect, test } from "bun:test"; -import { createTask, listTaskMessages, manusRequest } from "./client"; +import { + createSlideDeck, + createTask, + DEFAULT_SLIDE_MAX_POLLS, + DEFAULT_SLIDE_POLL_INTERVAL_MS, + latestAgentStatus, + listTaskMessages, + manusRequest, + SLIDES_FORMAT_PPTX, +} from "./client"; test("createTask posts to /v2/task.create and parses the ok envelope", async () => { const captured: { url: string; headers: Headers | null; body: string } = { @@ -100,3 +109,171 @@ test("throws when a 200 body is not an ok envelope", async () => { manusRequest({ fetchImpl }, { method: "GET", path: "/v2/skill.list" }), ).rejects.toThrow(/did not match the expected shape/); }); + +test("latestAgentStatus uses the first status_update under default desc order", () => { + expect( + latestAgentStatus([ + { type: "status_update", status_update: { agent_status: "stopped" } }, + { type: "status_update", status_update: { agent_status: "running" } }, + ]), + ).toBe("stopped"); +}); + +test("createSlideDeck treats mixed [stopped, running] desc as terminal", async () => { + const listUrls: string[] = []; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + expect( + JSON.parse(typeof init?.body === "string" ? init.body : ""), + ).toEqual({ + message: { + content: + "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + }, + }); + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listUrls.push(url); + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + { + type: "status_update", + status_update: { agent_status: "running" }, + }, + ], + }), + { status: 200 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + const result = await createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 3 }, + ); + expect(result.agent_status).toBe("stopped"); + expect(listUrls).toHaveLength(1); + expect(listUrls[0]).toContain(`slides_format=${SLIDES_FORMAT_PPTX}`); + expect(listUrls[0]).not.toContain("slides_format=pdf"); + expect(SLIDES_FORMAT_PPTX).toBe("pptx"); +}); + +test("createSlideDeck throws when the agent is still running after the poll budget", async () => { + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "running" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 2 }, + ), + ).rejects.toThrow(/did not stop in time \(agent_status: running\)/); +}); + +test("createSlideDeck throws when the agent is waiting", async () => { + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "waiting" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 5 }, + ), + ).rejects.toThrow(/waiting for confirmation/); +}); + +test("createSlideDeck aborts polling instead of waiting out the timeout", async () => { + const controller = new AbortController(); + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "running" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + const pending = createSlideDeck( + { fetchImpl }, + { + content: "Onboarding", + pollIntervalMs: 30_000, + maxPolls: 10, + signal: controller.signal, + }, + ); + queueMicrotask(() => controller.abort()); + await expect(pending).rejects.toThrow(/cancelled/); +}); + +test("default slide-deck wait is several minutes", () => { + expect( + DEFAULT_SLIDE_MAX_POLLS * DEFAULT_SLIDE_POLL_INTERVAL_MS, + ).toBeGreaterThan(60_000); + expect(DEFAULT_SLIDE_MAX_POLLS * DEFAULT_SLIDE_POLL_INTERVAL_MS).toBe( + 5 * 60 * 1000, + ); +}); diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index a9d92478c..c46a72f27 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -275,12 +275,14 @@ export function latestAgentStatus( messages: readonly TaskEvent[] | undefined, ): string | undefined { if (messages === undefined) return undefined; - let status: string | undefined; + // task.listMessages defaults to desc (newest first). The first + // status_update is the current agent_status; walking to the last + // event would treat an older running state as current. for (const event of messages) { const next = event.status_update?.agent_status; - if (next !== undefined) status = next; + if (next !== undefined) return next; } - return status; + return undefined; } export function extractOutputFiles( @@ -321,15 +323,58 @@ export function extractOutputFiles( const TERMINAL_STATUSES = new Set(["stopped", "error"]); +/** Manus `slides_format` accepts pptx or html — never pdf. */ +export const SLIDES_FORMAT_PPTX = "pptx"; + +export const DEFAULT_SLIDE_POLL_INTERVAL_MS = 2_000; +/** 5 minutes at the default interval — a real deck takes longer than 60s. */ +export const DEFAULT_SLIDE_MAX_POLLS = 150; + +const SLIDE_DECK_PROMPT_PREFIX = + "Create a slide presentation in pptx format. Produce a presentation " + + "deck, not a document. Topic and requirements:\n\n"; + export type CreateSlideDeckParams = CreateTaskParams & { readonly pollIntervalMs?: number; readonly maxPolls?: number; + readonly signal?: AbortSignal; }; +function throwIfSlideWaitAborted(signal: AbortSignal | undefined): void { + if (signal?.aborted) { + throw new Error("Manus slide-deck wait was cancelled"); + } +} + +function sleep(ms: number, signal?: AbortSignal): Promise { + if (ms <= 0) { + throwIfSlideWaitAborted(signal); + return Promise.resolve(); + } + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(new Error("Manus slide-deck wait was cancelled")); + }; + if (signal === undefined) return; + if (signal.aborted) { + clearTimeout(timer); + reject(new Error("Manus slide-deck wait was cancelled")); + return; + } + signal.addEventListener("abort", onAbort, { once: true }); + }); +} + /** * Creates a task whose prompt asks Manus to produce a slide deck, then * polls `task.listMessages` until the agent stops (or errors) and returns - * any output files so a caller can retrieve them. + * any output files so a caller can retrieve them. A timeout, a still-running + * or waiting agent, or an abort is a thrown error — never a successful deck. */ export async function createSlideDeck( config: ManusClientConfig, @@ -342,22 +387,38 @@ export async function createSlideDeck( readonly files: readonly OutputFile[]; readonly error?: string; }> { - const created = await createTask(config, params); - const pollIntervalMs = params.pollIntervalMs ?? 1500; - const maxPolls = params.maxPolls ?? 40; + const { pollIntervalMs, maxPolls, signal, ...taskParams } = params; + const created = await createTask(config, { + ...taskParams, + content: `${SLIDE_DECK_PROMPT_PREFIX}${taskParams.content}`, + }); + const intervalMs = pollIntervalMs ?? DEFAULT_SLIDE_POLL_INTERVAL_MS; + const polls = maxPolls ?? DEFAULT_SLIDE_MAX_POLLS; let messages: ListMessagesResponse | undefined; - for (let i = 0; i < maxPolls; i += 1) { + for (let i = 0; i < polls; i += 1) { + throwIfSlideWaitAborted(signal); messages = await listTaskMessages(config, { task_id: created.task_id, - slides_format: "pdf", + slides_format: SLIDES_FORMAT_PPTX, }); const status = latestAgentStatus(messages.messages); if (status !== undefined && TERMINAL_STATUSES.has(status)) break; - if (i < maxPolls - 1 && pollIntervalMs > 0) { - await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + if (status === "waiting") { + throw new Error( + `Manus task ${created.task_id} is waiting for confirmation and cannot finish unattended`, + ); + } + if (i < polls - 1) { + await sleep(intervalMs, signal); } } const status = latestAgentStatus(messages?.messages); + if (status === undefined || !TERMINAL_STATUSES.has(status)) { + throw new Error( + `Manus task ${created.task_id} did not stop in time` + + (status !== undefined ? ` (agent_status: ${status})` : ""), + ); + } const files = extractOutputFiles(messages?.messages); const errorEvent = messages?.messages?.find((event) => event.error_message); const result: { diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index 44a342d21..7013c25b1 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -8,6 +8,9 @@ export { listTaskMessages, manusRequest, DEFAULT_MANUS_BASE_URL, + DEFAULT_SLIDE_MAX_POLLS, + DEFAULT_SLIDE_POLL_INTERVAL_MS, + SLIDES_FORMAT_PPTX, } from "./client"; export type { CreateSlideDeckParams, diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index b6b0875a4..9fd80fe37 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -52,10 +52,11 @@ const STOPPED_WITH_DECK = { attachments: [ { type: "slides", - filename: "onboarding.pdf", - url: "https://files.manus.ai/onboarding.pdf", + filename: "onboarding.pptx", + url: "https://files.manus.ai/onboarding.pptx", id: "file_deck_1", - content_type: "application/pdf", + content_type: + "application/vnd.openxmlformats-officedocument.presentationml.presentation", }, ], }, @@ -81,6 +82,17 @@ test("declares create_slides plus thin tools covering the v2 surface", () => { expect(names.length).toBe(MANUS_ENDPOINTS.length + 1); }); +test("task_list_msgs describes slides_format as pptx or html, never pdf", () => { + const listMsgs = MANUS_ENDPOINTS.find( + (spec) => spec.name === "task_list_msgs", + ); + expect(listMsgs?.properties["slides_format"]?.description).toContain("pptx"); + expect(listMsgs?.properties["slides_format"]?.description).toContain("html"); + expect(listMsgs?.properties["slides_format"]?.description).not.toMatch( + /pdf/i, + ); +}); + test("degrades to a non-throwing 'not connected' error when no credential is bound", async () => { const bundle = manusTools(fakeEnv(fakeCredentials(undefined))); const result = await bundle.run( @@ -109,6 +121,12 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio urls.push(url); if (url.includes("/v2/task.create")) { expect(init?.method).toBe("POST"); + const body = JSON.parse(typeof init?.body === "string" ? init.body : ""); + expect(body.message.content).toContain("slide presentation"); + expect(body.message.content).toContain("pptx"); + expect(body.message.content).toContain( + "Make a five-slide deck about onboarding", + ); return new Response( JSON.stringify({ ok: true, @@ -120,6 +138,8 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio ); } if (url.includes("/v2/task.listMessages")) { + expect(url).toContain("slides_format=pptx"); + expect(url).not.toContain("slides_format=pdf"); return new Response(JSON.stringify(STOPPED_WITH_DECK), { status: 200 }); } return new Response("unexpected", { status: 500 }); @@ -146,11 +166,12 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio expect(parsed.agent_status).toBe("stopped"); expect(parsed.files).toEqual([ { - filename: "onboarding.pdf", - url: "https://files.manus.ai/onboarding.pdf", + filename: "onboarding.pptx", + url: "https://files.manus.ai/onboarding.pptx", id: "file_deck_1", type: "slides", - content_type: "application/pdf", + content_type: + "application/vnd.openxmlformats-officedocument.presentationml.presentation", }, ]); expect(urls.some((url) => url.includes("/v2/task.create"))).toBe(true); @@ -162,6 +183,42 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio } }); +test("create_slides returns isError when the agent is waiting", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: unknown) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "waiting" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toMatch(/waiting for confirmation/); + } finally { + globalThis.fetch = originalFetch; + } +}); + test("degrades to an error result (never throws) when the underlying call fails", async () => { const originalFetch = globalThis.fetch; globalThis.fetch = (async () => diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index 996d26d89..4f9ab756e 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -156,7 +156,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ cursor: STRING("Pagination cursor."), order: STRING("Sort order."), verbose: BOOLEAN("Include tool/plan events."), - slides_format: STRING("Preferred slides download format, e.g. pdf."), + slides_format: STRING("Preferred slides download format: pptx or html."), }, }, { @@ -622,6 +622,7 @@ function optionalListMessageFields(call: ToolCall): { async function runCreateSlides( env: ManusEnv, call: ToolCall, + signal: AbortSignal, ): Promise { const credential = await resolveManusCredential(env); if (credential === null) return notConnectedResult(call.id); @@ -638,6 +639,7 @@ async function runCreateSlides( const result = await createSlideDeck(asClientConfig(credential), { content: prompt, ...(title !== undefined ? { title } : {}), + signal, }); return { callId: call.id, content: JSON.stringify(result) }; } catch (err) { @@ -690,8 +692,10 @@ export const manusTools = defineTool({ }, })), ], - run: (call, _signal) => { - if (call.name === CREATE_SLIDES_TOOL) return runCreateSlides(env, call); + run: (call, signal) => { + if (call.name === CREATE_SLIDES_TOOL) { + return runCreateSlides(env, call, signal); + } const spec = MANUS_ENDPOINTS.find((entry) => entry.name === call.name); if (spec === undefined) { return Promise.resolve({ From 989ed15b1df40a6761a8e0bb3cac7543b8c77fa9 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:57:44 -0700 Subject: [PATCH 06/75] Add tests for folding pinned-package credentials at launch A pin with no matching binding is inert at tool time. Launch already folds MCP bindings when the package is pinned; static handles such as Manus need the same coverage so a connected tenant does not see "not connected" after Settings. --- packages/folded-runs/test/launch.test.ts | 268 +++++++++++++++++++++++ 1 file changed, 268 insertions(+) diff --git a/packages/folded-runs/test/launch.test.ts b/packages/folded-runs/test/launch.test.ts index 8b7f8fc5c..1cf240ce2 100644 --- a/packages/folded-runs/test/launch.test.ts +++ b/packages/folded-runs/test/launch.test.ts @@ -1403,6 +1403,274 @@ describe("deployAtHead — mcp credential bindings", () => { }); }); +describe("deployAtHead — pinned-package credential bindings", () => { + const MANUS_BINDING = { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant" as const, + }; + + function catalogSources(): DefinitionSourceResolution { + return { + ok: true, + sources: [ + { + id: "off_1", + provider: "anthropic", + baseURL: "https://inference.invalid", + apiKey: "placeholder", + model: "claude-sonnet-5", + }, + ], + defaultSource: "off_1", + }; + } + + test("folds a connected manus binding into delivery and runtimeConfig when manus-tools is pinned", async () => { + resolveDefinitionSourcesCalls.length = 0; + resolveDefinitionSourcesResult = catalogSources(); + buildCredentialDeliveryCalls.length = 0; + buildCredentialDeliveryResult = { + ok: true, + delivery: { + bindings: [ + { + handle: "manus", + credentialId: "cred_manus_1", + consumer: "tool:@corbits/manus-tools", + }, + ], + materials: [ + { + credentialId: "cred_manus_1", + providerKey: "manus", + origin: "https://api.manus.ai", + secret: "n/a", + }, + ], + }, + }; + + const db = createFakeDb(); + const sessionService = createFakeSessionService(); + const assetService = createFakeAssetService(); + const eventCollectors = createFakeEventCollectors(); + const pinnedPackageCalls: { tenantId: string; pins: unknown }[] = []; + + await deployAtHead( + { + db: db as never, + sidecarRouter: createFakeSidecarRouter(), + assetService, + sessionService, + eventCollectors, + credentialCipher: {} as never, + toolGrantsForPins: () => [], + pinnedPackageCredentialBindingsFor: async (tenantId, pins) => { + pinnedPackageCalls.push({ tenantId, pins }); + return [MANUS_BINDING]; + }, + }, + { + tenantId: "ten_1", + instanceId: "ins_1", + triggerAddress: "ins_1@ten1.workbench.test", + principalId: "prn_1", + sessionId: "ses_1", + foldedBody: { + ...FOLDED_BODY, + toolPackagePins: [{ name: "@corbits/manus-tools", version: "*" }], + }, + launchLabel: "myra", + }, + ); + + expect(pinnedPackageCalls).toEqual([ + { + tenantId: "ten_1", + pins: [{ name: "@corbits/manus-tools", version: "*" }], + }, + ]); + expect(buildCredentialDeliveryCalls).toHaveLength(1); + expect(buildCredentialDeliveryCalls[0]).toMatchObject({ + tenantId: "ten_1", + bindings: [MANUS_BINDING], + }); + + const deployed = onlyCall(sessionService.adoptedDeployCalls); + expect(deployed.credentialCipher).toBeDefined(); + expect(deployed.config.grants).toContainEqual( + expect.objectContaining({ + resource: "credential:cred_manus_1", + action: "use", + conditions: { tool: "tool:@corbits/manus-tools" }, + }), + ); + const entry = + assetService.populateAssetCalls[0]?.tree.files["workflow.js"] ?? ""; + expect(entryDefinition(entry)["credentialBindings"]).toEqual([ + MANUS_BINDING, + ]); + }); + + test("succeeds with no manus binding when the port returns none", async () => { + resolveDefinitionSourcesCalls.length = 0; + resolveDefinitionSourcesResult = catalogSources(); + buildCredentialDeliveryCalls.length = 0; + + const db = createFakeDb(); + const sessionService = createFakeSessionService(); + const assetService = createFakeAssetService(); + const eventCollectors = createFakeEventCollectors(); + + await deployAtHead( + { + db: db as never, + sidecarRouter: createFakeSidecarRouter(), + assetService, + sessionService, + eventCollectors, + credentialCipher: {} as never, + toolGrantsForPins: () => [], + pinnedPackageCredentialBindingsFor: async () => [], + }, + { + tenantId: "ten_1", + instanceId: "ins_2", + triggerAddress: "ins_2@ten1.workbench.test", + principalId: "prn_2", + sessionId: "ses_2", + foldedBody: { + ...FOLDED_BODY, + toolPackagePins: [{ name: "@corbits/manus-tools", version: "*" }], + }, + launchLabel: "myra", + }, + ); + + expect(buildCredentialDeliveryCalls).toHaveLength(0); + const deployed = sessionService.adoptedDeployCalls[0] as { + credentials?: unknown; + }; + expect(deployed.credentials).toBeUndefined(); + const entry = + assetService.populateAssetCalls[0]?.tree.files["workflow.js"] ?? ""; + expect(entryDefinition(entry)["credentialBindings"] ?? []).toEqual([]); + }); + + test("does not add a manus binding when manus-tools is not pinned", async () => { + resolveDefinitionSourcesCalls.length = 0; + resolveDefinitionSourcesResult = catalogSources(); + buildCredentialDeliveryCalls.length = 0; + const db = createFakeDb(); + const sessionService = createFakeSessionService(); + const assetService = createFakeAssetService(); + const eventCollectors = createFakeEventCollectors(); + const pinnedPackageCalls: { tenantId: string; pins: unknown }[] = []; + + await deployAtHead( + { + db: db as never, + sidecarRouter: createFakeSidecarRouter(), + assetService, + sessionService, + eventCollectors, + credentialCipher: {} as never, + toolGrantsForPins: () => [], + pinnedPackageCredentialBindingsFor: async (tenantId, pins) => { + pinnedPackageCalls.push({ tenantId, pins }); + return []; + }, + }, + { + tenantId: "ten_1", + instanceId: "ins_3", + triggerAddress: "ins_3@ten1.workbench.test", + principalId: "prn_3", + sessionId: "ses_3", + foldedBody: FOLDED_BODY, + launchLabel: "myra", + }, + ); + + expect(pinnedPackageCalls).toEqual([ + { tenantId: "ten_1", pins: FOLDED_BODY.toolPackagePins }, + ]); + expect(buildCredentialDeliveryCalls).toHaveLength(0); + const entry = + assetService.populateAssetCalls[0]?.tree.files["workflow.js"] ?? ""; + expect(entryDefinition(entry)["credentialBindings"] ?? []).toEqual([]); + }); + + test("skips a pinned-package handle the definition already binds", async () => { + resolveDefinitionSourcesCalls.length = 0; + resolveDefinitionSourcesResult = catalogSources(); + buildCredentialDeliveryCalls.length = 0; + buildCredentialDeliveryResult = { + ok: true, + delivery: { + bindings: [ + { + handle: "manus", + credentialId: "cred_manus_1", + consumer: "tool:@corbits/manus-tools", + }, + ], + materials: [ + { + credentialId: "cred_manus_1", + providerKey: "manus", + origin: "https://api.manus.ai", + secret: "n/a", + }, + ], + }, + }; + + const db = createFakeDb(); + const sessionService = createFakeSessionService(); + const assetService = createFakeAssetService(); + const eventCollectors = createFakeEventCollectors(); + + await deployAtHead( + { + db: db as never, + sidecarRouter: createFakeSidecarRouter(), + assetService, + sessionService, + eventCollectors, + credentialCipher: {} as never, + toolGrantsForPins: () => [], + pinnedPackageCredentialBindingsFor: async () => [MANUS_BINDING], + }, + { + tenantId: "ten_1", + instanceId: "ins_4", + triggerAddress: "ins_4@ten1.workbench.test", + principalId: "prn_4", + sessionId: "ses_4", + foldedBody: { + ...FOLDED_BODY, + toolPackagePins: [{ name: "@corbits/manus-tools", version: "*" }], + credentialBindings: [MANUS_BINDING], + }, + launchLabel: "myra", + }, + ); + + expect(buildCredentialDeliveryCalls).toHaveLength(1); + expect(buildCredentialDeliveryCalls[0]).toMatchObject({ + bindings: [MANUS_BINDING], + }); + const entry = + assetService.populateAssetCalls[0]?.tree.files["workflow.js"] ?? ""; + expect(entryDefinition(entry)["credentialBindings"]).toEqual([ + MANUS_BINDING, + ]); + }); +}); + // CL-6452: a folded run's deployed bytes carry per-run values, so their // wire hash is unique to the run and the deploy's freeze ensures a fresh // definition row over the agent's asset, then repoints the run at it. From 5489911dfa12297c5c84f02eb106566848f080b7 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:59:11 -0700 Subject: [PATCH 07/75] Fold connected pinned-package credentials into launch A pin with no matching binding is inert at tool time. Required assistant binds would throw on first chat, so launch now folds CONNECTOR_REGISTRY-fed bindings for pins the tenant already connected, the same way it already folds MCP server bindings. --- apps/hub/src/index.ts | 8 ++++ ...pinned-package-credential-bindings.test.ts | 41 ++++++++++++++++ .../src/pinned-package-credential-bindings.ts | 48 +++++++++++++++++++ packages/chat/src/platform-adapter.ts | 8 ++++ packages/folded-runs/src/index.ts | 1 + packages/folded-runs/src/launch.ts | 28 +++++++++-- packages/folded-runs/src/types.ts | 28 +++++++++++ 7 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 apps/hub/src/pinned-package-credential-bindings.test.ts create mode 100644 apps/hub/src/pinned-package-credential-bindings.ts diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index 5529ff05a..ccd60f707 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -352,6 +352,7 @@ import { createBootAssetWiring, REGISTRIES } from "./asset-service-factory"; import { createRoutineScheduler } from "./routine-scheduler"; import { createToolGrantsForPins } from "./tool-grants"; import { createMcpCredentialBindingsFor } from "./mcp-credential-bindings"; +import { createPinnedPackageCredentialBindingsFor } from "./pinned-package-credential-bindings"; // Host policy constants, not configuration. const MAX_TARBALL_BYTES = 10 * 1024 * 1024; @@ -710,6 +711,9 @@ export async function createHub(config: HubConfig) { ); // See `./mcp-credential-bindings.ts`'s own doc. const mcpCredentialBindingsFor = createMcpCredentialBindingsFor(db); + // See `./pinned-package-credential-bindings.ts`'s own doc. + const pinnedPackageCredentialBindingsFor = + createPinnedPackageCredentialBindingsFor(db); const sidecarRouter = createSidecarRouter({ hubPublicKey, authenticateSidecar: createSidecarTokenAuthenticator({ db }), @@ -1291,6 +1295,7 @@ export async function createHub(config: HubConfig) { credentialCipher, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, // Chat residents are undeployed on idle again (see the comment above // this function): `chatIdleReapMs` (env-overridable via // `WORKBENCH_CHAT_IDLE_REAP_MS`, default 30 minutes) is @@ -1997,6 +2002,7 @@ export async function createHub(config: HubConfig) { eventCollectors, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, cryptoProviderCache: foldedRunCryptoProviders, launchMode: AGENT_SECTION_MODE, persistLaunch: workbenchLaunchPersistExtra, @@ -2478,6 +2484,7 @@ export async function createHub(config: HubConfig) { hubPublicKey, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, }; // Every genuine top-level deployment run, folded runs (workbench hosts, @@ -2668,6 +2675,7 @@ export async function createHub(config: HubConfig) { credentialCipher, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, cryptoProviderCache: foldedRunCryptoProviders, joinDeliveryWorkbench: (input) => joinRunParticipant({ store: chatStore }, input), diff --git a/apps/hub/src/pinned-package-credential-bindings.test.ts b/apps/hub/src/pinned-package-credential-bindings.test.ts new file mode 100644 index 000000000..24cbfe836 --- /dev/null +++ b/apps/hub/src/pinned-package-credential-bindings.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from "bun:test"; +import { bindingsForConnectedPins } from "./pinned-package-credential-bindings"; + +const MANUS_PIN = { name: "@corbits/manus-tools", version: "*" }; +const GRANOLA_PIN = { name: "@corbits/granola-tools", version: "*" }; + +describe("bindingsForConnectedPins", () => { + test("emits a manus tenant binding when manus-tools is pinned and Manus is connected", () => { + expect(bindingsForConnectedPins([MANUS_PIN], ["manus"])).toEqual([ + { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant", + }, + ]); + }); + + test("returns none when manus-tools is pinned but Manus is not connected", () => { + expect(bindingsForConnectedPins([MANUS_PIN], ["granola"])).toEqual([]); + }); + + test("returns none when Manus is connected but manus-tools is not pinned", () => { + expect(bindingsForConnectedPins([GRANOLA_PIN], ["manus"])).toEqual([]); + }); + + test("emits a granola binding when granola-tools is pinned and Granola is connected", () => { + expect(bindingsForConnectedPins([GRANOLA_PIN], ["granola"])).toEqual([ + { + package: "@corbits/granola-tools", + handle: "granola", + provider: "granola", + locator: "tenant", + }, + ]); + }); + + test("returns none for empty pins even when connectors are connected", () => { + expect(bindingsForConnectedPins([], ["manus", "granola"])).toEqual([]); + }); +}); diff --git a/apps/hub/src/pinned-package-credential-bindings.ts b/apps/hub/src/pinned-package-credential-bindings.ts new file mode 100644 index 000000000..bfcba09c1 --- /dev/null +++ b/apps/hub/src/pinned-package-credential-bindings.ts @@ -0,0 +1,48 @@ +// The `PinnedPackageCredentialBindingsFor` port every `FoldedRunsDeps` +// below is wired with — see `@corbits/folded-runs`' `types.ts` for why +// this has to be supplied by the composition root rather than declared as +// a required assistant `credentialBindings` entry. Static-handle packages +// (`@corbits/manus-tools`, granola-tools, …) declare +// `interchange.credentials`, but requiring those binds on the assistant +// would throw `MissingCredentialError` on signup / first chat. This +// factory emits a tenant binding only when a pin names a package a +// `CONNECTOR_REGISTRY` entry `feedsTools` AND the tenant already has a +// connected credential for that connector (`listConnectedProviders`). +import type { DB } from "@intx/db"; +import type { CredentialBinding } from "@intx/types"; +import type { ToolPackagePin } from "@intx/types/tool-packages"; +import type { PinnedPackageCredentialBindingsFor } from "@corbits/folded-runs"; +import { listConnectedProviders } from "@corbits/chat"; +import { CONNECTOR_REGISTRY } from "@workbench/connections/registry"; + +export function bindingsForConnectedPins( + pins: readonly ToolPackagePin[], + connectedConnectorIds: readonly string[], +): readonly CredentialBinding[] { + const pinNames = new Set(pins.map((pin) => pin.name)); + if (pinNames.size === 0) return []; + const connected = new Set(connectedConnectorIds); + const bindings: CredentialBinding[] = []; + for (const descriptor of Object.values(CONNECTOR_REGISTRY)) { + if (!connected.has(descriptor.id)) continue; + for (const toolPackageName of descriptor.feedsTools) { + if (!pinNames.has(toolPackageName)) continue; + bindings.push({ + package: toolPackageName, + handle: descriptor.id, + provider: descriptor.id, + locator: "tenant", + }); + } + } + return bindings; +} + +export function createPinnedPackageCredentialBindingsFor( + db: DB["db"], +): PinnedPackageCredentialBindingsFor { + return async (tenantId, pins) => { + const connected = await listConnectedProviders(db, tenantId); + return bindingsForConnectedPins(pins, connected); + }; +} diff --git a/packages/chat/src/platform-adapter.ts b/packages/chat/src/platform-adapter.ts index ba8ab665f..ae2ceb041 100644 --- a/packages/chat/src/platform-adapter.ts +++ b/packages/chat/src/platform-adapter.ts @@ -76,6 +76,8 @@ export type CreateHubChatPlatformDeps = { toolGrantsForPins: FoldedRunsDeps["toolGrantsForPins"]; /** See `FoldedRunsDeps.mcpCredentialBindingsFor`. */ mcpCredentialBindingsFor?: FoldedRunsDeps["mcpCredentialBindingsFor"]; + /** See `FoldedRunsDeps.pinnedPackageCredentialBindingsFor`. */ + pinnedPackageCredentialBindingsFor?: FoldedRunsDeps["pinnedPackageCredentialBindingsFor"]; /** * Decrypts credential secrets when an invited agent's launch resolves * inference sources against the tenant catalog — see @@ -207,6 +209,12 @@ export function createHubChatPlatform( ...(deps.mcpCredentialBindingsFor !== undefined ? { mcpCredentialBindingsFor: deps.mcpCredentialBindingsFor } : {}), + ...(deps.pinnedPackageCredentialBindingsFor !== undefined + ? { + pinnedPackageCredentialBindingsFor: + deps.pinnedPackageCredentialBindingsFor, + } + : {}), }; const cryptoProviders = createCryptoProviderCache(); diff --git a/packages/folded-runs/src/index.ts b/packages/folded-runs/src/index.ts index 5f061f1a9..5519fd370 100644 --- a/packages/folded-runs/src/index.ts +++ b/packages/folded-runs/src/index.ts @@ -1,6 +1,7 @@ export type { FoldedRunsDeps, McpCredentialBindingsFor, + PinnedPackageCredentialBindingsFor, PinnedToolGrantDeclaration, ToolGrantsForPins, SentFoldedMail, diff --git a/packages/folded-runs/src/launch.ts b/packages/folded-runs/src/launch.ts index 1d6f0e551..cf621d8fc 100644 --- a/packages/folded-runs/src/launch.ts +++ b/packages/folded-runs/src/launch.ts @@ -245,6 +245,7 @@ export async function deployAtHead( | "assetService" | "toolGrantsForPins" | "mcpCredentialBindingsFor" + | "pinnedPackageCredentialBindingsFor" >, params: { tenantId: string; @@ -397,9 +398,29 @@ export async function deployAtHead( isMcpToolsPin && deps.mcpCredentialBindingsFor !== undefined ? await deps.mcpCredentialBindingsFor(params.tenantId) : []; + // Static-handle packages (`@corbits/manus-tools`, granola-tools, …) declare + // `interchange.credentials`, but the assistant does not require those + // bindings — a required bind would throw MissingCredentialError on first + // chat. When this port is supplied, fold in only the bindings for pins + // whose connector the tenant already has, skipping handles the definition + // itself already bound. + const pinnedPackageBindings: readonly CredentialBinding[] = + deps.pinnedPackageCredentialBindingsFor !== undefined + ? await deps.pinnedPackageCredentialBindingsFor( + params.tenantId, + params.foldedBody.toolPackagePins, + ) + : []; + const definedHandles = new Set( + params.foldedBody.credentialBindings.map((binding) => binding.handle), + ); + const extraPinnedBindings = pinnedPackageBindings.filter( + (binding) => !definedHandles.has(binding.handle), + ); const credentialBindings = [ ...params.foldedBody.credentialBindings, ...mcpBindings, + ...extraPinnedBindings, ]; // The deploy front resolves the credential MATERIAL itself from the @@ -464,9 +485,10 @@ export async function deployAtHead( // The definition's own `credentialBindings` are what the workflow // host's per-step credential snapshot // (`vendor/intx/workflow-host/src/supervisor/credentials.ts`) derives - // its consumer bindings from, which is why the pinned-package MCP - // bindings folded in above have to reach the rendered config and not - // just the delivery: without them `env.credentials.resolve("mcp.")` + // its consumer bindings from, which is why the pinned-package bindings + // folded in above — MCP `mcp.` handles and static connector + // handles such as `manus` — have to reach the rendered config and not + // just the delivery: without them `env.credentials.resolve(...)` // fails "not connected" even when the material was delivered. const runtimeConfig: AgentRuntimeConfig = { workflowId: `wf_${params.instanceId}`, diff --git a/packages/folded-runs/src/types.ts b/packages/folded-runs/src/types.ts index f1b47c1e5..5ff0efeff 100644 --- a/packages/folded-runs/src/types.ts +++ b/packages/folded-runs/src/types.ts @@ -80,6 +80,28 @@ export type McpCredentialBindingsFor = ( tenantId: string, ) => Promise; +/** + * Derives extra credential bindings for a folded run's pinned tool packages + * whose handles are static (known at package-publish time) but whose + * workflow definition does not require them. A required assistant binding + * would throw `MissingCredentialError` on signup / first chat when the + * tenant has not connected the provider; a pin with no matching binding is + * otherwise inert at tool time (`env.credentials.resolve(handle)` fails + * "not connected" even when Settings already has the key). + * + * `deployAtHead` calls this whenever it is supplied, with the launch's + * `toolPackagePins`, and concatenates the result onto the definition's own + * bindings (skipping handles already present). The composition root + * (`apps/hub`) supplies the real implementation from + * `CONNECTOR_REGISTRY.feedsTools` plus the tenant's connected providers — + * `folded-runs` never imports that registry itself. Optional: a caller that + * never pins a connector-fed package has no need to supply it. + */ +export type PinnedPackageCredentialBindingsFor = ( + tenantId: string, + pins: readonly ToolPackagePin[], +) => Promise; + export type FoldedRunsDeps = { db: DB["db"]; /** @@ -112,6 +134,12 @@ export type FoldedRunsDeps = { * composition today) has no need to supply it. */ mcpCredentialBindingsFor?: McpCredentialBindingsFor; + /** + * See `PinnedPackageCredentialBindingsFor`'s own doc. Optional: a caller + * that never pins a connector-fed package (granola-tools, manus-tools, …) + * has no need to supply it. + */ + pinnedPackageCredentialBindingsFor?: PinnedPackageCredentialBindingsFor; }; export type SentFoldedMail = { From f71388cc14714ac95fb9eb448963e43af028f5a6 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:59:31 -0700 Subject: [PATCH 08/75] Name Manus in probes, assistant pins, and credential-wiring docs The probes header still listed four connectors, the assistant pin comment still counted four manager-tools bundles, and credential-wiring said four sidecar plugins while five are registered. --- docs/credential-wiring.md | 10 ++++++++-- packages/connections/src/probes.ts | 2 +- workflows/assistant/src/index.ts | 11 +++++++---- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/credential-wiring.md b/docs/credential-wiring.md index 8cf35968f..e0c71a6e5 100644 --- a/docs/credential-wiring.md +++ b/docs/credential-wiring.md @@ -56,9 +56,15 @@ registers: `x-manus-api-key`. A Manus provider row MUST set this plugin -- seeding it as `"http"` or `"http-x-api-key"` sends the wrong header name and Manus rejects the call. +- **`mcp-streamable-http`** -- `@corbits/credential-providers`'s + `createMcpStreamableHttpCredentialProvider`. For a token-bearing MCP + server it sends `authorization: Bearer `; for a keyless one + (`MCP_NO_TOKEN_SENTINEL`) it sends no authorization header. The vendored + `http` plugin cannot express the keyless case. -All four plugins mirror the same origin-pinning and `redirect: "manual"` -protections; only the injected header differs. +All five plugins the sidecar registers mirror the same origin-pinning and +`redirect: "manual"` protections; only the injected header (or its +absence, for keyless MCP) differs. `packages/connections` (the Connections-surface registry) is the other place this plugin id needs to be correct: whatever seeds or registers a diff --git a/packages/connections/src/probes.ts b/packages/connections/src/probes.ts index fefec4ab9..a1fb426d3 100644 --- a/packages/connections/src/probes.ts +++ b/packages/connections/src/probes.ts @@ -1,5 +1,5 @@ // Real, free credential probes for the tool connectors this ticket -// adds — Granola, Exa, ScrapeCreators, Linear, and GitHub — each hitting the +// adds — Granola, Exa, ScrapeCreators, Linear, GitHub, and Manus — each hitting the // same production endpoint its tool client (`packages/*-tools/src/ // client.ts`) already calls, authenticated with the real key. This // mirrors `@workbench/hub-client/credential-test`'s diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index da9ebbaf0..1588e52be 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -31,14 +31,17 @@ export const ASSISTANT_STEP_ID = "assistant"; /** * The tool packages this deployment pins. `@corbits/memory-tools` - * (CL-5852) is the original pin; `@corbits/capability-tools` - * (CL-6084/CL-6086) lets Myra self-service a missing tool, skill, or - * model; the remaining four are the manager-tools bundles giving Myra + * is the original pin; `@corbits/capability-tools` lets Myra self-service + * a missing tool, skill, or model; the manager-tools bundles give Myra * real workbench-management capability — a specialist agent she can * create and invite in, this workbench's routines, connection * visibility, and skill capture — each a thin wrapper over an existing * platform primitive (see each package's own file-header comment for - * which one). + * which one). `@corbits/mcp-tools` and `@corbits/interaction-tools` + * expose tenant-connected MCP servers and the ask-user card; + * `@corbits/manus-tools` is pinned so Manus tools exist when the tenant + * has connected Manus (launch folds the binding only then — the pin + * itself does not require a credential). */ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/memory-tools", version: "0.0.4" }, From 65a90102f4434ed815cd996cba8e8605f98a136a Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:18:30 -0700 Subject: [PATCH 09/75] Add factory tests for pinned-package connector credentials The factory currently lists model catalog providers, so a connected Manus key never emits a binding. These cases pin the owning check: a live Manus connector plus a manus-tools pin binds, while a catalog-only Anthropic connection does not. --- ...pinned-package-credential-bindings.test.ts | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/apps/hub/src/pinned-package-credential-bindings.test.ts b/apps/hub/src/pinned-package-credential-bindings.test.ts index 24cbfe836..96a3c59ba 100644 --- a/apps/hub/src/pinned-package-credential-bindings.test.ts +++ b/apps/hub/src/pinned-package-credential-bindings.test.ts @@ -1,5 +1,8 @@ import { describe, expect, test } from "bun:test"; -import { bindingsForConnectedPins } from "./pinned-package-credential-bindings"; +import { + bindingsForConnectedPins, + createPinnedPackageCredentialBindingsFor, +} from "./pinned-package-credential-bindings"; const MANUS_PIN = { name: "@corbits/manus-tools", version: "*" }; const GRANOLA_PIN = { name: "@corbits/granola-tools", version: "*" }; @@ -39,3 +42,26 @@ describe("bindingsForConnectedPins", () => { expect(bindingsForConnectedPins([], ["manus", "granola"])).toEqual([]); }); }); + +describe("createPinnedPackageCredentialBindingsFor", () => { + test("emits a manus tenant binding when isConnectorConnected is true for manus", async () => { + const bindingsFor = createPinnedPackageCredentialBindingsFor( + async (_tenantId, connectorId) => connectorId === "manus", + ); + expect(await bindingsFor("tenant-1", [MANUS_PIN])).toEqual([ + { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant", + }, + ]); + }); + + test("emits none when only a catalog-style inference connector is connected", async () => { + const bindingsFor = createPinnedPackageCredentialBindingsFor( + async (_tenantId, connectorId) => connectorId === "anthropic", + ); + expect(await bindingsFor("tenant-1", [MANUS_PIN])).toEqual([]); + }); +}); From 63fe2a9e51fdb75ed606e5a3e9afc43d73803f57 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:19:23 -0700 Subject: [PATCH 10/75] Resolve pinned-package credentials via connector ownership MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit listConnectedProviders only sees model catalog rows, so a pasted Manus key never folded a tenant binding at launch. Ask isConnectorConnected instead — the same resolveCredentialRequirement check GET /connections already uses. --- apps/hub/src/index.ts | 30 ++++++++++--------- .../src/pinned-package-credential-bindings.ts | 25 ++++++++++++---- 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index ccd60f707..f9175a7d5 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -711,9 +711,20 @@ export async function createHub(config: HubConfig) { ); // See `./mcp-credential-bindings.ts`'s own doc. const mcpCredentialBindingsFor = createMcpCredentialBindingsFor(db); - // See `./pinned-package-credential-bindings.ts`'s own doc. + // Same owning check GET /connections uses — see + // `@workbench/connections`' `workflow-connection-routes.ts` and the + // `createWorkflowConnectionRoutes` wiring below. Not + // `listConnectedProviders` (catalog-only). + const isConnectorConnected = async (tenantId: string, connectorId: string) => + (await resolveCredentialRequirement( + db, + tenantId, + { providerName: connectorId, source: "tenant" }, + null, + null, + )) !== null; const pinnedPackageCredentialBindingsFor = - createPinnedPackageCredentialBindingsFor(db); + createPinnedPackageCredentialBindingsFor(isConnectorConnected); const sidecarRouter = createSidecarRouter({ hubPublicKey, authenticateSidecar: createSidecarTokenAuthenticator({ db }), @@ -2405,18 +2416,9 @@ export async function createHub(config: HubConfig) { "/api/workflow-connections", createWorkflowConnectionRoutes({ authenticator: createWorkflowRunAuthenticator({ db }), - // The same resolution `buildCredentialDelivery` uses at agent-launch - // time to decide whether a tool actually gets a credential — so - // `list_connections` reports exactly what an agent could really use, - // for an inference provider and a tool connector alike (CL-6492). - isConnectorConnected: async (tenantId, connectorId) => - (await resolveCredentialRequirement( - db, - tenantId, - { providerName: connectorId, source: "tenant" }, - null, - null, - )) !== null, + // Same `isConnectorConnected` the pinned-package factory is wired + // with above (CL-6492). + isConnectorConnected, listMcpServers: (tenantId) => listMcpServerConnections(db, tenantId), }), ); diff --git a/apps/hub/src/pinned-package-credential-bindings.ts b/apps/hub/src/pinned-package-credential-bindings.ts index bfcba09c1..f3893abcc 100644 --- a/apps/hub/src/pinned-package-credential-bindings.ts +++ b/apps/hub/src/pinned-package-credential-bindings.ts @@ -7,14 +7,19 @@ // would throw `MissingCredentialError` on signup / first chat. This // factory emits a tenant binding only when a pin names a package a // `CONNECTOR_REGISTRY` entry `feedsTools` AND the tenant already has a -// connected credential for that connector (`listConnectedProviders`). -import type { DB } from "@intx/db"; +// connected credential for that connector (`isConnectorConnected`, the +// same owning check `createWorkflowConnectionRoutes` uses — not +// `@corbits/chat`'s catalog-only `listConnectedProviders`). import type { CredentialBinding } from "@intx/types"; import type { ToolPackagePin } from "@intx/types/tool-packages"; import type { PinnedPackageCredentialBindingsFor } from "@corbits/folded-runs"; -import { listConnectedProviders } from "@corbits/chat"; import { CONNECTOR_REGISTRY } from "@workbench/connections/registry"; +export type IsConnectorConnected = ( + tenantId: string, + connectorId: string, +) => Promise; + export function bindingsForConnectedPins( pins: readonly ToolPackagePin[], connectedConnectorIds: readonly string[], @@ -39,10 +44,18 @@ export function bindingsForConnectedPins( } export function createPinnedPackageCredentialBindingsFor( - db: DB["db"], + isConnectorConnected: IsConnectorConnected, ): PinnedPackageCredentialBindingsFor { return async (tenantId, pins) => { - const connected = await listConnectedProviders(db, tenantId); - return bindingsForConnectedPins(pins, connected); + const pinNames = new Set(pins.map((pin) => pin.name)); + if (pinNames.size === 0) return []; + const connectedConnectorIds: string[] = []; + for (const descriptor of Object.values(CONNECTOR_REGISTRY)) { + if (!descriptor.feedsTools.some((name) => pinNames.has(name))) continue; + if (await isConnectorConnected(tenantId, descriptor.id)) { + connectedConnectorIds.push(descriptor.id); + } + } + return bindingsForConnectedPins(pins, connectedConnectorIds); }; } From 92c289102d9b382543398fe6e760fcae5e405ace Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:26:17 -0700 Subject: [PATCH 11/75] Bump @corbits/manus-tools after source changes --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index ffd17b9af..6cacf236a 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.1", + "version": "0.0.2", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 1588e52be..d38e510c0 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.1" }, + { name: "@corbits/manus-tools", version: "0.0.2" }, ]; /** From 363027b9f7b16bb8b9d0e020c1840454fb91657e Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:34:49 -0700 Subject: [PATCH 12/75] Stop pinning manus-tools version in its manifest test --- packages/manus-tools/src/manifest.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/manus-tools/src/manifest.test.ts b/packages/manus-tools/src/manifest.test.ts index 0f36b5454..55d82b5c9 100644 --- a/packages/manus-tools/src/manifest.test.ts +++ b/packages/manus-tools/src/manifest.test.ts @@ -18,5 +18,4 @@ test("declares exactly one credential handle: manus", () => { throw new Error(parsed.summary); } expect(parsed.interchange?.credentials).toEqual([{ handle: "manus" }]); - expect(parsed.version).toBe("0.0.1"); }); From 51e6af1bbd9ee86d5f17baea61fac196b8b7d677 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:42:51 -0700 Subject: [PATCH 13/75] Bump @corbits/manus-tools after the manifest test change --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 6cacf236a..67c50ef44 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.2", + "version": "0.0.3", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index d38e510c0..48a12734e 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.2" }, + { name: "@corbits/manus-tools", version: "0.0.3" }, ]; /** From 2e391c75fd33767c87512e6ba4147783d6f58e7e Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:29:50 -0700 Subject: [PATCH 14/75] Add tests for Manus task skill and ContentPart fields --- packages/manus-tools/src/client.test.ts | 102 +++++++++++++++++- packages/manus-tools/src/tool.test.ts | 134 +++++++++++++++++++++++- 2 files changed, 230 insertions(+), 6 deletions(-) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index ae8b42e6f..6ceea6f58 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -42,12 +42,58 @@ test("createTask posts to /v2/task.create and parses the ok envelope", async () expect(captured.headers?.get("authorization")).toBeNull(); expect(captured.headers?.get("x-api-key")).toBeNull(); expect(JSON.parse(captured.body)).toEqual({ - message: { content: "Make slides" }, + message: { content: [{ type: "text", text: "Make slides" }] }, }); expect(created.task_id).toBe("task_1"); expect(created.task_url).toBe("https://manus.im/app/task_1"); }); +test("createTask posts skill, connector, and schema fields only when set", async () => { + const captured: { body: string } = { body: "" }; + const fetchImpl = (async (_input: URL | string, init?: RequestInit) => { + captured.body = typeof init?.body === "string" ? init.body : ""; + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_2", + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await createTask( + { fetchImpl }, + { + content: "Use the listed skill", + enable_skills: ["skill_abc"], + force_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + structured_output_schema: { + type: "object", + properties: { title: { type: "string" } }, + required: ["title"], + additionalProperties: false, + }, + }, + ); + expect(JSON.parse(captured.body)).toEqual({ + message: { + content: [{ type: "text", text: "Use the listed skill" }], + enable_skills: ["skill_abc"], + force_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + }, + structured_output_schema: { + type: "object", + properties: { title: { type: "string" } }, + required: ["title"], + additionalProperties: false, + }, + }); +}); + test("listTaskMessages GETs /v2/task.listMessages without an auth header", async () => { const captured: { url: string; headers: Headers | null } = { url: "", @@ -128,8 +174,13 @@ test("createSlideDeck treats mixed [stopped, running] desc as terminal", async ( JSON.parse(typeof init?.body === "string" ? init.body : ""), ).toEqual({ message: { - content: - "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + content: [ + { + type: "text", + text: + "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + }, + ], }, }); return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { @@ -277,3 +328,48 @@ test("default slide-deck wait is several minutes", () => { 5 * 60 * 1000, ); }); + +test("createSlideDeck forwards optional skill fields on create", async () => { + let createBody = ""; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + createBody = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await createSlideDeck( + { fetchImpl }, + { + content: "Onboarding", + enable_skills: ["skill_slides"], + force_skills: ["skill_slides"], + pollIntervalMs: 0, + maxPolls: 1, + }, + ); + const body = JSON.parse(createBody) as { + message: { + enable_skills?: string[]; + force_skills?: string[]; + }; + }; + expect(body.message.enable_skills).toEqual(["skill_slides"]); + expect(body.message.force_skills).toEqual(["skill_slides"]); +}); diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index 9fd80fe37..56ef6153d 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -122,11 +122,18 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio if (url.includes("/v2/task.create")) { expect(init?.method).toBe("POST"); const body = JSON.parse(typeof init?.body === "string" ? init.body : ""); - expect(body.message.content).toContain("slide presentation"); - expect(body.message.content).toContain("pptx"); - expect(body.message.content).toContain( + expect(body.message.content).toEqual([ + expect.objectContaining({ + type: "text", + }), + ]); + expect(body.message.content[0].text).toContain("slide presentation"); + expect(body.message.content[0].text).toContain("pptx"); + expect(body.message.content[0].text).toContain( "Make a five-slide deck about onboarding", ); + expect(body.message.enable_skills).toBeUndefined(); + expect(body.message.force_skills).toBeUndefined(); return new Response( JSON.stringify({ ok: true, @@ -234,3 +241,124 @@ test("degrades to an error result (never throws) when the underlying call fails" globalThis.fetch = originalFetch; } }); + +test("task_create and task_send_msg expose skill and connector fields", () => { + const create = MANUS_ENDPOINTS.find((spec) => spec.name === "task_create"); + const send = MANUS_ENDPOINTS.find((spec) => spec.name === "task_send_msg"); + for (const spec of [create, send]) { + expect(spec?.properties["enable_skills"]?.type).toBe("array"); + expect(spec?.properties["force_skills"]?.type).toBe("array"); + expect(spec?.properties["connectors"]?.type).toBe("array"); + expect(spec?.properties["task_references"]?.type).toBe("array"); + } + expect(create?.properties["structured_output_schema"]?.type).toBe("object"); + expect(send?.properties["structured_output_schema"]).toBeUndefined(); +}); + +test("task_create omits skill fields unless the assistant passes ids", async () => { + const originalFetch = globalThis.fetch; + let createBody = ""; + globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { + createBody = typeof init?.body === "string" ? init.body : ""; + return new Response( + JSON.stringify({ ok: true, task_id: "task_1" }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const omitted = await bundle.run( + { + id: "call_create", + name: "task_create", + arguments: { content: "Hello" }, + }, + new AbortController().signal, + ); + expect(omitted.isError).toBeUndefined(); + expect(JSON.parse(createBody)).toEqual({ + message: { content: [{ type: "text", text: "Hello" }] }, + }); + + const present = await bundle.run( + { + id: "call_create_skills", + name: "task_create", + arguments: { + content: "Hello with skills", + enable_skills: ["skill_abc"], + force_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + structured_output_schema: { type: "object" }, + }, + }, + new AbortController().signal, + ); + expect(present.isError).toBeUndefined(); + expect(JSON.parse(createBody)).toEqual({ + message: { + content: [{ type: "text", text: "Hello with skills" }], + enable_skills: ["skill_abc"], + force_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + }, + structured_output_schema: { type: "object" }, + }); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("task_send_msg posts ContentPart content and optional skill fields", async () => { + const originalFetch = globalThis.fetch; + let sendBody = ""; + globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { + sendBody = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true }), { status: 200 }); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const omitted = await bundle.run( + { + id: "call_send", + name: "task_send_msg", + arguments: { task_id: "task_1", content: "Follow up" }, + }, + new AbortController().signal, + ); + expect(omitted.isError).toBeUndefined(); + expect(JSON.parse(sendBody)).toEqual({ + task_id: "task_1", + message: { content: [{ type: "text", text: "Follow up" }] }, + }); + + const present = await bundle.run( + { + id: "call_send_skills", + name: "task_send_msg", + arguments: { + task_id: "task_1", + content: "Follow up with skills", + enable_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + }, + }, + new AbortController().signal, + ); + expect(present.isError).toBeUndefined(); + expect(JSON.parse(sendBody)).toEqual({ + task_id: "task_1", + message: { + content: [{ type: "text", text: "Follow up with skills" }], + enable_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + }, + }); + } finally { + globalThis.fetch = originalFetch; + } +}); From 4e42c5db38a06937d6fa2a063c2862ce0c96bf32 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:32:02 -0700 Subject: [PATCH 15/75] Wire Manus task messages as ContentPart with optional skills --- packages/manus-tools/src/client.ts | 58 ++++++++++++++- packages/manus-tools/src/index.ts | 4 ++ packages/manus-tools/src/tool.ts | 111 +++++++++++++++++++++++++++-- 3 files changed, 168 insertions(+), 5 deletions(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index c46a72f27..f4fe0d5b7 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -198,14 +198,67 @@ export type CreateTaskParams = { readonly hide_in_task_list?: boolean; readonly share_visibility?: string; readonly agent_profile?: string; + readonly enable_skills?: readonly string[]; + readonly force_skills?: readonly string[]; + readonly connectors?: readonly string[]; + readonly task_references?: readonly string[]; + readonly structured_output_schema?: Readonly>; }; +export type TaskTextContentPart = { + readonly type: "text"; + readonly text: string; +}; + +export type TaskMessageSkillFields = { + readonly enable_skills?: readonly string[]; + readonly force_skills?: readonly string[]; + readonly connectors?: readonly string[]; + readonly task_references?: readonly string[]; +}; + +export type TaskMessageBody = { + readonly content: readonly TaskTextContentPart[]; +} & TaskMessageSkillFields; + +/** + * Builds the v2 `message` object: prompt as a ContentPart array, with + * skill/connector/reference arrays omitted when unset. + */ +export function buildTaskMessage( + content: string, + fields?: TaskMessageSkillFields, +): TaskMessageBody { + const message: { + content: readonly TaskTextContentPart[]; + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + } = { + content: [{ type: "text", text: content }], + }; + if (fields?.enable_skills !== undefined) { + message.enable_skills = fields.enable_skills; + } + if (fields?.force_skills !== undefined) { + message.force_skills = fields.force_skills; + } + if (fields?.connectors !== undefined) { + message.connectors = fields.connectors; + } + if (fields?.task_references !== undefined) { + message.task_references = fields.task_references; + } + return message; +} + export async function createTask( config: ManusClientConfig, params: CreateTaskParams, ): Promise { const body: Record = { - message: { content: params.content }, + message: buildTaskMessage(params.content, params), }; if (params.title !== undefined) body["title"] = params.title; if (params.project_id !== undefined) body["project_id"] = params.project_id; @@ -222,6 +275,9 @@ export async function createTask( if (params.agent_profile !== undefined) { body["agent_profile"] = params.agent_profile; } + if (params.structured_output_schema !== undefined) { + body["structured_output_schema"] = params.structured_output_schema; + } const raw = await manusRequest(config, { method: "POST", path: "/v2/task.create", diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index 7013c25b1..c3eb3f291 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -1,6 +1,7 @@ export { CreateTaskResponse, ListMessagesResponse, + buildTaskMessage, createSlideDeck, createTask, extractOutputFiles, @@ -20,6 +21,9 @@ export type { OutputFile, TaskAttachment, TaskEvent, + TaskMessageBody, + TaskMessageSkillFields, + TaskTextContentPart, } from "./client"; export { CREATE_SLIDES_TOOL, diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index 4f9ab756e..e330433a7 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -7,6 +7,7 @@ import type { CredentialCapability } from "@intx/types"; import type { ToolCall, ToolResult } from "@intx/types/runtime"; import { + buildTaskMessage, createSlideDeck, createTask, listTaskMessages, @@ -25,6 +26,7 @@ export const CREATE_SLIDES_TOOL = "create_slides"; type JsonSchemaProperty = { readonly type: string; readonly description: string; + readonly items?: { readonly type: string }; }; type EndpointSpec = { @@ -52,6 +54,26 @@ const OBJECT = (description: string): JsonSchemaProperty => ({ type: "object", description, }); +const STRING_ARRAY = (description: string): JsonSchemaProperty => ({ + type: "array", + description, + items: { type: "string" }, +}); + +const MESSAGE_SKILL_PROPERTIES = { + enable_skills: STRING_ARRAY( + "Skill ids from skill_list to make available. If omitted, the account default skills are used.", + ), + force_skills: STRING_ARRAY( + "Skill ids the agent must invoke. Forced skills are available even when not listed in enable_skills.", + ), + connectors: STRING_ARRAY( + "Connector ids from connector_list to attach to this message.", + ), + task_references: STRING_ARRAY( + "Task ids (up to 20) the agent may browse. Pass the 22-character id, not a URL.", + ), +} as const; export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ { @@ -59,7 +81,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ method: "POST", path: "/v2/task.create", description: - "Creates a Manus task. Pass content as the prompt text (sent as message.content). Poll task_list_msgs for progress.", + "Creates a Manus task. Pass content as the prompt text (sent as message.content ContentPart text). Poll task_list_msgs for progress. Pass skill ids from skill_list via enable_skills or force_skills.", required: ["content"], properties: { content: STRING("Prompt text that starts the task."), @@ -74,6 +96,10 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ ), share_visibility: STRING("private, team, or public."), agent_profile: STRING("manus-1.6, manus-1.6-lite, or manus-1.6-max."), + ...MESSAGE_SKILL_PROPERTIES, + structured_output_schema: OBJECT( + "JSON Schema for structured output extraction. Sent on the create body, not inside message.", + ), }, }, { @@ -135,12 +161,16 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ name: "task_send_msg", method: "POST", path: "/v2/task.sendMessage", - description: "Sends a follow-up message to an existing Manus task.", + description: + "Sends a follow-up message to an existing Manus task. Pass skill ids from skill_list via enable_skills or force_skills.", required: ["task_id", "content"], properties: { task_id: STRING("Task id."), - content: STRING("Follow-up prompt text (sent as message.content)."), + content: STRING( + "Follow-up prompt text (sent as message.content ContentPart text).", + ), agent_profile: STRING("Optional agent profile override."), + ...MESSAGE_SKILL_PROPERTIES, }, }, { @@ -507,7 +537,7 @@ async function runEndpoint( } const body: Record = { task_id: taskId, - message: { content }, + message: buildTaskMessage(content, messageSkillFields(call)), }; const profile = stringArg(call, "agent_profile"); if (profile !== undefined) body["agent_profile"] = profile; @@ -561,6 +591,11 @@ function optionalCreateFields(call: ToolCall): { hide_in_task_list?: boolean; share_visibility?: string; agent_profile?: string; + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + structured_output_schema?: Readonly>; } { const fields: { title?: string; @@ -570,6 +605,11 @@ function optionalCreateFields(call: ToolCall): { hide_in_task_list?: boolean; share_visibility?: string; agent_profile?: string; + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + structured_output_schema?: Readonly>; } = {}; const title = stringArg(call, "title"); if (title !== undefined) fields.title = title; @@ -587,6 +627,69 @@ function optionalCreateFields(call: ToolCall): { if (visibility !== undefined) fields.share_visibility = visibility; const profile = stringArg(call, "agent_profile"); if (profile !== undefined) fields.agent_profile = profile; + const skills = messageSkillFields(call); + if (skills.enable_skills !== undefined) { + fields.enable_skills = skills.enable_skills; + } + if (skills.force_skills !== undefined) { + fields.force_skills = skills.force_skills; + } + if (skills.connectors !== undefined) { + fields.connectors = skills.connectors; + } + if (skills.task_references !== undefined) { + fields.task_references = skills.task_references; + } + const schema = objectArg(call, "structured_output_schema"); + if (schema !== undefined) fields.structured_output_schema = schema; + return fields; +} + +function stringArrayArg( + call: ToolCall, + key: string, +): readonly string[] | undefined { + const value = call.arguments[key]; + if (!Array.isArray(value)) return undefined; + if (!value.every((item) => typeof item === "string")) return undefined; + return value; +} + +function objectArg( + call: ToolCall, + key: string, +): Readonly> | undefined { + const value = call.arguments[key]; + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return undefined; + } + const record: Record = {}; + for (const [field, fieldValue] of Object.entries(value)) { + record[field] = fieldValue; + } + return record; +} + +function messageSkillFields(call: ToolCall): { + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; +} { + const fields: { + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + } = {}; + const enableSkills = stringArrayArg(call, "enable_skills"); + if (enableSkills !== undefined) fields.enable_skills = enableSkills; + const forceSkills = stringArrayArg(call, "force_skills"); + if (forceSkills !== undefined) fields.force_skills = forceSkills; + const connectors = stringArrayArg(call, "connectors"); + if (connectors !== undefined) fields.connectors = connectors; + const taskReferences = stringArrayArg(call, "task_references"); + if (taskReferences !== undefined) fields.task_references = taskReferences; return fields; } From f08a9e360051dc3ad1f7a73fbbf8cbd0bf85ec50 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:32:19 -0700 Subject: [PATCH 16/75] Bump @corbits/manus-tools after skill field wiring --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 67c50ef44..e05e742ad 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.3", + "version": "0.0.4", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 48a12734e..22b67853f 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.3" }, + { name: "@corbits/manus-tools", version: "0.0.4" }, ]; /** From 7d5ff8d9a11d966435e9923485194c8de785c9c0 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:34:36 -0700 Subject: [PATCH 17/75] Add tests for Manus slide-deck lite agent profile --- packages/manus-tools/src/client.test.ts | 64 +++++++++++++++++++++++++ packages/manus-tools/src/tool.test.ts | 1 + 2 files changed, 65 insertions(+) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 6ceea6f58..94ff04361 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -182,6 +182,7 @@ test("createSlideDeck treats mixed [stopped, running] desc as terminal", async ( }, ], }, + agent_profile: "manus-1.6-lite", }); return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { status: 200, @@ -365,6 +366,7 @@ test("createSlideDeck forwards optional skill fields on create", async () => { }, ); const body = JSON.parse(createBody) as { + agent_profile?: string; message: { enable_skills?: string[]; force_skills?: string[]; @@ -372,4 +374,66 @@ test("createSlideDeck forwards optional skill fields on create", async () => { }; expect(body.message.enable_skills).toEqual(["skill_slides"]); expect(body.message.force_skills).toEqual(["skill_slides"]); + expect(body.agent_profile).toBe("manus-1.6-lite"); +}); + +test("createTask omits agent_profile unless the caller sets it", async () => { + const captured: { body: string } = { body: "" }; + const fetchImpl = (async (_input: URL | string, init?: RequestInit) => { + captured.body = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + }) as unknown as typeof fetch; + + await createTask({ fetchImpl }, { content: "Hello" }); + expect(JSON.parse(captured.body)).toEqual({ + message: { content: [{ type: "text", text: "Hello" }] }, + }); + + await createTask( + { fetchImpl }, + { content: "Hello", agent_profile: "manus-1.6-max" }, + ); + expect(JSON.parse(captured.body)).toEqual({ + message: { content: [{ type: "text", text: "Hello" }] }, + agent_profile: "manus-1.6-max", + }); +}); + +test("createSlideDeck keeps a caller-supplied agent_profile", async () => { + let createBody = ""; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + createBody = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await createSlideDeck( + { fetchImpl }, + { + content: "Onboarding", + agent_profile: "manus-1.6-max", + pollIntervalMs: 0, + maxPolls: 1, + }, + ); + expect(JSON.parse(createBody).agent_profile).toBe("manus-1.6-max"); }); diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index 56ef6153d..f4c26f90c 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -134,6 +134,7 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio ); expect(body.message.enable_skills).toBeUndefined(); expect(body.message.force_skills).toBeUndefined(); + expect(body.agent_profile).toBe("manus-1.6-lite"); return new Response( JSON.stringify({ ok: true, From 5e6308acdecf385482a1552ded527b5f0d75eedd Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:34:51 -0700 Subject: [PATCH 18/75] Default Manus slide-deck creates to the lite agent profile --- packages/manus-tools/src/client.ts | 7 +++++++ packages/manus-tools/src/index.ts | 1 + 2 files changed, 8 insertions(+) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index f4fe0d5b7..850b2cfe6 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -386,6 +386,9 @@ export const DEFAULT_SLIDE_POLL_INTERVAL_MS = 2_000; /** 5 minutes at the default interval — a real deck takes longer than 60s. */ export const DEFAULT_SLIDE_MAX_POLLS = 150; +/** Free/personal accounts persist tasks only on the lite profile. */ +export const SLIDE_DECK_AGENT_PROFILE = "manus-1.6-lite"; + const SLIDE_DECK_PROMPT_PREFIX = "Create a slide presentation in pptx format. Produce a presentation " + "deck, not a document. Topic and requirements:\n\n"; @@ -447,6 +450,10 @@ export async function createSlideDeck( const created = await createTask(config, { ...taskParams, content: `${SLIDE_DECK_PROMPT_PREFIX}${taskParams.content}`, + agent_profile: + taskParams.agent_profile !== undefined + ? taskParams.agent_profile + : SLIDE_DECK_AGENT_PROFILE, }); const intervalMs = pollIntervalMs ?? DEFAULT_SLIDE_POLL_INTERVAL_MS; const polls = maxPolls ?? DEFAULT_SLIDE_MAX_POLLS; diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index c3eb3f291..15e93490a 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -11,6 +11,7 @@ export { DEFAULT_MANUS_BASE_URL, DEFAULT_SLIDE_MAX_POLLS, DEFAULT_SLIDE_POLL_INTERVAL_MS, + SLIDE_DECK_AGENT_PROFILE, SLIDES_FORMAT_PPTX, } from "./client"; export type { From 35a45356330791b4335711e5301b181239d887b9 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:34:57 -0700 Subject: [PATCH 19/75] Bump @corbits/manus-tools after the lite profile default --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index e05e742ad..dd61482a9 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.4", + "version": "0.0.5", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 22b67853f..66c8b42c6 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.4" }, + { name: "@corbits/manus-tools", version: "0.0.5" }, ]; /** From 4a1ac6fc610bf18309cd6525b4e1631d53a4421d Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:49:33 -0700 Subject: [PATCH 20/75] Add tests for Manus createTask lite agent profile default --- packages/manus-tools/src/client.test.ts | 15 +++++++++++- packages/manus-tools/src/tool.test.ts | 32 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 94ff04361..db1eab933 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -43,6 +43,7 @@ test("createTask posts to /v2/task.create and parses the ok envelope", async () expect(captured.headers?.get("x-api-key")).toBeNull(); expect(JSON.parse(captured.body)).toEqual({ message: { content: [{ type: "text", text: "Make slides" }] }, + agent_profile: "manus-1.6-lite", }); expect(created.task_id).toBe("task_1"); expect(created.task_url).toBe("https://manus.im/app/task_1"); @@ -91,6 +92,7 @@ test("createTask posts skill, connector, and schema fields only when set", async required: ["title"], additionalProperties: false, }, + agent_profile: "manus-1.6-lite", }); }); @@ -377,7 +379,7 @@ test("createSlideDeck forwards optional skill fields on create", async () => { expect(body.agent_profile).toBe("manus-1.6-lite"); }); -test("createTask omits agent_profile unless the caller sets it", async () => { +test("createTask defaults agent_profile to manus-1.6-lite when omitted", async () => { const captured: { body: string } = { body: "" }; const fetchImpl = (async (_input: URL | string, init?: RequestInit) => { captured.body = typeof init?.body === "string" ? init.body : ""; @@ -389,7 +391,18 @@ test("createTask omits agent_profile unless the caller sets it", async () => { await createTask({ fetchImpl }, { content: "Hello" }); expect(JSON.parse(captured.body)).toEqual({ message: { content: [{ type: "text", text: "Hello" }] }, + agent_profile: "manus-1.6-lite", }); +}); + +test("createTask keeps a caller-supplied agent_profile", async () => { + const captured: { body: string } = { body: "" }; + const fetchImpl = (async (_input: URL | string, init?: RequestInit) => { + captured.body = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + }) as unknown as typeof fetch; await createTask( { fetchImpl }, diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index f4c26f90c..2c2cb9d43 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -254,6 +254,36 @@ test("task_create and task_send_msg expose skill and connector fields", () => { } expect(create?.properties["structured_output_schema"]?.type).toBe("object"); expect(send?.properties["structured_output_schema"]).toBeUndefined(); + expect(create?.properties["agent_profile"]?.description).toContain( + "manus-1.6-lite", + ); + expect(create?.properties["agent_profile"]?.description).toMatch(/default/i); +}); + +test("task_create without agent_profile posts manus-1.6-lite", async () => { + const originalFetch = globalThis.fetch; + let createBody = ""; + globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { + createBody = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + { + id: "call_create_default_profile", + name: "task_create", + arguments: { content: "Hello" }, + }, + new AbortController().signal, + ); + expect(result.isError).toBeUndefined(); + expect(JSON.parse(createBody).agent_profile).toBe("manus-1.6-lite"); + } finally { + globalThis.fetch = originalFetch; + } }); test("task_create omits skill fields unless the assistant passes ids", async () => { @@ -279,6 +309,7 @@ test("task_create omits skill fields unless the assistant passes ids", async () expect(omitted.isError).toBeUndefined(); expect(JSON.parse(createBody)).toEqual({ message: { content: [{ type: "text", text: "Hello" }] }, + agent_profile: "manus-1.6-lite", }); const present = await bundle.run( @@ -306,6 +337,7 @@ test("task_create omits skill fields unless the assistant passes ids", async () task_references: ["task_ref_1"], }, structured_output_schema: { type: "object" }, + agent_profile: "manus-1.6-lite", }); } finally { globalThis.fetch = originalFetch; From 152e209fa5e526e942839ce4d8c082c057c6a5b4 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:50:24 -0700 Subject: [PATCH 21/75] Default Manus createTask to the lite agent profile --- packages/manus-tools/src/client.ts | 10 +++++----- packages/manus-tools/src/index.ts | 1 + packages/manus-tools/src/tool.ts | 4 +++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 850b2cfe6..02d840ba3 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -189,6 +189,9 @@ export async function manusRequest( return parseOkBody(body); } +/** Free/personal accounts persist tasks only on the lite profile. */ +export const DEFAULT_AGENT_PROFILE = "manus-1.6-lite"; + export type CreateTaskParams = { readonly content: string; readonly title?: string; @@ -272,9 +275,7 @@ export async function createTask( if (params.share_visibility !== undefined) { body["share_visibility"] = params.share_visibility; } - if (params.agent_profile !== undefined) { - body["agent_profile"] = params.agent_profile; - } + body["agent_profile"] = params.agent_profile ?? DEFAULT_AGENT_PROFILE; if (params.structured_output_schema !== undefined) { body["structured_output_schema"] = params.structured_output_schema; } @@ -386,8 +387,7 @@ export const DEFAULT_SLIDE_POLL_INTERVAL_MS = 2_000; /** 5 minutes at the default interval — a real deck takes longer than 60s. */ export const DEFAULT_SLIDE_MAX_POLLS = 150; -/** Free/personal accounts persist tasks only on the lite profile. */ -export const SLIDE_DECK_AGENT_PROFILE = "manus-1.6-lite"; +export const SLIDE_DECK_AGENT_PROFILE = DEFAULT_AGENT_PROFILE; const SLIDE_DECK_PROMPT_PREFIX = "Create a slide presentation in pptx format. Produce a presentation " + diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index 15e93490a..682f0eef1 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -11,6 +11,7 @@ export { DEFAULT_MANUS_BASE_URL, DEFAULT_SLIDE_MAX_POLLS, DEFAULT_SLIDE_POLL_INTERVAL_MS, + DEFAULT_AGENT_PROFILE, SLIDE_DECK_AGENT_PROFILE, SLIDES_FORMAT_PPTX, } from "./client"; diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index e330433a7..5268ee1b9 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -95,7 +95,9 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ "When true, hide the task from the Manus task list.", ), share_visibility: STRING("private, team, or public."), - agent_profile: STRING("manus-1.6, manus-1.6-lite, or manus-1.6-max."), + agent_profile: STRING( + "Defaults to manus-1.6-lite. Other values: manus-1.6, manus-1.6-max.", + ), ...MESSAGE_SKILL_PROPERTIES, structured_output_schema: OBJECT( "JSON Schema for structured output extraction. Sent on the create body, not inside message.", From 44be9e1ea2af57361be0b43467dcf83a743a458b Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:50:40 -0700 Subject: [PATCH 22/75] Bump @corbits/manus-tools after the createTask lite default --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index dd61482a9..64d43a594 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.5", + "version": "0.0.6", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 66c8b42c6..4f2ea215b 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.5" }, + { name: "@corbits/manus-tools", version: "0.0.6" }, ]; /** From a36d402e980f76bae7a733e19358dbc177daa32f Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:55:37 -0700 Subject: [PATCH 23/75] Add tests for Manus slide-deck listMessages not_found retry --- packages/manus-tools/src/client.test.ts | 107 ++++++++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index db1eab933..27c63d857 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -450,3 +450,110 @@ test("createSlideDeck keeps a caller-supplied agent_profile", async () => { ); expect(JSON.parse(createBody).agent_profile).toBe("manus-1.6-max"); }); + +test("createSlideDeck retries listMessages not_found then succeeds when the task is readable", async () => { + let listCalls = 0; + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listCalls += 1; + if (listCalls === 1) { + return new Response( + JSON.stringify({ + ok: false, + error: { code: "not_found", message: "Task not found" }, + }), + { status: 404 }, + ); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + const result = await createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 3 }, + ); + expect(result.agent_status).toBe("stopped"); + expect(listCalls).toBe(2); +}); + +test("createSlideDeck still throws unrelated listMessages errors", async () => { + let listCalls = 0; + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listCalls += 1; + return new Response( + JSON.stringify({ + ok: false, + error: { code: "permission_denied", message: "bad key" }, + }), + { status: 401 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 3 }, + ), + ).rejects.toThrow(/permission_denied: bad key/); + expect(listCalls).toBe(1); +}); + +test("createSlideDeck throws when listMessages stays not_found through the poll budget", async () => { + let listCalls = 0; + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listCalls += 1; + return new Response( + JSON.stringify({ + ok: false, + error: { code: "not_found", message: "Task not found" }, + }), + { status: 404 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 2 }, + ), + ).rejects.toThrow(/did not stop in time|not_found: Task not found/); + expect(listCalls).toBe(2); +}); From e830690e62e380042bcc52c238be9daa4cc01622 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:56:11 -0700 Subject: [PATCH 24/75] Retry Manus slide-deck polls on listMessages not_found --- packages/manus-tools/src/client.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 02d840ba3..11ff3455e 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -399,6 +399,13 @@ export type CreateSlideDeckParams = CreateTaskParams & { readonly signal?: AbortSignal; }; +function isManusTaskNotFoundError(error: unknown): boolean { + return ( + error instanceof Error && + error.message.includes("Manus request failed: not_found: Task not found") + ); +} + function throwIfSlideWaitAborted(signal: AbortSignal | undefined): void { if (signal?.aborted) { throw new Error("Manus slide-deck wait was cancelled"); @@ -460,10 +467,18 @@ export async function createSlideDeck( let messages: ListMessagesResponse | undefined; for (let i = 0; i < polls; i += 1) { throwIfSlideWaitAborted(signal); - messages = await listTaskMessages(config, { - task_id: created.task_id, - slides_format: SLIDES_FORMAT_PPTX, - }); + try { + messages = await listTaskMessages(config, { + task_id: created.task_id, + slides_format: SLIDES_FORMAT_PPTX, + }); + } catch (error) { + if (!isManusTaskNotFoundError(error)) throw error; + if (i < polls - 1) { + await sleep(intervalMs, signal); + } + continue; + } const status = latestAgentStatus(messages.messages); if (status !== undefined && TERMINAL_STATUSES.has(status)) break; if (status === "waiting") { From 4bd723759d6ca4120c8d75ed30c49f0f018ab90f Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:56:31 -0700 Subject: [PATCH 25/75] Bump @corbits/manus-tools after listMessages not_found retry --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 64d43a594..d9d2f0a1c 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.6", + "version": "0.0.7", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 4f2ea215b..1e03cd253 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.6" }, + { name: "@corbits/manus-tools", version: "0.0.7" }, ]; /** From ea02cdbc2da569f086e71eb82b07382828528f97 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:59:33 -0700 Subject: [PATCH 26/75] Add tests for Manus listMessages string timestamps Live list-messages bodies send ISO strings on timestamp. Pin that parse path, keep numeric timestamps, and still extract agent_status and attachments. --- packages/manus-tools/src/client.test.ts | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 27c63d857..736799bfa 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -5,6 +5,7 @@ import { createTask, DEFAULT_SLIDE_MAX_POLLS, DEFAULT_SLIDE_POLL_INTERVAL_MS, + extractOutputFiles, latestAgentStatus, listTaskMessages, manusRequest, @@ -132,6 +133,69 @@ test("listTaskMessages GETs /v2/task.listMessages without an auth header", async expect(listed.messages?.[0]?.status_update?.agent_status).toBe("stopped"); }); +test("listTaskMessages parses ISO string timestamps and still extracts status and attachments", async () => { + const fetchImpl = (async () => + new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + timestamp: "2026-08-26T12:00:00.000Z", + status_update: { agent_status: "stopped" }, + }, + { + type: "assistant_message", + timestamp: "2026-08-26T12:00:01.000Z", + assistant_message: { + content: "Here is the deck.", + attachments: [ + { + filename: "onboarding.pptx", + url: "https://files.manus.ai/onboarding.pptx", + }, + ], + }, + }, + ], + }), + { status: 200 }, + )) as unknown as typeof fetch; + + const listed = await listTaskMessages({ fetchImpl }, { task_id: "task_1" }); + expect(listed.messages?.[0]?.timestamp).toBe("2026-08-26T12:00:00.000Z"); + expect(latestAgentStatus(listed.messages)).toBe("stopped"); + expect(extractOutputFiles(listed.messages)).toEqual([ + { + filename: "onboarding.pptx", + url: "https://files.manus.ai/onboarding.pptx", + }, + ]); +}); + +test("listTaskMessages parses numeric timestamps", async () => { + const fetchImpl = (async () => + new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + timestamp: 1756224000, + status_update: { agent_status: "running" }, + }, + ], + }), + { status: 200 }, + )) as unknown as typeof fetch; + + const listed = await listTaskMessages({ fetchImpl }, { task_id: "task_1" }); + expect(listed.messages?.[0]?.timestamp).toBe(1756224000); + expect(listed.messages?.[0]?.status_update?.agent_status).toBe("running"); +}); + test("maps a non-ok HTTP body with a Manus error envelope", async () => { const fetchImpl = (async () => new Response( From d5379ee96fad0f1232b39b3bb3c6a68f0cc70ba2 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:59:45 -0700 Subject: [PATCH 27/75] Accept string or number timestamps on Manus TaskEvent Live list-messages returns ISO strings. The plugin does not use timestamp for status or files, so both shapes must parse. --- packages/manus-tools/src/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 11ff3455e..3ec6cbb83 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -43,7 +43,7 @@ export type TaskAttachment = typeof TaskAttachment.infer; const TaskEvent = type({ "id?": "string", "type?": "string", - "timestamp?": "number", + "timestamp?": "number | string", "assistant_message?": { "content?": "string", "attachments?": TaskAttachment.array(), From f88ecc9175673b80da18f0bfa34e9f12f9090a2d Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:59:50 -0700 Subject: [PATCH 28/75] Bump @corbits/manus-tools after string timestamp parse --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index d9d2f0a1c..6ff56e436 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.7", + "version": "0.0.8", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 1e03cd253..3ee924837 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.7" }, + { name: "@corbits/manus-tools", version: "0.0.8" }, ]; /** From 2ea3de21ec547eaba190527b1b7670c3301bf30b Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 23:02:30 -0700 Subject: [PATCH 29/75] Add tests for lowercase Manus listMessages not_found Live create_slides 404s with "task not found". Pin retry on that casing while keeping the capital-T envelope. --- packages/manus-tools/src/client.test.ts | 45 +++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 736799bfa..af04a9f5f 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -560,6 +560,51 @@ test("createSlideDeck retries listMessages not_found then succeeds when the task expect(listCalls).toBe(2); }); +test("createSlideDeck retries listMessages not_found with lowercase task not found", async () => { + let listCalls = 0; + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listCalls += 1; + if (listCalls === 1) { + return new Response( + JSON.stringify({ + ok: false, + error: { code: "not_found", message: "task not found" }, + }), + { status: 404 }, + ); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + const result = await createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 3 }, + ); + expect(result.agent_status).toBe("stopped"); + expect(listCalls).toBe(2); +}); + test("createSlideDeck still throws unrelated listMessages errors", async () => { let listCalls = 0; const fetchImpl = (async (input: URL | string) => { From 119a77cbf75b73d18ed916f3e339063d4313cf8d Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 23:02:53 -0700 Subject: [PATCH 30/75] Match Manus listMessages not_found without Task casing Live 404s say "task not found". Treat any Manus not_found as retryable during listMessages poll. --- packages/manus-tools/src/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 3ec6cbb83..06db73539 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -402,7 +402,7 @@ export type CreateSlideDeckParams = CreateTaskParams & { function isManusTaskNotFoundError(error: unknown): boolean { return ( error instanceof Error && - error.message.includes("Manus request failed: not_found: Task not found") + error.message.toLowerCase().includes("manus request failed: not_found") ); } From 33f6f23117a6388ba27a4a873aa02ee5e5d674a0 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 23:03:08 -0700 Subject: [PATCH 31/75] Bump @corbits/manus-tools after lowercase not_found match --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 6ff56e436..51472bb5b 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.8", + "version": "0.0.9", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 3ee924837..d5e1e587a 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.8" }, + { name: "@corbits/manus-tools", version: "0.0.9" }, ]; /** From daafc705865183ca2b8458948420e0c198472440 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Thu, 27 Aug 2026 11:56:44 -0700 Subject: [PATCH 32/75] Validate Manus task detail responses --- packages/manus-tools/package.json | 2 +- packages/manus-tools/src/client.test.ts | 19 +++++- packages/manus-tools/src/client.ts | 45 ++++++++++++++ packages/manus-tools/src/index.ts | 3 + packages/manus-tools/src/tool.test.ts | 79 +++++++++++++++++++++++-- packages/manus-tools/src/tool.ts | 17 ++++++ workflows/assistant/src/index.ts | 2 +- 7 files changed, 159 insertions(+), 8 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 51472bb5b..fdd07422f 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.9", + "version": "0.0.10", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index af04a9f5f..7b9f2075c 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -6,6 +6,7 @@ import { DEFAULT_SLIDE_MAX_POLLS, DEFAULT_SLIDE_POLL_INTERVAL_MS, extractOutputFiles, + getTaskDetail, latestAgentStatus, listTaskMessages, manusRequest, @@ -97,6 +98,21 @@ test("createTask posts skill, connector, and schema fields only when set", async }); }); +test("getTaskDetail rejects a malformed successful task payload", async () => { + const fetchImpl = (async () => + new Response( + JSON.stringify({ + ok: true, + task: { id: "task_1", status: "completed" }, + }), + { status: 200 }, + )) as unknown as typeof fetch; + + await expect(getTaskDetail({ fetchImpl }, "task_1")).rejects.toThrow( + /task-detail response did not match the expected shape/, + ); +}); + test("listTaskMessages GETs /v2/task.listMessages without an auth header", async () => { const captured: { url: string; headers: Headers | null } = { url: "", @@ -243,8 +259,7 @@ test("createSlideDeck treats mixed [stopped, running] desc as terminal", async ( content: [ { type: "text", - text: - "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + text: "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", }, ], }, diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 06db73539..860267e62 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -71,6 +71,33 @@ export const CreateTaskResponse = type({ }); export type CreateTaskResponse = typeof CreateTaskResponse.infer; +const TaskCreatorAPIKey = type({ + id: "string", + name: "string", +}); + +const TaskDetail = type({ + id: "string", + status: "'running' | 'stopped' | 'waiting' | 'error'", + "created_at?": "number", + "updated_at?": "number", + "task_type?": "'standard' | 'project' | 'agent_subtask'", + "share_visibility?": "'private' | 'team' | 'public'", + "title?": "string", + "credit_usage?": "number", + "task_url?": "string", + "created_by_api_key?": TaskCreatorAPIKey.or("null"), + "agent_profile?": "'manus-1.6' | 'manus-1.6-lite' | 'manus-1.6-max'", +}); +export type TaskDetail = typeof TaskDetail.infer; + +export const TaskDetailResponse = type({ + ok: "true", + "request_id?": "string", + task: TaskDetail, +}); +export type TaskDetailResponse = typeof TaskDetailResponse.infer; + export const ListMessagesResponse = type({ ok: "true", "request_id?": "string", @@ -293,6 +320,24 @@ export async function createTask( return parsed; } +export async function getTaskDetail( + config: ManusClientConfig, + taskId: string, +): Promise { + const raw = await manusRequest(config, { + method: "GET", + path: "/v2/task.detail", + params: { task_id: taskId }, + }); + const parsed = TaskDetailResponse(raw); + if (parsed instanceof type.errors) { + throw new Error( + `Manus task-detail response did not match the expected shape: ${parsed.summary}`, + ); + } + return parsed; +} + export type ListMessagesParams = { readonly task_id: string; readonly limit?: number; diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index 682f0eef1..5c570ae8d 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -1,10 +1,12 @@ export { CreateTaskResponse, ListMessagesResponse, + TaskDetailResponse, buildTaskMessage, createSlideDeck, createTask, extractOutputFiles, + getTaskDetail, latestAgentStatus, listTaskMessages, manusRequest, @@ -22,6 +24,7 @@ export type { ManusClientConfig, OutputFile, TaskAttachment, + TaskDetail, TaskEvent, TaskMessageBody, TaskMessageSkillFields, diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index 2c2cb9d43..598e1c5d1 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -286,15 +286,86 @@ test("task_create without agent_profile posts manus-1.6-lite", async () => { } }); +test("task_create result feeds task_detail through the validated GET boundary", async () => { + const originalFetch = globalThis.fetch; + const createdTaskId = "task_created_42"; + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + const url = String(input); + if (url === "https://api.manus.ai/v2/task.create") { + return new Response( + JSON.stringify({ ok: true, task_id: createdTaskId }), + { status: 200 }, + ); + } + expect(url).toBe( + `https://api.manus.ai/v2/task.detail?task_id=${createdTaskId}`, + ); + expect(init?.method).toBe("GET"); + return new Response( + JSON.stringify({ + ok: true, + request_id: "req_detail_1", + task: { + id: createdTaskId, + status: "running", + title: "Deterministic read", + task_type: "standard", + share_visibility: "private", + agent_profile: "manus-1.6-lite", + }, + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const created = await bundle.run( + { + id: "call_create_then_read", + name: "task_create", + arguments: { content: "Create a deterministic task" }, + }, + new AbortController().signal, + ); + expect(created.isError).toBeUndefined(); + const createResult = JSON.parse(created.content as string) as { + task_id: string; + }; + + const detail = await bundle.run( + { + id: "call_task_detail", + name: "task_detail", + arguments: { task_id: createResult.task_id }, + }, + new AbortController().signal, + ); + expect(detail.isError).toBeUndefined(); + expect(JSON.parse(detail.content as string)).toEqual({ + ok: true, + request_id: "req_detail_1", + task: { + id: createdTaskId, + status: "running", + title: "Deterministic read", + task_type: "standard", + share_visibility: "private", + agent_profile: "manus-1.6-lite", + }, + }); + } finally { + globalThis.fetch = originalFetch; + } +}); + test("task_create omits skill fields unless the assistant passes ids", async () => { const originalFetch = globalThis.fetch; let createBody = ""; globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { createBody = typeof init?.body === "string" ? init.body : ""; - return new Response( - JSON.stringify({ ok: true, task_id: "task_1" }), - { status: 200 }, - ); + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); }) as unknown as typeof fetch; try { const bundle = manusTools(fakeEnv(fakeCredentials("key"))); diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index 5268ee1b9..e55e854b2 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -10,6 +10,7 @@ import { buildTaskMessage, createSlideDeck, createTask, + getTaskDetail, listTaskMessages, manusRequest, type ManusClientConfig, @@ -527,6 +528,22 @@ async function runEndpoint( return errorResult(call.id, err); } } + if (spec.name === "task_detail") { + const taskId = stringArg(call, "task_id"); + if (taskId === undefined || taskId === "") { + return { + callId: call.id, + content: "task_detail requires a non-empty task_id argument", + isError: true, + }; + } + try { + const detail = await getTaskDetail(asClientConfig(credential), taskId); + return { callId: call.id, content: JSON.stringify(detail) }; + } catch (err) { + return errorResult(call.id, err); + } + } if (spec.name === "task_send_msg") { const content = stringArg(call, "content"); const taskId = stringArg(call, "task_id"); diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index d5e1e587a..887b6cb43 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.9" }, + { name: "@corbits/manus-tools", version: "0.0.10" }, ]; /** From a4eda05ec14c0fdc6ebe5faa072eb784a6a59e62 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Thu, 27 Aug 2026 15:55:12 -0700 Subject: [PATCH 33/75] Gate mutating Manus tools and flag create_slides agent errors Webhook, website publish/update, and task/file delete now declare approval ask so an assistant pin cannot auto-allow those calls. create_slides maps agent_status error to a thrown failure so the tool result is isError. --- apps/hub/src/tool-grants.test.ts | 19 +++++++++ packages/manus-tools/src/client.test.ts | 31 ++++++++++++++ packages/manus-tools/src/client.ts | 15 +++++-- packages/manus-tools/src/tool.test.ts | 56 +++++++++++++++++++++++++ packages/manus-tools/src/tool.ts | 15 ++++++- 5 files changed, 132 insertions(+), 4 deletions(-) diff --git a/apps/hub/src/tool-grants.test.ts b/apps/hub/src/tool-grants.test.ts index 7a69eb3d2..b2636f304 100644 --- a/apps/hub/src/tool-grants.test.ts +++ b/apps/hub/src/tool-grants.test.ts @@ -4,6 +4,7 @@ // `@corbits/folded-runs`' `deployAtHead`, which mints these into // `config.grants`. import { describe, expect, test } from "bun:test"; +import { describeCorbitsToolPackages } from "@corbits/tool-registry-publish"; import { createToolGrantsForPins } from "./tool-grants"; const DESCRIPTIONS = [ @@ -85,4 +86,22 @@ describe("createToolGrantsForPins", () => { const toolGrantsForPins = createToolGrantsForPins(DESCRIPTIONS); expect(toolGrantsForPins([])).toEqual([]); }); + + test("assistant pin of webhook_create is ask, not allow", async () => { + const toolGrantsForPins = createToolGrantsForPins( + await describeCorbitsToolPackages(), + ); + const grants = toolGrantsForPins([ + { name: "@corbits/manus-tools", version: "*" }, + ]); + expect( + grants.find((g) => g.resource.endsWith(":webhook_create"))?.effect, + ).toBe("ask"); + expect( + grants.find((g) => g.resource.endsWith(":create_slides"))?.effect, + ).toBe("allow"); + expect(grants.find((g) => g.resource.endsWith(":task_list"))?.effect).toBe( + "allow", + ); + }); }); diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 7b9f2075c..992018ac7 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -365,6 +365,37 @@ test("createSlideDeck throws when the agent is waiting", async () => { ).rejects.toThrow(/waiting for confirmation/); }); +test("createSlideDeck throws when the agent_status is error", async () => { + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "error" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 5 }, + ), + ).rejects.toThrow(/agent_status error/); +}); + test("createSlideDeck aborts polling instead of waiting out the timeout", async () => { const controller = new AbortController(); const fetchImpl = (async (input: URL | string) => { diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 860267e62..900a300e3 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -483,9 +483,10 @@ function sleep(ms: number, signal?: AbortSignal): Promise { /** * Creates a task whose prompt asks Manus to produce a slide deck, then - * polls `task.listMessages` until the agent stops (or errors) and returns - * any output files so a caller can retrieve them. A timeout, a still-running - * or waiting agent, or an abort is a thrown error — never a successful deck. + * polls `task.listMessages` until the agent stops and returns any output + * files so a caller can retrieve them. A timeout, a still-running or + * waiting agent, an `error` status, or an abort is a thrown error — + * never a successful deck. */ export async function createSlideDeck( config: ManusClientConfig, @@ -542,6 +543,14 @@ export async function createSlideDeck( (status !== undefined ? ` (agent_status: ${status})` : ""), ); } + if (status === "error") { + const errorEvent = messages?.messages?.find((event) => event.error_message); + const detail = errorEvent?.error_message?.content; + throw new Error( + `Manus task ${created.task_id} ended with agent_status error` + + (detail !== undefined ? `: ${detail}` : ""), + ); + } const files = extractOutputFiles(messages?.messages); const errorEvent = messages?.messages?.find((event) => event.error_message); const result: { diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index 598e1c5d1..ec66e6e69 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -82,6 +82,26 @@ test("declares create_slides plus thin tools covering the v2 surface", () => { expect(names.length).toBe(MANUS_ENDPOINTS.length + 1); }); +test("mutating admin tools declare approval ask; create_slides and read-ish tools stay ungated", () => { + const byName = new Map(manusTools.definitions.map((d) => [d.name, d])); + for (const name of [ + "webhook_create", + "webhook_delete", + "webhook_list", + "webhook_pubkey", + "website_publish", + "website_update", + "task_delete", + "file_delete", + ] as const) { + expect(byName.get(name)).toEqual({ name, approval: "ask" }); + } + expect(byName.get(CREATE_SLIDES_TOOL)).toEqual({ name: CREATE_SLIDES_TOOL }); + expect(byName.get("task_list")).toEqual({ name: "task_list" }); + expect(byName.get("task_list_msgs")).toEqual({ name: "task_list_msgs" }); + expect(byName.get("file_detail")).toEqual({ name: "file_detail" }); +}); + test("task_list_msgs describes slides_format as pptx or html, never pdf", () => { const listMsgs = MANUS_ENDPOINTS.find( (spec) => spec.name === "task_list_msgs", @@ -227,6 +247,42 @@ test("create_slides returns isError when the agent is waiting", async () => { } }); +test("create_slides returns isError when the agent_status is error", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: unknown) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "error" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toMatch(/agent_status error/); + } finally { + globalThis.fetch = originalFetch; + } +}); + test("degrades to an error result (never throws) when the underlying call fails", async () => { const originalFetch = globalThis.fetch; globalThis.fetch = (async () => diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index e55e854b2..68730af10 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -37,6 +37,7 @@ type EndpointSpec = { readonly description: string; readonly required: readonly string[]; readonly properties: Readonly>; + readonly approval?: "ask"; }; const STRING = (description: string): JsonSchemaProperty => ({ @@ -159,6 +160,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Deletes a Manus task.", required: ["task_id"], properties: { task_id: STRING("Task id.") }, + approval: "ask", }, { name: "task_send_msg", @@ -284,6 +286,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Deletes a Manus file.", required: ["file_id"], properties: { file_id: STRING("File id.") }, + approval: "ask", }, { name: "webhook_create", @@ -292,6 +295,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Creates a Manus webhook.", required: ["url"], properties: { url: STRING("Webhook callback URL.") }, + approval: "ask", }, { name: "webhook_list", @@ -300,6 +304,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Lists Manus webhooks.", required: [], properties: {}, + approval: "ask", }, { name: "webhook_delete", @@ -308,6 +313,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Deletes a Manus webhook.", required: ["webhook_id"], properties: { webhook_id: STRING("Webhook id.") }, + approval: "ask", }, { name: "webhook_pubkey", @@ -316,6 +322,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Returns the Manus webhook signing public key.", required: [], properties: {}, + approval: "ask", }, { name: "usage_list", @@ -400,6 +407,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ website_id: STRING("Website id."), visibility: STRING("Visibility."), }, + approval: "ask", }, { name: "website_update", @@ -413,6 +421,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ title: STRING("New title."), visibility: STRING("Visibility."), }, + approval: "ask", }, { name: "website_ckpts", @@ -799,7 +808,11 @@ export const manusTools = defineTool({ requires: ["credentials"], definitions: [ { name: CREATE_SLIDES_TOOL }, - ...MANUS_ENDPOINTS.map((spec) => ({ name: spec.name })), + ...MANUS_ENDPOINTS.map((spec) => + spec.approval === "ask" + ? { name: spec.name, approval: "ask" as const } + : { name: spec.name }, + ), ], factory: (env) => ({ definitions: [ From 3a2e893d86935316ba5578ffa23ea1312ef916af Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Thu, 27 Aug 2026 15:55:18 -0700 Subject: [PATCH 34/75] Bump @corbits/manus-tools after admin-tool gates --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index fdd07422f..7da533d97 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.10", + "version": "0.0.11", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 887b6cb43..028e52925 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.8" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.10" }, + { name: "@corbits/manus-tools", version: "0.0.11" }, ]; /** From 8b7095ce6c2cba814482fa6524f2d96f2d2a22d4 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 16:45:13 -0700 Subject: [PATCH 35/75] Add tests for a Manus tool package --- .../src/persist-credential.test.ts | 24 +++ packages/connections/src/probes.test.ts | 34 ++++ packages/connections/src/registry.test.ts | 17 +- .../src/http-x-manus-api-key-provider.test.ts | 124 ++++++++++++ packages/manus-tools/src/client.test.ts | 102 ++++++++++ packages/manus-tools/src/manifest.test.ts | 22 +++ packages/manus-tools/src/tool.test.ts | 179 ++++++++++++++++++ packages/plugins-ui/test/plugin-meta.test.ts | 12 ++ .../src/connections-pinned-by.test.ts | 4 + workflows/assistant/test/definition.test.ts | 15 ++ 10 files changed, 530 insertions(+), 3 deletions(-) create mode 100644 packages/credential-providers/src/http-x-manus-api-key-provider.test.ts create mode 100644 packages/manus-tools/src/client.test.ts create mode 100644 packages/manus-tools/src/manifest.test.ts create mode 100644 packages/manus-tools/src/tool.test.ts create mode 100644 packages/plugins-ui/test/plugin-meta.test.ts diff --git a/packages/connections/src/persist-credential.test.ts b/packages/connections/src/persist-credential.test.ts index f7f403d90..712ffbc05 100644 --- a/packages/connections/src/persist-credential.test.ts +++ b/packages/connections/src/persist-credential.test.ts @@ -89,6 +89,29 @@ describe("persistConnectorCredential", () => { expect(result.credentialId).toBe("cred_prv_github"); }); + test("manus persists the production API origin so origin-pin can resolve", async () => { + const { providers, seeds, fns } = recordingFns(); + await persistConnectorCredential({ + api: noApi as never, + cookies: [], + tenantId: "tnt_1", + descriptor: descriptorOrThrow("manus"), + secret: "manus_key", + log: () => undefined, + ...fns, + }); + + expect(providers).toEqual([ + { + tenantId: "tnt_1", + name: "manus", + plugin: "http-x-manus-api-key", + apiBaseUrl: "https://api.manus.ai", + }, + ]); + expect(seeds).toEqual([]); + }); + test("an inference provider seeds its catalog under the same credential name", async () => { const { credentials, seeds, fns } = recordingFns(); await persistConnectorCredential({ @@ -166,6 +189,7 @@ describe("isInferenceProvider", () => { expect(isInferenceProvider("openrouter")).toBe(true); expect(isInferenceProvider("github")).toBe(false); expect(isInferenceProvider("linear")).toBe(false); + expect(isInferenceProvider("manus")).toBe(false); }); }); diff --git a/packages/connections/src/probes.test.ts b/packages/connections/src/probes.test.ts index 9ceedea8f..6939000af 100644 --- a/packages/connections/src/probes.test.ts +++ b/packages/connections/src/probes.test.ts @@ -9,6 +9,7 @@ import { testGitHubCredential, testGranolaCredential, testLinearCredential, + testManusCredential, testScrapeCreatorsCredential, } from "./probes"; @@ -126,3 +127,36 @@ describe("testLinearCredential", () => { expect(result.ok).toBe(true); }); }); + +describe("testManusCredential", () => { + test("rejects a 401", async () => { + const result = await testManusCredential("test-key", fakeFetch(401)); + expect(result.ok).toBe(false); + }); + + test("accepts a 200", async () => { + const result = await testManusCredential( + "test-key", + fakeFetch(200, JSON.stringify({ ok: true, skills: [] })), + ); + expect(result.ok).toBe(true); + }); + + test("sends x-manus-api-key to skill.list", async () => { + const requested: { url: string; key: string | null }[] = []; + const fetchImpl: FetchLike = async (input, init) => { + requested.push({ + url: String(input), + key: + (init?.headers as Headers | undefined)?.get("x-manus-api-key") ?? + null, + }); + return new Response(JSON.stringify({ ok: true }), { status: 200 }); + }; + const result = await testManusCredential("manus_key", fetchImpl); + expect(result.ok).toBe(true); + expect(requested).toEqual([ + { url: "https://api.manus.ai/v2/skill.list", key: "manus_key" }, + ]); + }); +}); diff --git a/packages/connections/src/registry.test.ts b/packages/connections/src/registry.test.ts index 1dfa07f94..d77b30eaf 100644 --- a/packages/connections/src/registry.test.ts +++ b/packages/connections/src/registry.test.ts @@ -113,10 +113,18 @@ describe("CONNECTOR_REGISTRY", () => { expect(descriptor?.feedsTools).toEqual([]); }); - test("includes the five tool connectors with the right feedsTools", () => { + test("includes the tool connectors with the right feedsTools", () => { expect(CONNECTOR_REGISTRY["granola"]?.feedsTools).toEqual([ "@corbits/granola-tools", ]); + expect(CONNECTOR_REGISTRY["manus"]?.feedsTools).toEqual([ + "@corbits/manus-tools", + ]); + expect(CONNECTOR_REGISTRY["manus"]?.credentialPlugin).toBe( + "http-x-manus-api-key", + ); + expect(CONNECTOR_REGISTRY["manus"]?.authKind).toBe("api-key"); + expect(CONNECTOR_REGISTRY["manus"]?.icon).toBeUndefined(); expect(CONNECTOR_REGISTRY["exa"]?.feedsTools).toEqual([ "@corbits/web-search-tools", ]); @@ -161,9 +169,12 @@ describe("connectorDescriptors", () => { expect(CONNECTOR_REGISTRY["scrapecreators"]?.credentialPlugin).toBe( "http-x-api-key", ); - const bearerConnectors = new Set(["linear", "exa", "scrapecreators"]); + expect(CONNECTOR_REGISTRY["manus"]?.credentialPlugin).toBe( + "http-x-manus-api-key", + ); + const nonBearer = new Set(["linear", "exa", "scrapecreators", "manus"]); for (const [id, descriptor] of Object.entries(CONNECTOR_REGISTRY)) { - if (bearerConnectors.has(id)) continue; + if (nonBearer.has(id)) continue; expect(descriptor.credentialPlugin).toBe("http"); } }); diff --git a/packages/credential-providers/src/http-x-manus-api-key-provider.test.ts b/packages/credential-providers/src/http-x-manus-api-key-provider.test.ts new file mode 100644 index 000000000..7a7da95b9 --- /dev/null +++ b/packages/credential-providers/src/http-x-manus-api-key-provider.test.ts @@ -0,0 +1,124 @@ +import { expect, test } from "bun:test"; + +import { + createHttpXManusApiKeyCredentialProvider, + HTTP_X_MANUS_API_KEY_PROVIDER_KEY, +} from "./http-x-manus-api-key-provider"; + +const ORIGIN = "https://api.manus.ai"; + +function materialSource(secret: string): { current: string } { + return { current: secret }; +} + +test("key is http-x-manus-api-key", () => { + expect(createHttpXManusApiKeyCredentialProvider().key).toBe( + HTTP_X_MANUS_API_KEY_PROVIDER_KEY, + ); +}); + +test("sends the secret in x-manus-api-key, not authorization or x-api-key", async () => { + const captured: { + manusKey: string | null; + apiKey: string | null; + auth: string | null; + } = { + manusKey: null, + apiKey: null, + auth: null, + }; + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async (_input, init) => { + const headers = init?.headers as Headers | undefined; + captured.manusKey = headers?.get("x-manus-api-key") ?? null; + captured.apiKey = headers?.get("x-api-key") ?? null; + captured.auth = headers?.get("authorization") ?? null; + return new Response("{}", { status: 200 }); + }, + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: "manus_real_key" }), + }); + + await mediated.fetch(`${ORIGIN}/v2/skill.list`); + + expect(captured.manusKey).toBe("manus_real_key"); + expect(captured.apiKey).toBeNull(); + expect(captured.auth).toBeNull(); +}); + +test("re-reads the material source per call, reflecting a rotation", async () => { + const manusKeys: string[] = []; + const material = materialSource("original-key"); + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async (_input, init) => { + manusKeys.push( + (init?.headers as Headers | undefined)?.get("x-manus-api-key") ?? "", + ); + return new Response("{}", { status: 200 }); + }, + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: material.current }), + }); + + await mediated.fetch(`${ORIGIN}/v2/skill.list`); + material.current = "rotated-key"; + await mediated.fetch(`${ORIGIN}/v2/skill.list`); + + expect(manusKeys).toEqual(["original-key", "rotated-key"]); +}); + +test("refuses a cross-origin request rather than leaking the secret off the pinned origin", async () => { + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async () => new Response("{}", { status: 200 }), + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: "manus_real_key" }), + }); + + await expect( + mediated.fetch("https://evil.example.com/v2/skill.list"), + ).rejects.toThrow(/refusing cross-origin request/); +}); + +test("forces redirect: manual so a same-origin 3xx never auto-follows off the handle", async () => { + const captured: { redirect: string | undefined } = { redirect: undefined }; + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async (_input, init) => { + captured.redirect = init?.redirect; + return new Response("{}", { status: 200 }); + }, + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: "manus_real_key" }), + }); + + await mediated.fetch(`${ORIGIN}/v2/skill.list`); + + expect(captured.redirect).toBe("manual"); +}); + +test("also mediates a Request input, preserving its own headers", async () => { + const captured: { manusKey: string | null } = { manusKey: null }; + const provider = createHttpXManusApiKeyCredentialProvider({ + fetch: async (request) => { + captured.manusKey = (request as Request).headers.get("x-manus-api-key"); + return new Response("{}", { status: 200 }); + }, + }); + const mediated = provider.shape({ + origin: ORIGIN, + readCurrentMaterial: () => ({ secret: "manus_real_key" }), + }); + + await mediated.fetch( + new Request(`${ORIGIN}/v2/task.create`, { method: "POST" }), + ); + + expect(captured.manusKey).toBe("manus_real_key"); +}); diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts new file mode 100644 index 000000000..d0855a6f3 --- /dev/null +++ b/packages/manus-tools/src/client.test.ts @@ -0,0 +1,102 @@ +import { expect, test } from "bun:test"; + +import { createTask, listTaskMessages, manusRequest } from "./client"; + +test("createTask posts to /v2/task.create and parses the ok envelope", async () => { + const captured: { url: string; headers: Headers | null; body: string } = { + url: "", + headers: null, + body: "", + }; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + captured.url = String(input); + captured.headers = + init?.headers instanceof Headers + ? init.headers + : new Headers(init?.headers); + captured.body = typeof init?.body === "string" ? init.body : ""; + return new Response( + JSON.stringify({ + ok: true, + request_id: "req_1", + task_id: "task_1", + task_title: "Deck", + task_url: "https://manus.im/app/task_1", + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + const created = await createTask({ fetchImpl }, { content: "Make slides" }); + expect(captured.url).toBe("https://api.manus.ai/v2/task.create"); + expect(captured.headers?.get("x-manus-api-key")).toBeNull(); + expect(captured.headers?.get("authorization")).toBeNull(); + expect(captured.headers?.get("x-api-key")).toBeNull(); + expect(JSON.parse(captured.body)).toEqual({ + message: { content: "Make slides" }, + }); + expect(created.task_id).toBe("task_1"); + expect(created.task_url).toBe("https://manus.im/app/task_1"); +}); + +test("listTaskMessages GETs /v2/task.listMessages without an auth header", async () => { + const captured: { url: string; headers: Headers | null } = { + url: "", + headers: null, + }; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + captured.url = String(input); + captured.headers = + init?.headers instanceof Headers + ? init.headers + : init?.headers !== undefined + ? new Headers(init.headers) + : null; + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + const listed = await listTaskMessages({ fetchImpl }, { task_id: "task_1" }); + expect(captured.url).toBe( + "https://api.manus.ai/v2/task.listMessages?task_id=task_1", + ); + expect(captured.headers?.get("x-manus-api-key") ?? null).toBeNull(); + expect(listed.messages?.[0]?.status_update?.agent_status).toBe("stopped"); +}); + +test("maps a non-ok HTTP body with a Manus error envelope", async () => { + const fetchImpl = (async () => + new Response( + JSON.stringify({ + ok: false, + error: { code: "permission_denied", message: "bad key" }, + }), + { status: 401 }, + )) as unknown as typeof fetch; + + await expect( + manusRequest({ fetchImpl }, { method: "GET", path: "/v2/skill.list" }), + ).rejects.toThrow(/permission_denied: bad key/); +}); + +test("throws when a 200 body is not an ok envelope", async () => { + const fetchImpl = (async () => + new Response(JSON.stringify({ notes: [] }), { + status: 200, + })) as unknown as typeof fetch; + + await expect( + manusRequest({ fetchImpl }, { method: "GET", path: "/v2/skill.list" }), + ).rejects.toThrow(/did not match the expected shape/); +}); diff --git a/packages/manus-tools/src/manifest.test.ts b/packages/manus-tools/src/manifest.test.ts new file mode 100644 index 000000000..0f36b5454 --- /dev/null +++ b/packages/manus-tools/src/manifest.test.ts @@ -0,0 +1,22 @@ +// Proves this package's own `package.json` satisfies the vendored +// `PackageJSON` manifest schema with an `interchange.credentials` +// declaration the deploy-time `ToolPackageManifest` harvests. +import { expect, test } from "bun:test"; +import { type } from "arktype"; +import { PackageJSON } from "@intx/types/package-json"; + +import packageJson from "../package.json"; + +test("package.json parses against the vendored PackageJSON manifest schema", () => { + const parsed = PackageJSON(packageJson); + expect(parsed instanceof type.errors).toBe(false); +}); + +test("declares exactly one credential handle: manus", () => { + const parsed = PackageJSON(packageJson); + if (parsed instanceof type.errors) { + throw new Error(parsed.summary); + } + expect(parsed.interchange?.credentials).toEqual([{ handle: "manus" }]); + expect(parsed.version).toBe("0.0.1"); +}); diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts new file mode 100644 index 000000000..b6b0875a4 --- /dev/null +++ b/packages/manus-tools/src/tool.test.ts @@ -0,0 +1,179 @@ +import { expect, test } from "bun:test"; +import type { ToolCall } from "@intx/types/runtime"; +import type { CredentialCapability, MediatedCredential } from "@intx/types"; + +import { + CREATE_SLIDES_TOOL, + MANUS_ENDPOINTS, + MANUS_NOT_CONNECTED, + manusTools, +} from "./tool"; +import type { ManusEnv } from "./tool"; + +const CREATE_SLIDES_CALL: ToolCall = { + id: "call_1", + name: CREATE_SLIDES_TOOL, + arguments: { prompt: "Make a five-slide deck about onboarding" }, +}; + +function fakeCredentials(secret: string | undefined): CredentialCapability { + return { + resolve(handle: string): Promise { + if (secret === undefined) { + return Promise.reject( + new Error(`no credential is bound to handle "${handle}"`), + ); + } + return Promise.resolve({ + kind: "http", + fetch: (input, init) => fetch(input as string | URL, init), + dispose: () => {}, + }); + }, + }; +} + +function fakeEnv(credentials: CredentialCapability | undefined): ManusEnv { + return { credentials } as unknown as ManusEnv; +} + +const STOPPED_WITH_DECK = { + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + { + type: "assistant_message", + assistant_message: { + content: "Here is the deck.", + attachments: [ + { + type: "slides", + filename: "onboarding.pdf", + url: "https://files.manus.ai/onboarding.pdf", + id: "file_deck_1", + content_type: "application/pdf", + }, + ], + }, + }, + ], +}; + +test("declares create_slides plus thin tools covering the v2 surface", () => { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const names = bundle.definitions.map((d) => d.name); + expect(names).toContain(CREATE_SLIDES_TOOL); + expect(names).toContain("task_create"); + expect(names).toContain("task_list_msgs"); + expect(names).toContain("file_upload"); + expect(names).toContain("skill_list"); + expect(names).toContain("project_list"); + expect(names).toContain("agent_list"); + expect(names).toContain("webhook_list"); + expect(names).toContain("usage_credits"); + expect(names).toContain("connector_list"); + expect(names).toContain("browser_online"); + expect(names).toContain("website_status"); + expect(names.length).toBe(MANUS_ENDPOINTS.length + 1); +}); + +test("degrades to a non-throwing 'not connected' error when no credential is bound", async () => { + const bundle = manusTools(fakeEnv(fakeCredentials(undefined))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toBe(MANUS_NOT_CONNECTED); +}); + +test("degrades the same way when the step carries no credentials capability at all", async () => { + const bundle = manusTools(fakeEnv(undefined)); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toBe(MANUS_NOT_CONNECTED); +}); + +test("create_slides creates a task, polls messages, and surfaces the presentation file", async () => { + const originalFetch = globalThis.fetch; + const urls: string[] = []; + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + const url = String(input); + urls.push(url); + if (url.includes("/v2/task.create")) { + expect(init?.method).toBe("POST"); + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + task_title: "Onboarding", + task_url: "https://manus.im/app/task_1", + }), + { status: 200 }, + ); + } + if (url.includes("/v2/task.listMessages")) { + return new Response(JSON.stringify(STOPPED_WITH_DECK), { status: 200 }); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBeUndefined(); + const parsed = JSON.parse(result.content as string) as { + task_id: string; + agent_status: string; + files: readonly { + filename: string; + url: string; + id: string; + type: string; + content_type: string; + }[]; + }; + expect(parsed.task_id).toBe("task_1"); + expect(parsed.agent_status).toBe("stopped"); + expect(parsed.files).toEqual([ + { + filename: "onboarding.pdf", + url: "https://files.manus.ai/onboarding.pdf", + id: "file_deck_1", + type: "slides", + content_type: "application/pdf", + }, + ]); + expect(urls.some((url) => url.includes("/v2/task.create"))).toBe(true); + expect(urls.some((url) => url.includes("/v2/task.listMessages"))).toBe( + true, + ); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("degrades to an error result (never throws) when the underlying call fails", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => + new Response("nope", { status: 500 })) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + } finally { + globalThis.fetch = originalFetch; + } +}); diff --git a/packages/plugins-ui/test/plugin-meta.test.ts b/packages/plugins-ui/test/plugin-meta.test.ts new file mode 100644 index 000000000..9b64056c9 --- /dev/null +++ b/packages/plugins-ui/test/plugin-meta.test.ts @@ -0,0 +1,12 @@ +import { expect, test } from "bun:test"; +import { Stack } from "@corbits/icons"; + +import { pluginCategory, pluginIcon, pluginOutcome } from "../src/plugin-meta"; + +test("manus is a Productivity plugin whose outcome names tasks and slide-deck files", () => { + expect(pluginCategory("manus")).toBe("Productivity"); + expect(pluginOutcome("manus", "Manus")).toBe( + "Lets agents run Manus tasks and retrieve files — including slide decks.", + ); + expect(pluginIcon("manus")).toBe(Stack); +}); diff --git a/packages/settings-ui/src/connections-pinned-by.test.ts b/packages/settings-ui/src/connections-pinned-by.test.ts index b07ed95d1..2161d2e07 100644 --- a/packages/settings-ui/src/connections-pinned-by.test.ts +++ b/packages/settings-ui/src/connections-pinned-by.test.ts @@ -54,4 +54,8 @@ describe("connections pinned-by", () => { "reddit-opportunity-scanner", ]); }); + + test("manus pins the assistant", () => { + expect(CONNECTOR_PINNED_WORKFLOWS.manus).toEqual(["assistant"]); + }); }); diff --git a/workflows/assistant/test/definition.test.ts b/workflows/assistant/test/definition.test.ts index a02fbb95d..9defdca05 100644 --- a/workflows/assistant/test/definition.test.ts +++ b/workflows/assistant/test/definition.test.ts @@ -7,6 +7,7 @@ import { expect, test } from "bun:test"; import type { StepPrimitive, WorkflowDefinition } from "@intx/workflow"; import { + ASSISTANT_CREDENTIAL_BINDINGS, ASSISTANT_STEP_ID, ASSISTANT_SYSTEM_PROMPT, ASSISTANT_TOOL_PACKAGE_PINS, @@ -125,6 +126,7 @@ test("the agent pins memory, capability, and the manager-tools bundles at the ve "@corbits/skills-tools", "@corbits/mcp-tools", "@corbits/interaction-tools", + "@corbits/manus-tools", ]); // A pin the registry cannot resolve fails every assistant deploy, so // each one must name a version the workspace actually publishes. @@ -149,6 +151,19 @@ test("the prompt tells Myra to discover an MCP server's tools before calling one expect(ASSISTANT_SYSTEM_PROMPT).toContain("never guess a tool name"); }); +test("the workflow binds the Manus credential handle to a tenant-owned provider", () => { + const definition = buildAssistantWorkflow(INPUT); + expect(definition.credentialBindings).toEqual(ASSISTANT_CREDENTIAL_BINDINGS); + expect(ASSISTANT_CREDENTIAL_BINDINGS).toEqual([ + { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant", + }, + ]); +}); + test("the definition survives the workflow-asset JSON round-trip", () => { const definition = buildAssistantWorkflow(INPUT); const revived: unknown = JSON.parse(serializeAssistantWorkflow(definition)); From c6bf6c793abf905fc686e7748795fd861e80a9f8 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 16:45:20 -0700 Subject: [PATCH 36/75] Add a Manus plugin covering API v2 --- .../src/workflow-substrate-factory/index.ts | 11 +- bun.lock | 15 + packages/connections/src/descriptor.ts | 14 +- packages/connections/src/index.ts | 1 + .../connections/src/persist-credential.ts | 17 +- packages/connections/src/probes.ts | 10 + packages/connections/src/registry.ts | 12 + .../src/http-x-manus-api-key-provider.ts | 121 +++ packages/credential-providers/src/index.ts | 6 + packages/manus-tools/LICENSE | 176 +++++ packages/manus-tools/package.json | 31 + packages/manus-tools/src/client.ts | 381 ++++++++++ packages/manus-tools/src/index.ts | 28 + packages/manus-tools/src/tool.ts | 706 ++++++++++++++++++ packages/manus-tools/tsconfig.json | 7 + packages/plugins-ui/src/plugin-meta.ts | 5 + .../settings-ui/src/connections-pinned-by.ts | 1 + .../tool-registry-publish/src/registry.ts | 1 + workflows/assistant/src/index.ts | 19 + 19 files changed, 1548 insertions(+), 14 deletions(-) create mode 100644 packages/credential-providers/src/http-x-manus-api-key-provider.ts create mode 100644 packages/manus-tools/LICENSE create mode 100644 packages/manus-tools/package.json create mode 100644 packages/manus-tools/src/client.ts create mode 100644 packages/manus-tools/src/index.ts create mode 100644 packages/manus-tools/src/tool.ts create mode 100644 packages/manus-tools/tsconfig.json diff --git a/apps/sidecar/src/workflow-substrate-factory/index.ts b/apps/sidecar/src/workflow-substrate-factory/index.ts index 089e76606..a7ada16ba 100644 --- a/apps/sidecar/src/workflow-substrate-factory/index.ts +++ b/apps/sidecar/src/workflow-substrate-factory/index.ts @@ -38,6 +38,7 @@ import { import { createHttpRawAuthorizationCredentialProvider, createHttpXApiKeyCredentialProvider, + createHttpXManusApiKeyCredentialProvider, createMcpStreamableHttpCredentialProvider, } from "@corbits/credential-providers"; import { loadAdapterRegistry } from "@intx/inference/providers"; @@ -409,15 +410,17 @@ export function createSidecarSubstrateFactory( // with no `Bearer ` prefix -- Linear's convention) and // `http-x-api-key` plugin (for a provider row whose API expects the // secret in an `x-api-key` header -- Exa's and ScrapeCreators' - // convention), both from `@corbits/credential-providers` rather than - // forking or reaching around the vendored plugin. Fixed for the - // child's lifetime -- unlike the per-step wiring below, the set of - // provider plugins is not something a rotation or + // convention) and `http-x-manus-api-key` plugin (for Manus, which + // expects `x-manus-api-key`), all from `@corbits/credential-providers` + // rather than forking or reaching around the vendored plugin. Fixed + // for the child's lifetime -- unlike the per-step wiring below, the + // set of provider plugins is not something a rotation or // `credentials-updated` frame changes. const credentialProviders = createCredentialProviderRegistry([ ...builtinCredentialProviders(), createHttpRawAuthorizationCredentialProvider(), createHttpXApiKeyCredentialProvider(), + createHttpXManusApiKeyCredentialProvider(), createMcpStreamableHttpCredentialProvider(), ]); diff --git a/bun.lock b/bun.lock index 74c1a084f..b7b9770db 100644 --- a/bun.lock +++ b/bun.lock @@ -966,6 +966,19 @@ "typescript": "catalog:", }, }, + "packages/manus-tools": { + "name": "@corbits/manus-tools", + "version": "0.0.1", + "dependencies": { + "@intx/agent": "0.3.0", + "@intx/types": "0.3.0", + "arktype": "catalog:", + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:", + }, + }, "packages/mcp-tools": { "name": "@corbits/mcp-tools", "version": "0.0.8", @@ -2202,6 +2215,8 @@ "@corbits/mailbox": ["@corbits/mailbox@github:corbitsdev/corbits-mailbox#caa5214", { "dependencies": { "@hono/standard-validator": "0.2.3", "@standard-community/standard-json": "0.3.5", "@standard-community/standard-openapi": "0.2.9", "arktype": "2.1.29", "hono-openapi": "1.3.1" }, "peerDependencies": { "@intx/log": "^0.2.2", "@intx/mime": "^0.2.2", "@intx/types": "^0.2.2", "drizzle-orm": "^0.45.2", "hono": "^4.12.0", "postgres": "^3.4.0" } }, "corbitsdev-corbits-mailbox-caa5214", "sha512-z8DRBFgA4ukM8p29COeaMjfKZYe5jAUF4OBMiaIQFuW592+DGD/y6Ws6SjGlXmR9azkHNWh8oTzjlWlRP24vsQ=="], + "@corbits/manus-tools": ["@corbits/manus-tools@workspace:packages/manus-tools"], + "@corbits/mcp-tools": ["@corbits/mcp-tools@workspace:packages/mcp-tools"], "@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], diff --git a/packages/connections/src/descriptor.ts b/packages/connections/src/descriptor.ts index 7a89a2bad..53dfb35f7 100644 --- a/packages/connections/src/descriptor.ts +++ b/packages/connections/src/descriptor.ts @@ -98,13 +98,17 @@ export interface ConnectorDescriptor { /** * Which credential-provider plugin mediates this connector's secret at * run time — the sidecar registers `"http"` (Bearer), `"http-raw-authorization"` - * (raw `authorization` header, e.g. Linear), and `"http-x-api-key"` - * (`x-api-key` header, e.g. Exa, ScrapeCreators). Provider rows are - * seeded with this key; an unknown key means no mediated fetch resolves - * at capability time. + * (raw `authorization` header, e.g. Linear), `"http-x-api-key"` + * (`x-api-key` header, e.g. Exa, ScrapeCreators), and + * `"http-x-manus-api-key"` (`x-manus-api-key` header, Manus). Provider + * rows are seeded with this key; an unknown key means no mediated fetch + * resolves at capability time. */ readonly credentialPlugin: - "http" | "http-raw-authorization" | "http-x-api-key"; + | "http" + | "http-raw-authorization" + | "http-x-api-key" + | "http-x-manus-api-key"; /** Tool packages this connector's credential feeds — the settings card's * "Pinned by" line. Empty for inference-provider connectors, which feed * workflow deployments, not a specific tool package. */ diff --git a/packages/connections/src/index.ts b/packages/connections/src/index.ts index 5e4718585..23750297f 100644 --- a/packages/connections/src/index.ts +++ b/packages/connections/src/index.ts @@ -31,6 +31,7 @@ export { testGitHubCredential, testGranolaCredential, testLinearCredential, + testManusCredential, testScrapeCreatorsCredential, } from "./probes"; export { diff --git a/packages/connections/src/persist-credential.ts b/packages/connections/src/persist-credential.ts index bf99a30f8..eb33e864f 100644 --- a/packages/connections/src/persist-credential.ts +++ b/packages/connections/src/persist-credential.ts @@ -105,11 +105,18 @@ export async function persistConnectorCredential( plugin: args.descriptor.credentialPlugin, apiBaseUrl: args.baseURLOverride, } - : { - tenantId: args.tenantId, - name: args.descriptor.id, - plugin: args.descriptor.credentialPlugin, - }; + : args.descriptor.id === "manus" + ? { + tenantId: args.tenantId, + name: args.descriptor.id, + plugin: args.descriptor.credentialPlugin, + apiBaseUrl: "https://api.manus.ai", + } + : { + tenantId: args.tenantId, + name: args.descriptor.id, + plugin: args.descriptor.credentialPlugin, + }; const providerId = await runEnsureProvider( args.api, args.cookies, diff --git a/packages/connections/src/probes.ts b/packages/connections/src/probes.ts index cc4b401d3..fefec4ab9 100644 --- a/packages/connections/src/probes.ts +++ b/packages/connections/src/probes.ts @@ -120,3 +120,13 @@ export function testLinearCredential( body: JSON.stringify({ query: "{ viewer { id } } " }), }); } + +export function testManusCredential( + apiKey: string, + fetchImpl: FetchLike = fetch, +): Promise { + return probe("Manus", fetchImpl, "https://api.manus.ai/v2/skill.list", { + method: "GET", + headers: { "x-manus-api-key": apiKey }, + }); +} diff --git a/packages/connections/src/registry.ts b/packages/connections/src/registry.ts index aafdf1dc4..15cdea538 100644 --- a/packages/connections/src/registry.ts +++ b/packages/connections/src/registry.ts @@ -78,6 +78,7 @@ import { testGitHubCredential, testGranolaCredential, testLinearCredential, + testManusCredential, testScrapeCreatorsCredential, } from "./probes"; @@ -273,6 +274,17 @@ export const CONNECTOR_REGISTRY: Readonly> = probe: (apiKey) => testGranolaCredential(apiKey), description: "Pull meeting notes and transcripts into your agents.", }, + manus: { + id: "manus", + credentialPlugin: "http-x-manus-api-key", + displayName: "Manus", + authKind: "api-key", + docsUrl: "https://open.manus.ai/docs/v2/introduction", + feedsTools: ["@corbits/manus-tools"], + probe: (apiKey) => testManusCredential(apiKey), + description: + "Have Manus run tasks and produce files — including slide decks.", + }, exa: { id: "exa", // Exa authenticates via an `x-api-key` header, not `authorization` — diff --git a/packages/credential-providers/src/http-x-manus-api-key-provider.ts b/packages/credential-providers/src/http-x-manus-api-key-provider.ts new file mode 100644 index 000000000..9ef5147a6 --- /dev/null +++ b/packages/credential-providers/src/http-x-manus-api-key-provider.ts @@ -0,0 +1,121 @@ +// A workbench-owned `CredentialProvider`, sibling to +// `http-x-api-key-provider.ts`. Manus authenticates via `x-manus-api-key`, +// not `x-api-key` (Exa/ScrapeCreators) and not `authorization` in any +// shape. Registering this as its own plugin, keyed `http-x-manus-api-key`, +// lets a tenant's Manus provider row opt into the header its API actually +// wants without changing the existing `http-x-api-key` plugin. +// +// Every protection the sibling providers enforce is mirrored exactly: the +// handle is pinned to the credential's origin at shape time, every request +// is re-checked against that origin (a cross-origin target is refused), and +// every outbound request forces `redirect: "manual"` so a 3xx never lets a +// server redirect the key to a foreign host -- only the injected header +// NAME differs. + +import type { + CredentialProvider, + CredentialShapeContext, + HttpMediatedCredential, +} from "@intx/types"; + +/** + * The minimal call signature the shaped handle needs from `fetch`. Mirrors + * `@intx/harness`'s `FetchLike` so a caller can inject a stub in tests + * without pulling the full `fetch` type's extra members. + */ +export type FetchLike = ( + input: string | URL | Request, + init?: RequestInit, +) => Promise; + +export interface HttpXManusApiKeyCredentialProviderOptions { + /** + * The `fetch` the shaped handle delegates to once the request is + * origin-checked and the header is injected. Defaults to the global + * `fetch`; injectable so origin-pinning can be exercised without a + * network. + */ + fetch?: FetchLike; +} + +/** + * Provider plugin key a `credential` row's `plugin` column names to opt a + * binding into an `x-manus-api-key` header shape. + */ +export const HTTP_X_MANUS_API_KEY_PROVIDER_KEY = "http-x-manus-api-key"; + +/** + * Build the `http-x-manus-api-key` credential provider: an + * `HttpMediatedCredential` whose `fetch` sends the secret in the + * `x-manus-api-key` header. Register it alongside `@intx/harness`'s + * `builtinCredentialProviders()` in a `CredentialProviderRegistry` and + * point a provider row's `plugin` column at + * `HTTP_X_MANUS_API_KEY_PROVIDER_KEY` to opt that credential's bindings + * into this header shape. + */ +export function createHttpXManusApiKeyCredentialProvider( + opts?: HttpXManusApiKeyCredentialProviderOptions, +): CredentialProvider { + const fetchImpl: FetchLike = opts?.fetch ?? globalThis.fetch; + + return { + key: HTTP_X_MANUS_API_KEY_PROVIDER_KEY, + shape(context: CredentialShapeContext): HttpMediatedCredential { + const pinnedOrigin = new URL(context.origin).origin; + + return { + kind: "http", + async fetch( + input: string | URL | Request, + init?: RequestInit, + ): Promise { + const target = resolveTargetUrl(input, pinnedOrigin); + if (target.origin !== pinnedOrigin) { + throw new Error( + `http-x-manus-api-key credential is pinned to ${pinnedOrigin}; refusing cross-origin request to ${target.origin}`, + ); + } + + // Read the secret fresh on every call so a rotation of the + // underlying material cell reaches this handle without a rebuild. + const { secret } = context.readCurrentMaterial(); + + if (input instanceof Request) { + const headers = new Headers(input.headers); + headers.set("x-manus-api-key", secret); + return fetchImpl( + new Request(input, { headers, redirect: "manual" }), + ); + } + + const headers = new Headers(init?.headers); + headers.set("x-manus-api-key", secret); + return fetchImpl(target, { ...init, headers, redirect: "manual" }); + }, + dispose(): void { + // An x-manus-api-key http handle allocates no resources; nothing + // to release. + }, + }; + }, + }; +} + +/** + * Resolve the URL a request targets, matching `@intx/harness`'s own + * `resolveTargetUrl`: a relative string resolves against the pinned + * origin, an absolute string or URL keeps its own origin (refused above if + * it differs), and a `Request` already carries an absolute URL. + */ +function resolveTargetUrl( + input: string | URL | Request, + pinnedOrigin: string, +): URL { + if (typeof input === "string") { + return new URL(input, pinnedOrigin); + } + if (input instanceof URL) { + return input; + } + return new URL(input.url); +} diff --git a/packages/credential-providers/src/index.ts b/packages/credential-providers/src/index.ts index a7726317c..906346c41 100644 --- a/packages/credential-providers/src/index.ts +++ b/packages/credential-providers/src/index.ts @@ -13,6 +13,12 @@ export { } from "./http-x-api-key-provider"; export type { HttpXApiKeyCredentialProviderOptions } from "./http-x-api-key-provider"; +export { + createHttpXManusApiKeyCredentialProvider, + HTTP_X_MANUS_API_KEY_PROVIDER_KEY, +} from "./http-x-manus-api-key-provider"; +export type { HttpXManusApiKeyCredentialProviderOptions } from "./http-x-manus-api-key-provider"; + export { deriveResolvedBindings } from "./resolved-bindings"; export { diff --git a/packages/manus-tools/LICENSE b/packages/manus-tools/LICENSE new file mode 100644 index 000000000..c6487f4fd --- /dev/null +++ b/packages/manus-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/manus-tools/package.json b/packages/manus-tools/package.json new file mode 100644 index 000000000..ffd17b9af --- /dev/null +++ b/packages/manus-tools/package.json @@ -0,0 +1,31 @@ +{ + "name": "@corbits/manus-tools", + "private": true, + "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", + "version": "0.0.1", + "license": "LGPL-2.1-or-later", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "interchange": { + "credentials": [ + { + "handle": "manus" + } + ] + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "dependencies": { + "@intx/agent": "0.3.0", + "@intx/types": "0.3.0", + "arktype": "catalog:" + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:" + } +} diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts new file mode 100644 index 000000000..a9d92478c --- /dev/null +++ b/packages/manus-tools/src/client.ts @@ -0,0 +1,381 @@ +// A Manus OpenAPI v2 client. Every workbench consumer of Manus goes +// through the same parsed, validated shape. Callers that need graceful +// degradation (the tool bundle) catch at their own boundary rather than +// this client silently swallowing errors. +// +// Auth is never attached here: a mediated credential's `fetch` injects +// `x-manus-api-key` per call (see `@corbits/credential-providers`'s +// `http-x-manus-api-key` plugin). Tests inject a `fetchImpl` and assert +// that this module does not add an auth header of its own. +import { type } from "arktype"; + +export const DEFAULT_MANUS_BASE_URL = "https://api.manus.ai"; + +export interface ManusClientConfig { + /** Override for tests; defaults to the real Manus API host. */ + readonly baseUrl?: string; + readonly fetchImpl?: typeof fetch; +} + +const ManusErrorEnvelope = type({ + ok: "false", + "request_id?": "string", + error: { + code: "string", + message: "string", + }, +}); + +const ManusOkEnvelope = type({ + ok: "true", + "request_id?": "string", +}); + +const TaskAttachment = type({ + "type?": "string", + "filename?": "string", + "url?": "string", + "id?": "string", + "content_type?": "string", +}); +export type TaskAttachment = typeof TaskAttachment.infer; + +const TaskEvent = type({ + "id?": "string", + "type?": "string", + "timestamp?": "number", + "assistant_message?": { + "content?": "string", + "attachments?": TaskAttachment.array(), + }, + "status_update?": { + "agent_status?": "string", + "brief?": "string", + "description?": "string", + }, + "error_message?": { + "error_type?": "string", + "content?": "string", + }, +}); +export type TaskEvent = typeof TaskEvent.infer; + +export const CreateTaskResponse = type({ + ok: "true", + "request_id?": "string", + task_id: "string", + "task_title?": "string", + "task_url?": "string", + "share_url?": "string", + "share_visibility?": "string", +}); +export type CreateTaskResponse = typeof CreateTaskResponse.infer; + +export const ListMessagesResponse = type({ + ok: "true", + "request_id?": "string", + "task_id?": "string", + "messages?": TaskEvent.array(), + "has_more?": "boolean", + "next_cursor?": "string", +}); +export type ListMessagesResponse = typeof ListMessagesResponse.infer; + +export type ManusHttpMethod = "GET" | "POST"; + +export type OutputFile = { + readonly filename?: string; + readonly url?: string; + readonly id?: string; + readonly type?: string; + readonly content_type?: string; +}; + +function jsonHeaders(): Record { + return { "content-type": "application/json" }; +} + +function throwManusFailure( + status: number, + statusText: string, + body: unknown, +): never { + const parsed = ManusErrorEnvelope(body); + if (!(parsed instanceof type.errors)) { + throw new Error( + `Manus request failed: ${parsed.error.code}: ${parsed.error.message}`, + ); + } + throw new Error(`Manus request failed: ${status} ${statusText}`); +} + +function parseOkBody(body: unknown): Record { + const error = ManusErrorEnvelope(body); + if (!(error instanceof type.errors)) { + throw new Error( + `Manus request failed: ${error.error.code}: ${error.error.message}`, + ); + } + const parsed = ManusOkEnvelope(body); + if (parsed instanceof type.errors) { + throw new Error( + `Manus response did not match the expected shape: ${parsed.summary}`, + ); + } + if (typeof body !== "object" || body === null || Array.isArray(body)) { + throw new Error( + "Manus response did not match the expected shape: not an object", + ); + } + return body as Record; +} + +function queryString(params: Readonly>): string { + const search = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined || value === null) continue; + if ( + typeof value === "string" || + typeof value === "number" || + typeof value === "boolean" + ) { + search.set(key, String(value)); + } + } + const encoded = search.toString(); + return encoded === "" ? "" : `?${encoded}`; +} + +/** + * Calls one Manus v2 RPC path. GET arguments become query params; POST + * arguments become a JSON body. Throws on transport, HTTP, `ok: false`, + * or envelope-shape failure. + */ +export async function manusRequest( + config: ManusClientConfig, + args: { + readonly method: ManusHttpMethod; + readonly path: string; + readonly params?: Readonly>; + }, +): Promise> { + const doFetch = config.fetchImpl ?? fetch; + const base = config.baseUrl ?? DEFAULT_MANUS_BASE_URL; + const params = args.params ?? {}; + const url = + args.method === "GET" + ? `${base}${args.path}${queryString(params)}` + : `${base}${args.path}`; + const response = + args.method === "GET" + ? await doFetch(url, { method: "GET" }) + : await doFetch(url, { + method: "POST", + headers: jsonHeaders(), + body: JSON.stringify(params), + }); + let body: unknown; + try { + body = await response.json(); + } catch (cause) { + throw new Error( + `Manus request failed: ${response.status} ${response.statusText}`, + { cause }, + ); + } + if (!response.ok) { + throwManusFailure(response.status, response.statusText, body); + } + return parseOkBody(body); +} + +export type CreateTaskParams = { + readonly content: string; + readonly title?: string; + readonly project_id?: string; + readonly locale?: string; + readonly interactive_mode?: boolean; + readonly hide_in_task_list?: boolean; + readonly share_visibility?: string; + readonly agent_profile?: string; +}; + +export async function createTask( + config: ManusClientConfig, + params: CreateTaskParams, +): Promise { + const body: Record = { + message: { content: params.content }, + }; + if (params.title !== undefined) body["title"] = params.title; + if (params.project_id !== undefined) body["project_id"] = params.project_id; + if (params.locale !== undefined) body["locale"] = params.locale; + if (params.interactive_mode !== undefined) { + body["interactive_mode"] = params.interactive_mode; + } + if (params.hide_in_task_list !== undefined) { + body["hide_in_task_list"] = params.hide_in_task_list; + } + if (params.share_visibility !== undefined) { + body["share_visibility"] = params.share_visibility; + } + if (params.agent_profile !== undefined) { + body["agent_profile"] = params.agent_profile; + } + const raw = await manusRequest(config, { + method: "POST", + path: "/v2/task.create", + params: body, + }); + const parsed = CreateTaskResponse(raw); + if (parsed instanceof type.errors) { + throw new Error( + `Manus create-task response did not match the expected shape: ${parsed.summary}`, + ); + } + return parsed; +} + +export type ListMessagesParams = { + readonly task_id: string; + readonly limit?: number; + readonly cursor?: string; + readonly order?: string; + readonly verbose?: boolean; + readonly slides_format?: string; +}; + +export async function listTaskMessages( + config: ManusClientConfig, + params: ListMessagesParams, +): Promise { + const query: Record = { task_id: params.task_id }; + if (params.limit !== undefined) query["limit"] = params.limit; + if (params.cursor !== undefined) query["cursor"] = params.cursor; + if (params.order !== undefined) query["order"] = params.order; + if (params.verbose !== undefined) query["verbose"] = params.verbose; + if (params.slides_format !== undefined) { + query["slides_format"] = params.slides_format; + } + const raw = await manusRequest(config, { + method: "GET", + path: "/v2/task.listMessages", + params: query, + }); + const parsed = ListMessagesResponse(raw); + if (parsed instanceof type.errors) { + throw new Error( + `Manus list-messages response did not match the expected shape: ${parsed.summary}`, + ); + } + return parsed; +} + +export function latestAgentStatus( + messages: readonly TaskEvent[] | undefined, +): string | undefined { + if (messages === undefined) return undefined; + let status: string | undefined; + for (const event of messages) { + const next = event.status_update?.agent_status; + if (next !== undefined) status = next; + } + return status; +} + +export function extractOutputFiles( + messages: readonly TaskEvent[] | undefined, +): readonly OutputFile[] { + if (messages === undefined) return []; + const files: OutputFile[] = []; + for (const event of messages) { + const attachments = event.assistant_message?.attachments ?? []; + for (const attachment of attachments) { + if ( + attachment.filename === undefined && + attachment.url === undefined && + attachment.id === undefined + ) { + continue; + } + const file: { + filename?: string; + url?: string; + id?: string; + type?: string; + content_type?: string; + } = {}; + if (attachment.filename !== undefined) + file.filename = attachment.filename; + if (attachment.url !== undefined) file.url = attachment.url; + if (attachment.id !== undefined) file.id = attachment.id; + if (attachment.type !== undefined) file.type = attachment.type; + if (attachment.content_type !== undefined) { + file.content_type = attachment.content_type; + } + files.push(file); + } + } + return files; +} + +const TERMINAL_STATUSES = new Set(["stopped", "error"]); + +export type CreateSlideDeckParams = CreateTaskParams & { + readonly pollIntervalMs?: number; + readonly maxPolls?: number; +}; + +/** + * Creates a task whose prompt asks Manus to produce a slide deck, then + * polls `task.listMessages` until the agent stops (or errors) and returns + * any output files so a caller can retrieve them. + */ +export async function createSlideDeck( + config: ManusClientConfig, + params: CreateSlideDeckParams, +): Promise<{ + readonly task_id: string; + readonly task_title?: string; + readonly task_url?: string; + readonly agent_status?: string; + readonly files: readonly OutputFile[]; + readonly error?: string; +}> { + const created = await createTask(config, params); + const pollIntervalMs = params.pollIntervalMs ?? 1500; + const maxPolls = params.maxPolls ?? 40; + let messages: ListMessagesResponse | undefined; + for (let i = 0; i < maxPolls; i += 1) { + messages = await listTaskMessages(config, { + task_id: created.task_id, + slides_format: "pdf", + }); + const status = latestAgentStatus(messages.messages); + if (status !== undefined && TERMINAL_STATUSES.has(status)) break; + if (i < maxPolls - 1 && pollIntervalMs > 0) { + await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + } + } + const status = latestAgentStatus(messages?.messages); + const files = extractOutputFiles(messages?.messages); + const errorEvent = messages?.messages?.find((event) => event.error_message); + const result: { + task_id: string; + task_title?: string; + task_url?: string; + agent_status?: string; + files: readonly OutputFile[]; + error?: string; + } = { + task_id: created.task_id, + files, + }; + if (created.task_title !== undefined) result.task_title = created.task_title; + if (created.task_url !== undefined) result.task_url = created.task_url; + if (status !== undefined) result.agent_status = status; + if (errorEvent?.error_message?.content !== undefined) { + result.error = errorEvent.error_message.content; + } + return result; +} diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts new file mode 100644 index 000000000..44a342d21 --- /dev/null +++ b/packages/manus-tools/src/index.ts @@ -0,0 +1,28 @@ +export { + CreateTaskResponse, + ListMessagesResponse, + createSlideDeck, + createTask, + extractOutputFiles, + latestAgentStatus, + listTaskMessages, + manusRequest, + DEFAULT_MANUS_BASE_URL, +} from "./client"; +export type { + CreateSlideDeckParams, + CreateTaskParams, + ListMessagesParams, + ManusClientConfig, + OutputFile, + TaskAttachment, + TaskEvent, +} from "./client"; +export { + CREATE_SLIDES_TOOL, + MANUS_CREDENTIAL_HANDLE, + MANUS_ENDPOINTS, + MANUS_NOT_CONNECTED, + manusTools, +} from "./tool"; +export type { ManusEnv } from "./tool"; diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts new file mode 100644 index 000000000..996d26d89 --- /dev/null +++ b/packages/manus-tools/src/tool.ts @@ -0,0 +1,706 @@ +// The Manus tool bundle: an agent-facing wrapper around `./client.ts` +// that never throws. A missing credential or a failed call both come +// back as a completed `ToolResult` with `isError: true`. +import { defineTool } from "@intx/agent"; +import type { BaseEnv } from "@intx/agent"; +import type { CredentialCapability } from "@intx/types"; +import type { ToolCall, ToolResult } from "@intx/types/runtime"; + +import { + createSlideDeck, + createTask, + listTaskMessages, + manusRequest, + type ManusClientConfig, + type ManusHttpMethod, +} from "./client"; + +/** The handle this package declares in `interchange.credentials`. */ +export const MANUS_CREDENTIAL_HANDLE = "manus"; + +export const MANUS_NOT_CONNECTED = "Manus is not connected for this user."; + +export const CREATE_SLIDES_TOOL = "create_slides"; + +type JsonSchemaProperty = { + readonly type: string; + readonly description: string; +}; + +type EndpointSpec = { + readonly name: string; + readonly method: ManusHttpMethod; + readonly path: string; + readonly description: string; + readonly required: readonly string[]; + readonly properties: Readonly>; +}; + +const STRING = (description: string): JsonSchemaProperty => ({ + type: "string", + description, +}); +const NUMBER = (description: string): JsonSchemaProperty => ({ + type: "number", + description, +}); +const BOOLEAN = (description: string): JsonSchemaProperty => ({ + type: "boolean", + description, +}); +const OBJECT = (description: string): JsonSchemaProperty => ({ + type: "object", + description, +}); + +export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ + { + name: "task_create", + method: "POST", + path: "/v2/task.create", + description: + "Creates a Manus task. Pass content as the prompt text (sent as message.content). Poll task_list_msgs for progress.", + required: ["content"], + properties: { + content: STRING("Prompt text that starts the task."), + title: STRING("Optional custom task title."), + project_id: STRING("Project to associate this task with."), + locale: STRING("Output locale, e.g. en or zh-CN."), + interactive_mode: BOOLEAN( + "When true, the agent may pause to ask questions.", + ), + hide_in_task_list: BOOLEAN( + "When true, hide the task from the Manus task list.", + ), + share_visibility: STRING("private, team, or public."), + agent_profile: STRING("manus-1.6, manus-1.6-lite, or manus-1.6-max."), + }, + }, + { + name: "task_detail", + method: "GET", + path: "/v2/task.detail", + description: "Fetches one Manus task by task_id.", + required: ["task_id"], + properties: { task_id: STRING("Task id.") }, + }, + { + name: "task_list", + method: "GET", + path: "/v2/task.list", + description: "Lists Manus tasks.", + required: [], + properties: { + limit: NUMBER("Page size."), + cursor: STRING("Pagination cursor."), + order: STRING("Sort order."), + scope: STRING("List scope."), + agent_id: STRING("Filter by agent id."), + project_id: STRING("Filter by project id."), + }, + }, + { + name: "task_update", + method: "POST", + path: "/v2/task.update", + description: + "Updates a Manus task's title, visibility, or list visibility.", + required: ["task_id"], + properties: { + task_id: STRING("Task id."), + title: STRING("New title."), + share_visibility: STRING("private, team, or public."), + enable_visible_in_task_list: BOOLEAN( + "Show the task in the Manus task list.", + ), + }, + }, + { + name: "task_stop", + method: "POST", + path: "/v2/task.stop", + description: "Stops a running Manus task.", + required: ["task_id"], + properties: { task_id: STRING("Task id.") }, + }, + { + name: "task_delete", + method: "POST", + path: "/v2/task.delete", + description: "Deletes a Manus task.", + required: ["task_id"], + properties: { task_id: STRING("Task id.") }, + }, + { + name: "task_send_msg", + method: "POST", + path: "/v2/task.sendMessage", + description: "Sends a follow-up message to an existing Manus task.", + required: ["task_id", "content"], + properties: { + task_id: STRING("Task id."), + content: STRING("Follow-up prompt text (sent as message.content)."), + agent_profile: STRING("Optional agent profile override."), + }, + }, + { + name: "task_list_msgs", + method: "GET", + path: "/v2/task.listMessages", + description: + "Lists messages and status events for a Manus task. Poll until agent_status is stopped. Output files appear as assistant_message attachments.", + required: ["task_id"], + properties: { + task_id: STRING("Task id."), + limit: NUMBER("Page size."), + cursor: STRING("Pagination cursor."), + order: STRING("Sort order."), + verbose: BOOLEAN("Include tool/plan events."), + slides_format: STRING("Preferred slides download format, e.g. pdf."), + }, + }, + { + name: "task_confirm", + method: "POST", + path: "/v2/task.confirmAction", + description: + "Confirms a waiting Manus task action (event_id from a waiting status).", + required: ["task_id", "event_id"], + properties: { + task_id: STRING("Task id."), + event_id: STRING("Waiting event id."), + input: OBJECT("Optional confirmation input object."), + }, + }, + { + name: "project_create", + method: "POST", + path: "/v2/project.create", + description: "Creates a Manus project.", + required: ["name"], + properties: { + name: STRING("Project name."), + instruction: STRING("Optional project instruction."), + }, + }, + { + name: "project_list", + method: "GET", + path: "/v2/project.list", + description: "Lists Manus projects.", + required: [], + properties: {}, + }, + { + name: "skill_list", + method: "GET", + path: "/v2/skill.list", + description: "Lists available Manus skills.", + required: [], + properties: { project_id: STRING("Optional project id to scope skills.") }, + }, + { + name: "agent_list", + method: "GET", + path: "/v2/agent.list", + description: "Lists Manus agents.", + required: [], + properties: {}, + }, + { + name: "agent_detail", + method: "GET", + path: "/v2/agent.detail", + description: "Fetches one Manus agent by agent_id.", + required: ["agent_id"], + properties: { agent_id: STRING("Agent id.") }, + }, + { + name: "agent_update", + method: "POST", + path: "/v2/agent.update", + description: "Updates a Manus agent's nickname or about text.", + required: ["agent_id"], + properties: { + agent_id: STRING("Agent id."), + nickname: STRING("New nickname."), + about: STRING("New about text."), + }, + }, + { + name: "file_upload", + method: "POST", + path: "/v2/file.upload", + description: + "Creates a pending Manus file and returns a presigned upload_url. PUT the file bytes to that URL before it expires.", + required: ["filename"], + properties: { filename: STRING("File name to upload.") }, + }, + { + name: "file_detail", + method: "GET", + path: "/v2/file.detail", + description: "Fetches one Manus file by file_id.", + required: ["file_id"], + properties: { file_id: STRING("File id.") }, + }, + { + name: "file_delete", + method: "POST", + path: "/v2/file.delete", + description: "Deletes a Manus file.", + required: ["file_id"], + properties: { file_id: STRING("File id.") }, + }, + { + name: "webhook_create", + method: "POST", + path: "/v2/webhook.create", + description: "Creates a Manus webhook.", + required: ["url"], + properties: { url: STRING("Webhook callback URL.") }, + }, + { + name: "webhook_list", + method: "GET", + path: "/v2/webhook.list", + description: "Lists Manus webhooks.", + required: [], + properties: {}, + }, + { + name: "webhook_delete", + method: "POST", + path: "/v2/webhook.delete", + description: "Deletes a Manus webhook.", + required: ["webhook_id"], + properties: { webhook_id: STRING("Webhook id.") }, + }, + { + name: "webhook_pubkey", + method: "GET", + path: "/v2/webhook.publicKey", + description: "Returns the Manus webhook signing public key.", + required: [], + properties: {}, + }, + { + name: "usage_list", + method: "GET", + path: "/v2/usage.list", + description: "Lists Manus usage records.", + required: [], + properties: { + limit: NUMBER("Page size."), + cursor: STRING("Pagination cursor."), + }, + }, + { + name: "usage_credits", + method: "GET", + path: "/v2/usage.availableCredits", + description: "Returns available Manus credits.", + required: [], + properties: {}, + }, + { + name: "usage_team_stat", + method: "GET", + path: "/v2/usage.teamStatistic", + description: "Returns Manus team usage statistics.", + required: [], + properties: { + start_date: NUMBER("Start date as a unix timestamp."), + end_date: NUMBER("End date as a unix timestamp."), + }, + }, + { + name: "usage_team_log", + method: "GET", + path: "/v2/usage.teamLog", + description: "Returns the Manus team usage log.", + required: [], + properties: { + limit: NUMBER("Page size."), + cursor: STRING("Pagination cursor."), + start_date: NUMBER("Start date as a unix timestamp."), + end_date: NUMBER("End date as a unix timestamp."), + sort_by: STRING("Sort field."), + is_asc: BOOLEAN("Sort ascending when true."), + }, + }, + { + name: "connector_list", + method: "GET", + path: "/v2/connector.list", + description: "Lists Manus connectors available to this account.", + required: [], + properties: {}, + }, + { + name: "browser_online", + method: "GET", + path: "/v2/browser.onlineList", + description: "Lists online Manus browser clients.", + required: [], + properties: {}, + }, + { + name: "website_status", + method: "GET", + path: "/v2/website.status", + description: "Returns Manus website publish status for a task or website.", + required: [], + properties: { + task_id: STRING("Task id."), + website_id: STRING("Website id."), + }, + }, + { + name: "website_publish", + method: "POST", + path: "/v2/website.publish", + description: "Publishes a Manus website.", + required: [], + properties: { + task_id: STRING("Task id."), + website_id: STRING("Website id."), + visibility: STRING("Visibility."), + }, + }, + { + name: "website_update", + method: "POST", + path: "/v2/website.update", + description: "Updates a Manus website title or visibility.", + required: [], + properties: { + task_id: STRING("Task id."), + website_id: STRING("Website id."), + title: STRING("New title."), + visibility: STRING("Visibility."), + }, + }, + { + name: "website_ckpts", + method: "GET", + path: "/v2/website.listCheckpoints", + description: "Lists Manus website checkpoints.", + required: [], + properties: { + task_id: STRING("Task id."), + website_id: STRING("Website id."), + }, + }, +]; + +export interface ManusEnv extends BaseEnv { + readonly credentials?: CredentialCapability; +} + +function notConnectedResult(callId: string): ToolResult { + return { + callId, + content: MANUS_NOT_CONNECTED, + isError: true, + }; +} + +async function resolveManusCredential( + env: ManusEnv, +): Promise<{ fetchImpl: typeof fetch } | null> { + if (env.credentials === undefined) return null; + try { + const mediated = await env.credentials.resolve(MANUS_CREDENTIAL_HANDLE); + return { fetchImpl: mediated.fetch as unknown as typeof fetch }; + } catch { + return null; + } +} + +function asClientConfig(credential: { + fetchImpl: typeof fetch; +}): ManusClientConfig { + return { fetchImpl: credential.fetchImpl }; +} + +function stringArg(call: ToolCall, key: string): string | undefined { + const value = call.arguments[key]; + return typeof value === "string" ? value : undefined; +} + +function pickParams( + call: ToolCall, + keys: readonly string[], +): Record { + const params: Record = {}; + for (const key of keys) { + const value = call.arguments[key]; + if (value !== undefined) params[key] = value; + } + return params; +} + +function missingRequired( + call: ToolCall, + required: readonly string[], +): string | undefined { + for (const key of required) { + const value = call.arguments[key]; + if (value === undefined || value === "") return key; + } + return undefined; +} + +function errorResult(callId: string, err: unknown): ToolResult { + return { + callId, + content: err instanceof Error ? err.message : String(err), + isError: true, + }; +} + +async function runEndpoint( + env: ManusEnv, + call: ToolCall, + spec: EndpointSpec, +): Promise { + const credential = await resolveManusCredential(env); + if (credential === null) return notConnectedResult(call.id); + const missing = missingRequired(call, spec.required); + if (missing !== undefined) { + return { + callId: call.id, + content: `${spec.name} requires a non-empty ${missing} argument`, + isError: true, + }; + } + const params = pickParams(call, Object.keys(spec.properties)); + if (spec.name === "task_create") { + const content = stringArg(call, "content"); + if (content === undefined || content === "") { + return { + callId: call.id, + content: "task_create requires a non-empty content argument", + isError: true, + }; + } + try { + const created = await createTask(asClientConfig(credential), { + content, + ...optionalCreateFields(call), + }); + return { callId: call.id, content: JSON.stringify(created) }; + } catch (err) { + return errorResult(call.id, err); + } + } + if (spec.name === "task_send_msg") { + const content = stringArg(call, "content"); + const taskId = stringArg(call, "task_id"); + if (content === undefined || taskId === undefined) { + return { + callId: call.id, + content: "task_send_msg requires task_id and content", + isError: true, + }; + } + const body: Record = { + task_id: taskId, + message: { content }, + }; + const profile = stringArg(call, "agent_profile"); + if (profile !== undefined) body["agent_profile"] = profile; + try { + const result = await manusRequest(asClientConfig(credential), { + method: spec.method, + path: spec.path, + params: body, + }); + return { callId: call.id, content: JSON.stringify(result) }; + } catch (err) { + return errorResult(call.id, err); + } + } + if (spec.name === "task_list_msgs") { + const taskId = stringArg(call, "task_id"); + if (taskId === undefined || taskId === "") { + return { + callId: call.id, + content: "task_list_msgs requires a non-empty task_id argument", + isError: true, + }; + } + try { + const listed = await listTaskMessages(asClientConfig(credential), { + task_id: taskId, + ...optionalListMessageFields(call), + }); + return { callId: call.id, content: JSON.stringify(listed) }; + } catch (err) { + return errorResult(call.id, err); + } + } + try { + const result = await manusRequest(asClientConfig(credential), { + method: spec.method, + path: spec.path, + params, + }); + return { callId: call.id, content: JSON.stringify(result) }; + } catch (err) { + return errorResult(call.id, err); + } +} + +function optionalCreateFields(call: ToolCall): { + title?: string; + project_id?: string; + locale?: string; + interactive_mode?: boolean; + hide_in_task_list?: boolean; + share_visibility?: string; + agent_profile?: string; +} { + const fields: { + title?: string; + project_id?: string; + locale?: string; + interactive_mode?: boolean; + hide_in_task_list?: boolean; + share_visibility?: string; + agent_profile?: string; + } = {}; + const title = stringArg(call, "title"); + if (title !== undefined) fields.title = title; + const projectId = stringArg(call, "project_id"); + if (projectId !== undefined) fields.project_id = projectId; + const locale = stringArg(call, "locale"); + if (locale !== undefined) fields.locale = locale; + if (typeof call.arguments["interactive_mode"] === "boolean") { + fields.interactive_mode = call.arguments["interactive_mode"]; + } + if (typeof call.arguments["hide_in_task_list"] === "boolean") { + fields.hide_in_task_list = call.arguments["hide_in_task_list"]; + } + const visibility = stringArg(call, "share_visibility"); + if (visibility !== undefined) fields.share_visibility = visibility; + const profile = stringArg(call, "agent_profile"); + if (profile !== undefined) fields.agent_profile = profile; + return fields; +} + +function optionalListMessageFields(call: ToolCall): { + limit?: number; + cursor?: string; + order?: string; + verbose?: boolean; + slides_format?: string; +} { + const fields: { + limit?: number; + cursor?: string; + order?: string; + verbose?: boolean; + slides_format?: string; + } = {}; + if (typeof call.arguments["limit"] === "number") { + fields.limit = call.arguments["limit"]; + } + const cursor = stringArg(call, "cursor"); + if (cursor !== undefined) fields.cursor = cursor; + const order = stringArg(call, "order"); + if (order !== undefined) fields.order = order; + if (typeof call.arguments["verbose"] === "boolean") { + fields.verbose = call.arguments["verbose"]; + } + const slidesFormat = stringArg(call, "slides_format"); + if (slidesFormat !== undefined) fields.slides_format = slidesFormat; + return fields; +} + +async function runCreateSlides( + env: ManusEnv, + call: ToolCall, +): Promise { + const credential = await resolveManusCredential(env); + if (credential === null) return notConnectedResult(call.id); + const prompt = stringArg(call, "prompt"); + if (prompt === undefined || prompt === "") { + return { + callId: call.id, + content: `${CREATE_SLIDES_TOOL} requires a non-empty prompt argument`, + isError: true, + }; + } + const title = stringArg(call, "title"); + try { + const result = await createSlideDeck(asClientConfig(credential), { + content: prompt, + ...(title !== undefined ? { title } : {}), + }); + return { callId: call.id, content: JSON.stringify(result) }; + } catch (err) { + return errorResult(call.id, err); + } +} + +const CREATE_SLIDES_DEFINITION = { + name: CREATE_SLIDES_TOOL, + description: + "Creates a Manus task that produces a slide deck from a prompt, waits until the agent stops, and returns output files (filename, url, id) so they can be retrieved.", + inputSchema: { + type: "object", + properties: { + prompt: { + type: "string", + description: "What the slide deck should cover.", + }, + title: { + type: "string", + description: "Optional task title.", + }, + }, + required: ["prompt"], + }, +} as const; + +/** + * The `@corbits/manus-tools` bundle factory. The bundle id's local + * segment is kept short — the wire encoding of `:` must + * fit the 64-char OpenAI function-name cap. + */ +export const manusTools = defineTool({ + id: "@corbits/manus-tools/mn", + requires: ["credentials"], + definitions: [ + { name: CREATE_SLIDES_TOOL }, + ...MANUS_ENDPOINTS.map((spec) => ({ name: spec.name })), + ], + factory: (env) => ({ + definitions: [ + CREATE_SLIDES_DEFINITION, + ...MANUS_ENDPOINTS.map((spec) => ({ + name: spec.name, + description: spec.description, + inputSchema: { + type: "object", + properties: spec.properties, + ...(spec.required.length > 0 ? { required: [...spec.required] } : {}), + }, + })), + ], + run: (call, _signal) => { + if (call.name === CREATE_SLIDES_TOOL) return runCreateSlides(env, call); + const spec = MANUS_ENDPOINTS.find((entry) => entry.name === call.name); + if (spec === undefined) { + return Promise.resolve({ + callId: call.id, + content: `Unknown Manus tool: ${call.name}`, + isError: true, + }); + } + return runEndpoint(env, call, spec); + }, + }), +}); diff --git a/packages/manus-tools/tsconfig.json b/packages/manus-tools/tsconfig.json new file mode 100644 index 000000000..12ec9a862 --- /dev/null +++ b/packages/manus-tools/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["bun"] + }, + "include": ["src"] +} diff --git a/packages/plugins-ui/src/plugin-meta.ts b/packages/plugins-ui/src/plugin-meta.ts index 6fa64d63d..fd8b93524 100644 --- a/packages/plugins-ui/src/plugin-meta.ts +++ b/packages/plugins-ui/src/plugin-meta.ts @@ -13,6 +13,7 @@ import { type Icon, MagnifyingGlass, Microphone, + Stack, } from "@corbits/icons"; export type PluginCategory = @@ -32,6 +33,7 @@ export const PLUGIN_CATEGORY_ORDER: readonly PluginCategory[] = [ const CATEGORY_BY_ID: Readonly> = { granola: "Productivity", + manus: "Productivity", notion: "Productivity", zoom: "Communication", slack: "Communication", @@ -68,6 +70,8 @@ const OUTCOME_BY_ID: Readonly> = { huggingface: "Routes your agents' inference through Hugging Face-hosted models.", granola: "Lets agents read your Granola call notes and post-call summaries.", + manus: + "Lets agents run Manus tasks and retrieve files — including slide decks.", exa: "Lets agents run live web search and research lookups.", scrapecreators: "Lets agents pull Reddit threads and creator content.", linear: "Lets agents read and update your Linear issues.", @@ -79,6 +83,7 @@ const OUTCOME_BY_ID: Readonly> = { // than reaching for a third-party brand icon set. const ICON_BY_ID: Readonly> = { granola: Microphone, + manus: Stack, exa: MagnifyingGlass, scrapecreators: ChatCircle, linear: GitBranch, diff --git a/packages/settings-ui/src/connections-pinned-by.ts b/packages/settings-ui/src/connections-pinned-by.ts index 8c6d73534..a14777a5b 100644 --- a/packages/settings-ui/src/connections-pinned-by.ts +++ b/packages/settings-ui/src/connections-pinned-by.ts @@ -22,4 +22,5 @@ export const CONNECTOR_PINNED_WORKFLOWS: Readonly< attio: ["attio-task-agent"], scrapecreators: ["reddit-opportunity-scanner"], github: ["code-review"], + manus: ["assistant"], }; diff --git a/packages/tool-registry-publish/src/registry.ts b/packages/tool-registry-publish/src/registry.ts index 9911d9214..bdf222e1c 100644 --- a/packages/tool-registry-publish/src/registry.ts +++ b/packages/tool-registry-publish/src/registry.ts @@ -36,6 +36,7 @@ export const CORBITS_TOOL_PACKAGE_DIRS: readonly string[] = [ new URL("../../github-tools", import.meta.url).pathname, new URL("../../web-search-tools", import.meta.url).pathname, new URL("../../granola-tools", import.meta.url).pathname, + new URL("../../manus-tools", import.meta.url).pathname, new URL("../../linear-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 diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index f457db824..5cd55e201 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -25,6 +25,7 @@ import type { AgentDefinition, InferencePreference } from "@intx/agent"; import { defineWorkflow, step } from "@intx/workflow"; import type { WorkflowDefinition } from "@intx/workflow"; import type { ToolPackagePin } from "@intx/types/tool-packages"; +import type { CredentialBinding } from "@intx/types"; export const ASSISTANT_WORKFLOW_ID = "wf_assistant"; export const ASSISTANT_STEP_ID = "assistant"; @@ -50,6 +51,23 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, + { name: "@corbits/manus-tools", version: "0.0.1" }, +]; + +/** + * Binds `@corbits/manus-tools`' declared "manus" handle to a tenant-owned + * Manus credential. The launch resolves this against + * `buildCredentialDelivery`, materializing a consumer-scoped grant for + * the pinned package so Myra can call Manus when the connector is + * connected. + */ +export const ASSISTANT_CREDENTIAL_BINDINGS: readonly CredentialBinding[] = [ + { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant", + }, ]; /** @@ -268,6 +286,7 @@ export function buildAssistantWorkflow( return defineWorkflow({ id: ASSISTANT_WORKFLOW_ID, trigger: { type: "mail", to: input.triggerAddress }, + credentialBindings: ASSISTANT_CREDENTIAL_BINDINGS, steps: { assistant: step({ agent: { From bc4c76c7b93a8b789ea14ff42f99cf4c864351c2 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 16:45:28 -0700 Subject: [PATCH 37/75] Update docs: Manus plugin --- docs/credential-wiring.md | 24 ++++++++++----- packages/credential-providers/README.md | 8 +++++ packages/manus-tools/README.md | 40 +++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 7 deletions(-) create mode 100644 packages/manus-tools/README.md diff --git a/docs/credential-wiring.md b/docs/credential-wiring.md index 32faf5db1..8cf35968f 100644 --- a/docs/credential-wiring.md +++ b/docs/credential-wiring.md @@ -1,7 +1,7 @@ # Credential wiring: from connect to tool call (CL-6032) How a tenant's connected credential (Settings · Connections) reaches the -tool call a workflow step makes, and the two `CredentialProvider` plugins +tool call a workflow step makes, and the `CredentialProvider` plugins that shape it. ## The chain @@ -36,8 +36,8 @@ step-agent-tools.ts`) derives each tool factory's consumer identity ## Provider plugins A credential's `provider` row names a `plugin` -- the `CredentialProvider` -key its bindings shape through. Two are registered in the sidecar's -`CredentialProviderRegistry`: +key its bindings shape through. The sidecar's `CredentialProviderRegistry` +registers: - **`http`** -- `@intx/harness`'s vendored `createHttpCredentialProvider`. Sends `authorization: Bearer `. The default for any bearer-token @@ -47,14 +47,24 @@ key its bindings shape through. Two are registered in the sidecar's verbatim in `authorization`, no `Bearer ` prefix. Linear's API expects this raw-key convention, not a bearer token, so a Linear provider row MUST set `plugin: "http-raw-authorization"` -- seeding it as `"http"` - sends the wrong header shape and Linear rejects the call. Both plugins - mirror the same origin-pinning and `redirect: "manual"` protections; - only the injected header value differs. + sends the wrong header shape and Linear rejects the call. +- **`http-x-api-key`** -- `@corbits/credential-providers`'s + `createHttpXApiKeyCredentialProvider`. Sends the secret in `x-api-key`. + Exa and ScrapeCreators expect this header, not `authorization`. +- **`http-x-manus-api-key`** -- `@corbits/credential-providers`'s + `createHttpXManusApiKeyCredentialProvider`. Sends the secret in + `x-manus-api-key`. A Manus provider row MUST set this plugin -- seeding + it as `"http"` or `"http-x-api-key"` sends the wrong header name and + Manus rejects the call. + +All four plugins mirror the same origin-pinning and `redirect: "manual"` +protections; only the injected header differs. `packages/connections` (the Connections-surface registry) is the other place this plugin id needs to be correct: whatever seeds or registers a Linear provider row there must set `plugin: "http-raw-authorization"`, -matching this doc, not the `"http"` default other connectors use. +and a Manus row must set `plugin: "http-x-manus-api-key"`, matching this +doc, not the `"http"` default other connectors use. ## Trust boundary diff --git a/packages/credential-providers/README.md b/packages/credential-providers/README.md index 93f9e3aaf..372b4b8c3 100644 --- a/packages/credential-providers/README.md +++ b/packages/credential-providers/README.md @@ -43,6 +43,14 @@ same origin-pinning and `redirect: "manual"` protections; only the injected header name differs. A tenant's Exa or ScrapeCreators provider row must set `plugin: "http-x-api-key"`. +## `http-x-manus-api-key` + +Manus authenticates via `x-manus-api-key`, not `x-api-key` and not +`authorization` in any shape. `createHttpXManusApiKeyCredentialProvider` +(key `http-x-manus-api-key`) mirrors the same origin-pinning and +`redirect: "manual"` protections; only the injected header name differs. +A tenant's Manus provider row must set `plugin: "http-x-manus-api-key"`. + ## `resolved-bindings` `deriveResolvedBindings` reshapes a launch-time `CredentialDelivery` diff --git a/packages/manus-tools/README.md b/packages/manus-tools/README.md new file mode 100644 index 000000000..219937af3 --- /dev/null +++ b/packages/manus-tools/README.md @@ -0,0 +1,40 @@ +# @corbits/manus-tools + +Manus OpenAPI v2 integration: a typed client and an `@intx/agent` tool +bundle covering tasks, files, skills, projects, agents, webhooks, usage, +connectors, browser, and website endpoints. Slide-deck creation is the +passing demo — `create_slides` starts a task, polls messages until the +agent stops, and surfaces output files (filename, url, id). + +## Credential + +The bundle's env carries `credentials`, the harness's consumer-gated +`CredentialCapability`. When it is absent, or `credentials.resolve("manus")` +throws, the tool never throws itself: it returns a completed result with +`isError: true` and content `"Manus is not connected for this user."` + +This package declares one credential handle, `manus`, in +`package.json`'s `interchange.credentials`. Connect Manus once in Settings +· Connections (API key via `x-manus-api-key`). The client never attaches +that header — the `http-x-manus-api-key` credential plugin injects it. +The assistant workflow pins `@corbits/manus-tools` so the tools exist; it +does not require a Manus credential binding. An unconnected tenant +degrades at tool time to "Manus is not connected for this user." like +Granola, rather than failing launch. + +## Usage + +```ts +import { manusTools } from "@corbits/manus-tools"; + +const agent = defineAgent({ + // ... + tools: [manusTools], +}); +``` + +## Running tests + +``` +cd packages/manus-tools && bun test +``` From ae6c30535e1f61f610dee36d5d288e2438f010eb Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:07:57 -0700 Subject: [PATCH 38/75] Drop required Manus credential binding from the assistant --- workflows/assistant/src/index.ts | 18 ------------------ workflows/assistant/test/definition.test.ts | 16 +++++----------- 2 files changed, 5 insertions(+), 29 deletions(-) diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 5cd55e201..a1fc16884 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -25,7 +25,6 @@ import type { AgentDefinition, InferencePreference } from "@intx/agent"; import { defineWorkflow, step } from "@intx/workflow"; import type { WorkflowDefinition } from "@intx/workflow"; import type { ToolPackagePin } from "@intx/types/tool-packages"; -import type { CredentialBinding } from "@intx/types"; export const ASSISTANT_WORKFLOW_ID = "wf_assistant"; export const ASSISTANT_STEP_ID = "assistant"; @@ -54,22 +53,6 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/manus-tools", version: "0.0.1" }, ]; -/** - * Binds `@corbits/manus-tools`' declared "manus" handle to a tenant-owned - * Manus credential. The launch resolves this against - * `buildCredentialDelivery`, materializing a consumer-scoped grant for - * the pinned package so Myra can call Manus when the connector is - * connected. - */ -export const ASSISTANT_CREDENTIAL_BINDINGS: readonly CredentialBinding[] = [ - { - package: "@corbits/manus-tools", - handle: "manus", - provider: "manus", - locator: "tenant", - }, -]; - /** * WELCOME: how Myra introduces herself when asked. Said once, briefly — * an offer, not a menu. The opening hello itself is canned and posted @@ -286,7 +269,6 @@ export function buildAssistantWorkflow( return defineWorkflow({ id: ASSISTANT_WORKFLOW_ID, trigger: { type: "mail", to: input.triggerAddress }, - credentialBindings: ASSISTANT_CREDENTIAL_BINDINGS, steps: { assistant: step({ agent: { diff --git a/workflows/assistant/test/definition.test.ts b/workflows/assistant/test/definition.test.ts index 9defdca05..5be5b32ab 100644 --- a/workflows/assistant/test/definition.test.ts +++ b/workflows/assistant/test/definition.test.ts @@ -7,7 +7,6 @@ import { expect, test } from "bun:test"; import type { StepPrimitive, WorkflowDefinition } from "@intx/workflow"; import { - ASSISTANT_CREDENTIAL_BINDINGS, ASSISTANT_STEP_ID, ASSISTANT_SYSTEM_PROMPT, ASSISTANT_TOOL_PACKAGE_PINS, @@ -151,17 +150,12 @@ test("the prompt tells Myra to discover an MCP server's tools before calling one expect(ASSISTANT_SYSTEM_PROMPT).toContain("never guess a tool name"); }); -test("the workflow binds the Manus credential handle to a tenant-owned provider", () => { +test("the workflow pins manus-tools and does not require a Manus credential binding", () => { const definition = buildAssistantWorkflow(INPUT); - expect(definition.credentialBindings).toEqual(ASSISTANT_CREDENTIAL_BINDINGS); - expect(ASSISTANT_CREDENTIAL_BINDINGS).toEqual([ - { - package: "@corbits/manus-tools", - handle: "manus", - provider: "manus", - locator: "tenant", - }, - ]); + expect(ASSISTANT_TOOL_PACKAGE_PINS.map((pin) => pin.name)).toContain( + "@corbits/manus-tools", + ); + expect(definition.credentialBindings ?? []).toEqual([]); }); test("the definition survives the workflow-asset JSON round-trip", () => { From d0fb6cfb375b3dea11a77d9730d64d5845c64e03 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:08:01 -0700 Subject: [PATCH 39/75] Wait for Manus slide decks without pdf or stale status --- packages/manus-tools/src/client.test.ts | 179 +++++++++++++++++++++++- packages/manus-tools/src/client.ts | 83 +++++++++-- packages/manus-tools/src/index.ts | 3 + packages/manus-tools/src/tool.test.ts | 69 ++++++++- packages/manus-tools/src/tool.ts | 10 +- 5 files changed, 323 insertions(+), 21 deletions(-) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index d0855a6f3..ae8b42e6f 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -1,6 +1,15 @@ import { expect, test } from "bun:test"; -import { createTask, listTaskMessages, manusRequest } from "./client"; +import { + createSlideDeck, + createTask, + DEFAULT_SLIDE_MAX_POLLS, + DEFAULT_SLIDE_POLL_INTERVAL_MS, + latestAgentStatus, + listTaskMessages, + manusRequest, + SLIDES_FORMAT_PPTX, +} from "./client"; test("createTask posts to /v2/task.create and parses the ok envelope", async () => { const captured: { url: string; headers: Headers | null; body: string } = { @@ -100,3 +109,171 @@ test("throws when a 200 body is not an ok envelope", async () => { manusRequest({ fetchImpl }, { method: "GET", path: "/v2/skill.list" }), ).rejects.toThrow(/did not match the expected shape/); }); + +test("latestAgentStatus uses the first status_update under default desc order", () => { + expect( + latestAgentStatus([ + { type: "status_update", status_update: { agent_status: "stopped" } }, + { type: "status_update", status_update: { agent_status: "running" } }, + ]), + ).toBe("stopped"); +}); + +test("createSlideDeck treats mixed [stopped, running] desc as terminal", async () => { + const listUrls: string[] = []; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + expect( + JSON.parse(typeof init?.body === "string" ? init.body : ""), + ).toEqual({ + message: { + content: + "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + }, + }); + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listUrls.push(url); + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + { + type: "status_update", + status_update: { agent_status: "running" }, + }, + ], + }), + { status: 200 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + const result = await createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 3 }, + ); + expect(result.agent_status).toBe("stopped"); + expect(listUrls).toHaveLength(1); + expect(listUrls[0]).toContain(`slides_format=${SLIDES_FORMAT_PPTX}`); + expect(listUrls[0]).not.toContain("slides_format=pdf"); + expect(SLIDES_FORMAT_PPTX).toBe("pptx"); +}); + +test("createSlideDeck throws when the agent is still running after the poll budget", async () => { + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "running" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 2 }, + ), + ).rejects.toThrow(/did not stop in time \(agent_status: running\)/); +}); + +test("createSlideDeck throws when the agent is waiting", async () => { + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "waiting" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 5 }, + ), + ).rejects.toThrow(/waiting for confirmation/); +}); + +test("createSlideDeck aborts polling instead of waiting out the timeout", async () => { + const controller = new AbortController(); + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "running" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + const pending = createSlideDeck( + { fetchImpl }, + { + content: "Onboarding", + pollIntervalMs: 30_000, + maxPolls: 10, + signal: controller.signal, + }, + ); + queueMicrotask(() => controller.abort()); + await expect(pending).rejects.toThrow(/cancelled/); +}); + +test("default slide-deck wait is several minutes", () => { + expect( + DEFAULT_SLIDE_MAX_POLLS * DEFAULT_SLIDE_POLL_INTERVAL_MS, + ).toBeGreaterThan(60_000); + expect(DEFAULT_SLIDE_MAX_POLLS * DEFAULT_SLIDE_POLL_INTERVAL_MS).toBe( + 5 * 60 * 1000, + ); +}); diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index a9d92478c..c46a72f27 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -275,12 +275,14 @@ export function latestAgentStatus( messages: readonly TaskEvent[] | undefined, ): string | undefined { if (messages === undefined) return undefined; - let status: string | undefined; + // task.listMessages defaults to desc (newest first). The first + // status_update is the current agent_status; walking to the last + // event would treat an older running state as current. for (const event of messages) { const next = event.status_update?.agent_status; - if (next !== undefined) status = next; + if (next !== undefined) return next; } - return status; + return undefined; } export function extractOutputFiles( @@ -321,15 +323,58 @@ export function extractOutputFiles( const TERMINAL_STATUSES = new Set(["stopped", "error"]); +/** Manus `slides_format` accepts pptx or html — never pdf. */ +export const SLIDES_FORMAT_PPTX = "pptx"; + +export const DEFAULT_SLIDE_POLL_INTERVAL_MS = 2_000; +/** 5 minutes at the default interval — a real deck takes longer than 60s. */ +export const DEFAULT_SLIDE_MAX_POLLS = 150; + +const SLIDE_DECK_PROMPT_PREFIX = + "Create a slide presentation in pptx format. Produce a presentation " + + "deck, not a document. Topic and requirements:\n\n"; + export type CreateSlideDeckParams = CreateTaskParams & { readonly pollIntervalMs?: number; readonly maxPolls?: number; + readonly signal?: AbortSignal; }; +function throwIfSlideWaitAborted(signal: AbortSignal | undefined): void { + if (signal?.aborted) { + throw new Error("Manus slide-deck wait was cancelled"); + } +} + +function sleep(ms: number, signal?: AbortSignal): Promise { + if (ms <= 0) { + throwIfSlideWaitAborted(signal); + return Promise.resolve(); + } + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(new Error("Manus slide-deck wait was cancelled")); + }; + if (signal === undefined) return; + if (signal.aborted) { + clearTimeout(timer); + reject(new Error("Manus slide-deck wait was cancelled")); + return; + } + signal.addEventListener("abort", onAbort, { once: true }); + }); +} + /** * Creates a task whose prompt asks Manus to produce a slide deck, then * polls `task.listMessages` until the agent stops (or errors) and returns - * any output files so a caller can retrieve them. + * any output files so a caller can retrieve them. A timeout, a still-running + * or waiting agent, or an abort is a thrown error — never a successful deck. */ export async function createSlideDeck( config: ManusClientConfig, @@ -342,22 +387,38 @@ export async function createSlideDeck( readonly files: readonly OutputFile[]; readonly error?: string; }> { - const created = await createTask(config, params); - const pollIntervalMs = params.pollIntervalMs ?? 1500; - const maxPolls = params.maxPolls ?? 40; + const { pollIntervalMs, maxPolls, signal, ...taskParams } = params; + const created = await createTask(config, { + ...taskParams, + content: `${SLIDE_DECK_PROMPT_PREFIX}${taskParams.content}`, + }); + const intervalMs = pollIntervalMs ?? DEFAULT_SLIDE_POLL_INTERVAL_MS; + const polls = maxPolls ?? DEFAULT_SLIDE_MAX_POLLS; let messages: ListMessagesResponse | undefined; - for (let i = 0; i < maxPolls; i += 1) { + for (let i = 0; i < polls; i += 1) { + throwIfSlideWaitAborted(signal); messages = await listTaskMessages(config, { task_id: created.task_id, - slides_format: "pdf", + slides_format: SLIDES_FORMAT_PPTX, }); const status = latestAgentStatus(messages.messages); if (status !== undefined && TERMINAL_STATUSES.has(status)) break; - if (i < maxPolls - 1 && pollIntervalMs > 0) { - await new Promise((resolve) => setTimeout(resolve, pollIntervalMs)); + if (status === "waiting") { + throw new Error( + `Manus task ${created.task_id} is waiting for confirmation and cannot finish unattended`, + ); + } + if (i < polls - 1) { + await sleep(intervalMs, signal); } } const status = latestAgentStatus(messages?.messages); + if (status === undefined || !TERMINAL_STATUSES.has(status)) { + throw new Error( + `Manus task ${created.task_id} did not stop in time` + + (status !== undefined ? ` (agent_status: ${status})` : ""), + ); + } const files = extractOutputFiles(messages?.messages); const errorEvent = messages?.messages?.find((event) => event.error_message); const result: { diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index 44a342d21..7013c25b1 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -8,6 +8,9 @@ export { listTaskMessages, manusRequest, DEFAULT_MANUS_BASE_URL, + DEFAULT_SLIDE_MAX_POLLS, + DEFAULT_SLIDE_POLL_INTERVAL_MS, + SLIDES_FORMAT_PPTX, } from "./client"; export type { CreateSlideDeckParams, diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index b6b0875a4..9fd80fe37 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -52,10 +52,11 @@ const STOPPED_WITH_DECK = { attachments: [ { type: "slides", - filename: "onboarding.pdf", - url: "https://files.manus.ai/onboarding.pdf", + filename: "onboarding.pptx", + url: "https://files.manus.ai/onboarding.pptx", id: "file_deck_1", - content_type: "application/pdf", + content_type: + "application/vnd.openxmlformats-officedocument.presentationml.presentation", }, ], }, @@ -81,6 +82,17 @@ test("declares create_slides plus thin tools covering the v2 surface", () => { expect(names.length).toBe(MANUS_ENDPOINTS.length + 1); }); +test("task_list_msgs describes slides_format as pptx or html, never pdf", () => { + const listMsgs = MANUS_ENDPOINTS.find( + (spec) => spec.name === "task_list_msgs", + ); + expect(listMsgs?.properties["slides_format"]?.description).toContain("pptx"); + expect(listMsgs?.properties["slides_format"]?.description).toContain("html"); + expect(listMsgs?.properties["slides_format"]?.description).not.toMatch( + /pdf/i, + ); +}); + test("degrades to a non-throwing 'not connected' error when no credential is bound", async () => { const bundle = manusTools(fakeEnv(fakeCredentials(undefined))); const result = await bundle.run( @@ -109,6 +121,12 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio urls.push(url); if (url.includes("/v2/task.create")) { expect(init?.method).toBe("POST"); + const body = JSON.parse(typeof init?.body === "string" ? init.body : ""); + expect(body.message.content).toContain("slide presentation"); + expect(body.message.content).toContain("pptx"); + expect(body.message.content).toContain( + "Make a five-slide deck about onboarding", + ); return new Response( JSON.stringify({ ok: true, @@ -120,6 +138,8 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio ); } if (url.includes("/v2/task.listMessages")) { + expect(url).toContain("slides_format=pptx"); + expect(url).not.toContain("slides_format=pdf"); return new Response(JSON.stringify(STOPPED_WITH_DECK), { status: 200 }); } return new Response("unexpected", { status: 500 }); @@ -146,11 +166,12 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio expect(parsed.agent_status).toBe("stopped"); expect(parsed.files).toEqual([ { - filename: "onboarding.pdf", - url: "https://files.manus.ai/onboarding.pdf", + filename: "onboarding.pptx", + url: "https://files.manus.ai/onboarding.pptx", id: "file_deck_1", type: "slides", - content_type: "application/pdf", + content_type: + "application/vnd.openxmlformats-officedocument.presentationml.presentation", }, ]); expect(urls.some((url) => url.includes("/v2/task.create"))).toBe(true); @@ -162,6 +183,42 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio } }); +test("create_slides returns isError when the agent is waiting", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: unknown) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "waiting" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toMatch(/waiting for confirmation/); + } finally { + globalThis.fetch = originalFetch; + } +}); + test("degrades to an error result (never throws) when the underlying call fails", async () => { const originalFetch = globalThis.fetch; globalThis.fetch = (async () => diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index 996d26d89..4f9ab756e 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -156,7 +156,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ cursor: STRING("Pagination cursor."), order: STRING("Sort order."), verbose: BOOLEAN("Include tool/plan events."), - slides_format: STRING("Preferred slides download format, e.g. pdf."), + slides_format: STRING("Preferred slides download format: pptx or html."), }, }, { @@ -622,6 +622,7 @@ function optionalListMessageFields(call: ToolCall): { async function runCreateSlides( env: ManusEnv, call: ToolCall, + signal: AbortSignal, ): Promise { const credential = await resolveManusCredential(env); if (credential === null) return notConnectedResult(call.id); @@ -638,6 +639,7 @@ async function runCreateSlides( const result = await createSlideDeck(asClientConfig(credential), { content: prompt, ...(title !== undefined ? { title } : {}), + signal, }); return { callId: call.id, content: JSON.stringify(result) }; } catch (err) { @@ -690,8 +692,10 @@ export const manusTools = defineTool({ }, })), ], - run: (call, _signal) => { - if (call.name === CREATE_SLIDES_TOOL) return runCreateSlides(env, call); + run: (call, signal) => { + if (call.name === CREATE_SLIDES_TOOL) { + return runCreateSlides(env, call, signal); + } const spec = MANUS_ENDPOINTS.find((entry) => entry.name === call.name); if (spec === undefined) { return Promise.resolve({ From b039beec263c946187b55e135b841687e7b1f6a9 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:57:44 -0700 Subject: [PATCH 40/75] Add tests for folding pinned-package credentials at launch A pin with no matching binding is inert at tool time. Launch already folds MCP bindings when the package is pinned; static handles such as Manus need the same coverage so a connected tenant does not see "not connected" after Settings. --- packages/folded-runs/test/launch.test.ts | 268 +++++++++++++++++++++++ 1 file changed, 268 insertions(+) diff --git a/packages/folded-runs/test/launch.test.ts b/packages/folded-runs/test/launch.test.ts index 8b7f8fc5c..1cf240ce2 100644 --- a/packages/folded-runs/test/launch.test.ts +++ b/packages/folded-runs/test/launch.test.ts @@ -1403,6 +1403,274 @@ describe("deployAtHead — mcp credential bindings", () => { }); }); +describe("deployAtHead — pinned-package credential bindings", () => { + const MANUS_BINDING = { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant" as const, + }; + + function catalogSources(): DefinitionSourceResolution { + return { + ok: true, + sources: [ + { + id: "off_1", + provider: "anthropic", + baseURL: "https://inference.invalid", + apiKey: "placeholder", + model: "claude-sonnet-5", + }, + ], + defaultSource: "off_1", + }; + } + + test("folds a connected manus binding into delivery and runtimeConfig when manus-tools is pinned", async () => { + resolveDefinitionSourcesCalls.length = 0; + resolveDefinitionSourcesResult = catalogSources(); + buildCredentialDeliveryCalls.length = 0; + buildCredentialDeliveryResult = { + ok: true, + delivery: { + bindings: [ + { + handle: "manus", + credentialId: "cred_manus_1", + consumer: "tool:@corbits/manus-tools", + }, + ], + materials: [ + { + credentialId: "cred_manus_1", + providerKey: "manus", + origin: "https://api.manus.ai", + secret: "n/a", + }, + ], + }, + }; + + const db = createFakeDb(); + const sessionService = createFakeSessionService(); + const assetService = createFakeAssetService(); + const eventCollectors = createFakeEventCollectors(); + const pinnedPackageCalls: { tenantId: string; pins: unknown }[] = []; + + await deployAtHead( + { + db: db as never, + sidecarRouter: createFakeSidecarRouter(), + assetService, + sessionService, + eventCollectors, + credentialCipher: {} as never, + toolGrantsForPins: () => [], + pinnedPackageCredentialBindingsFor: async (tenantId, pins) => { + pinnedPackageCalls.push({ tenantId, pins }); + return [MANUS_BINDING]; + }, + }, + { + tenantId: "ten_1", + instanceId: "ins_1", + triggerAddress: "ins_1@ten1.workbench.test", + principalId: "prn_1", + sessionId: "ses_1", + foldedBody: { + ...FOLDED_BODY, + toolPackagePins: [{ name: "@corbits/manus-tools", version: "*" }], + }, + launchLabel: "myra", + }, + ); + + expect(pinnedPackageCalls).toEqual([ + { + tenantId: "ten_1", + pins: [{ name: "@corbits/manus-tools", version: "*" }], + }, + ]); + expect(buildCredentialDeliveryCalls).toHaveLength(1); + expect(buildCredentialDeliveryCalls[0]).toMatchObject({ + tenantId: "ten_1", + bindings: [MANUS_BINDING], + }); + + const deployed = onlyCall(sessionService.adoptedDeployCalls); + expect(deployed.credentialCipher).toBeDefined(); + expect(deployed.config.grants).toContainEqual( + expect.objectContaining({ + resource: "credential:cred_manus_1", + action: "use", + conditions: { tool: "tool:@corbits/manus-tools" }, + }), + ); + const entry = + assetService.populateAssetCalls[0]?.tree.files["workflow.js"] ?? ""; + expect(entryDefinition(entry)["credentialBindings"]).toEqual([ + MANUS_BINDING, + ]); + }); + + test("succeeds with no manus binding when the port returns none", async () => { + resolveDefinitionSourcesCalls.length = 0; + resolveDefinitionSourcesResult = catalogSources(); + buildCredentialDeliveryCalls.length = 0; + + const db = createFakeDb(); + const sessionService = createFakeSessionService(); + const assetService = createFakeAssetService(); + const eventCollectors = createFakeEventCollectors(); + + await deployAtHead( + { + db: db as never, + sidecarRouter: createFakeSidecarRouter(), + assetService, + sessionService, + eventCollectors, + credentialCipher: {} as never, + toolGrantsForPins: () => [], + pinnedPackageCredentialBindingsFor: async () => [], + }, + { + tenantId: "ten_1", + instanceId: "ins_2", + triggerAddress: "ins_2@ten1.workbench.test", + principalId: "prn_2", + sessionId: "ses_2", + foldedBody: { + ...FOLDED_BODY, + toolPackagePins: [{ name: "@corbits/manus-tools", version: "*" }], + }, + launchLabel: "myra", + }, + ); + + expect(buildCredentialDeliveryCalls).toHaveLength(0); + const deployed = sessionService.adoptedDeployCalls[0] as { + credentials?: unknown; + }; + expect(deployed.credentials).toBeUndefined(); + const entry = + assetService.populateAssetCalls[0]?.tree.files["workflow.js"] ?? ""; + expect(entryDefinition(entry)["credentialBindings"] ?? []).toEqual([]); + }); + + test("does not add a manus binding when manus-tools is not pinned", async () => { + resolveDefinitionSourcesCalls.length = 0; + resolveDefinitionSourcesResult = catalogSources(); + buildCredentialDeliveryCalls.length = 0; + const db = createFakeDb(); + const sessionService = createFakeSessionService(); + const assetService = createFakeAssetService(); + const eventCollectors = createFakeEventCollectors(); + const pinnedPackageCalls: { tenantId: string; pins: unknown }[] = []; + + await deployAtHead( + { + db: db as never, + sidecarRouter: createFakeSidecarRouter(), + assetService, + sessionService, + eventCollectors, + credentialCipher: {} as never, + toolGrantsForPins: () => [], + pinnedPackageCredentialBindingsFor: async (tenantId, pins) => { + pinnedPackageCalls.push({ tenantId, pins }); + return []; + }, + }, + { + tenantId: "ten_1", + instanceId: "ins_3", + triggerAddress: "ins_3@ten1.workbench.test", + principalId: "prn_3", + sessionId: "ses_3", + foldedBody: FOLDED_BODY, + launchLabel: "myra", + }, + ); + + expect(pinnedPackageCalls).toEqual([ + { tenantId: "ten_1", pins: FOLDED_BODY.toolPackagePins }, + ]); + expect(buildCredentialDeliveryCalls).toHaveLength(0); + const entry = + assetService.populateAssetCalls[0]?.tree.files["workflow.js"] ?? ""; + expect(entryDefinition(entry)["credentialBindings"] ?? []).toEqual([]); + }); + + test("skips a pinned-package handle the definition already binds", async () => { + resolveDefinitionSourcesCalls.length = 0; + resolveDefinitionSourcesResult = catalogSources(); + buildCredentialDeliveryCalls.length = 0; + buildCredentialDeliveryResult = { + ok: true, + delivery: { + bindings: [ + { + handle: "manus", + credentialId: "cred_manus_1", + consumer: "tool:@corbits/manus-tools", + }, + ], + materials: [ + { + credentialId: "cred_manus_1", + providerKey: "manus", + origin: "https://api.manus.ai", + secret: "n/a", + }, + ], + }, + }; + + const db = createFakeDb(); + const sessionService = createFakeSessionService(); + const assetService = createFakeAssetService(); + const eventCollectors = createFakeEventCollectors(); + + await deployAtHead( + { + db: db as never, + sidecarRouter: createFakeSidecarRouter(), + assetService, + sessionService, + eventCollectors, + credentialCipher: {} as never, + toolGrantsForPins: () => [], + pinnedPackageCredentialBindingsFor: async () => [MANUS_BINDING], + }, + { + tenantId: "ten_1", + instanceId: "ins_4", + triggerAddress: "ins_4@ten1.workbench.test", + principalId: "prn_4", + sessionId: "ses_4", + foldedBody: { + ...FOLDED_BODY, + toolPackagePins: [{ name: "@corbits/manus-tools", version: "*" }], + credentialBindings: [MANUS_BINDING], + }, + launchLabel: "myra", + }, + ); + + expect(buildCredentialDeliveryCalls).toHaveLength(1); + expect(buildCredentialDeliveryCalls[0]).toMatchObject({ + bindings: [MANUS_BINDING], + }); + const entry = + assetService.populateAssetCalls[0]?.tree.files["workflow.js"] ?? ""; + expect(entryDefinition(entry)["credentialBindings"]).toEqual([ + MANUS_BINDING, + ]); + }); +}); + // CL-6452: a folded run's deployed bytes carry per-run values, so their // wire hash is unique to the run and the deploy's freeze ensures a fresh // definition row over the agent's asset, then repoints the run at it. From e77f079a2b201a5eaff67adcb843834613be39da Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:59:11 -0700 Subject: [PATCH 41/75] Fold connected pinned-package credentials into launch A pin with no matching binding is inert at tool time. Required assistant binds would throw on first chat, so launch now folds CONNECTOR_REGISTRY-fed bindings for pins the tenant already connected, the same way it already folds MCP server bindings. --- apps/hub/src/index.ts | 8 ++++ ...pinned-package-credential-bindings.test.ts | 41 ++++++++++++++++ .../src/pinned-package-credential-bindings.ts | 48 +++++++++++++++++++ packages/chat/src/platform-adapter.ts | 8 ++++ packages/folded-runs/src/index.ts | 1 + packages/folded-runs/src/launch.ts | 28 +++++++++-- packages/folded-runs/src/types.ts | 28 +++++++++++ 7 files changed, 159 insertions(+), 3 deletions(-) create mode 100644 apps/hub/src/pinned-package-credential-bindings.test.ts create mode 100644 apps/hub/src/pinned-package-credential-bindings.ts diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index 483887d8e..03257051a 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -355,6 +355,7 @@ import { createBootAssetWiring, REGISTRIES } from "./asset-service-factory"; import { createRoutineScheduler } from "./routine-scheduler"; import { createToolGrantsForPins } from "./tool-grants"; import { createMcpCredentialBindingsFor } from "./mcp-credential-bindings"; +import { createPinnedPackageCredentialBindingsFor } from "./pinned-package-credential-bindings"; import { shutdownHub } from "./shutdown"; // Host policy constants, not configuration. @@ -714,6 +715,9 @@ export async function createHub(config: HubConfig) { ); // See `./mcp-credential-bindings.ts`'s own doc. const mcpCredentialBindingsFor = createMcpCredentialBindingsFor(db); + // See `./pinned-package-credential-bindings.ts`'s own doc. + const pinnedPackageCredentialBindingsFor = + createPinnedPackageCredentialBindingsFor(db); const sidecarRouter = createSidecarRouter({ hubPublicKey, authenticateSidecar: createSidecarTokenAuthenticator({ db }), @@ -1278,6 +1282,7 @@ export async function createHub(config: HubConfig) { credentialCipher, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, // Chat residents are undeployed on idle again (see the comment above // this function): `chatIdleReapMs` (env-overridable via // `WORKBENCH_CHAT_IDLE_REAP_MS`, default 30 minutes) is @@ -1984,6 +1989,7 @@ export async function createHub(config: HubConfig) { eventCollectors, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, cryptoProviderCache: foldedRunCryptoProviders, launchMode: AGENT_SECTION_MODE, persistLaunch: workbenchLaunchPersistExtra, @@ -2512,6 +2518,7 @@ export async function createHub(config: HubConfig) { hubPublicKey, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, }; // Every genuine top-level deployment run, folded runs (workbench hosts, @@ -2702,6 +2709,7 @@ export async function createHub(config: HubConfig) { credentialCipher, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, cryptoProviderCache: foldedRunCryptoProviders, joinDeliveryWorkbench: (input) => joinRunParticipant({ store: chatStore }, input), diff --git a/apps/hub/src/pinned-package-credential-bindings.test.ts b/apps/hub/src/pinned-package-credential-bindings.test.ts new file mode 100644 index 000000000..24cbfe836 --- /dev/null +++ b/apps/hub/src/pinned-package-credential-bindings.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, test } from "bun:test"; +import { bindingsForConnectedPins } from "./pinned-package-credential-bindings"; + +const MANUS_PIN = { name: "@corbits/manus-tools", version: "*" }; +const GRANOLA_PIN = { name: "@corbits/granola-tools", version: "*" }; + +describe("bindingsForConnectedPins", () => { + test("emits a manus tenant binding when manus-tools is pinned and Manus is connected", () => { + expect(bindingsForConnectedPins([MANUS_PIN], ["manus"])).toEqual([ + { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant", + }, + ]); + }); + + test("returns none when manus-tools is pinned but Manus is not connected", () => { + expect(bindingsForConnectedPins([MANUS_PIN], ["granola"])).toEqual([]); + }); + + test("returns none when Manus is connected but manus-tools is not pinned", () => { + expect(bindingsForConnectedPins([GRANOLA_PIN], ["manus"])).toEqual([]); + }); + + test("emits a granola binding when granola-tools is pinned and Granola is connected", () => { + expect(bindingsForConnectedPins([GRANOLA_PIN], ["granola"])).toEqual([ + { + package: "@corbits/granola-tools", + handle: "granola", + provider: "granola", + locator: "tenant", + }, + ]); + }); + + test("returns none for empty pins even when connectors are connected", () => { + expect(bindingsForConnectedPins([], ["manus", "granola"])).toEqual([]); + }); +}); diff --git a/apps/hub/src/pinned-package-credential-bindings.ts b/apps/hub/src/pinned-package-credential-bindings.ts new file mode 100644 index 000000000..bfcba09c1 --- /dev/null +++ b/apps/hub/src/pinned-package-credential-bindings.ts @@ -0,0 +1,48 @@ +// The `PinnedPackageCredentialBindingsFor` port every `FoldedRunsDeps` +// below is wired with — see `@corbits/folded-runs`' `types.ts` for why +// this has to be supplied by the composition root rather than declared as +// a required assistant `credentialBindings` entry. Static-handle packages +// (`@corbits/manus-tools`, granola-tools, …) declare +// `interchange.credentials`, but requiring those binds on the assistant +// would throw `MissingCredentialError` on signup / first chat. This +// factory emits a tenant binding only when a pin names a package a +// `CONNECTOR_REGISTRY` entry `feedsTools` AND the tenant already has a +// connected credential for that connector (`listConnectedProviders`). +import type { DB } from "@intx/db"; +import type { CredentialBinding } from "@intx/types"; +import type { ToolPackagePin } from "@intx/types/tool-packages"; +import type { PinnedPackageCredentialBindingsFor } from "@corbits/folded-runs"; +import { listConnectedProviders } from "@corbits/chat"; +import { CONNECTOR_REGISTRY } from "@workbench/connections/registry"; + +export function bindingsForConnectedPins( + pins: readonly ToolPackagePin[], + connectedConnectorIds: readonly string[], +): readonly CredentialBinding[] { + const pinNames = new Set(pins.map((pin) => pin.name)); + if (pinNames.size === 0) return []; + const connected = new Set(connectedConnectorIds); + const bindings: CredentialBinding[] = []; + for (const descriptor of Object.values(CONNECTOR_REGISTRY)) { + if (!connected.has(descriptor.id)) continue; + for (const toolPackageName of descriptor.feedsTools) { + if (!pinNames.has(toolPackageName)) continue; + bindings.push({ + package: toolPackageName, + handle: descriptor.id, + provider: descriptor.id, + locator: "tenant", + }); + } + } + return bindings; +} + +export function createPinnedPackageCredentialBindingsFor( + db: DB["db"], +): PinnedPackageCredentialBindingsFor { + return async (tenantId, pins) => { + const connected = await listConnectedProviders(db, tenantId); + return bindingsForConnectedPins(pins, connected); + }; +} diff --git a/packages/chat/src/platform-adapter.ts b/packages/chat/src/platform-adapter.ts index ba8ab665f..ae2ceb041 100644 --- a/packages/chat/src/platform-adapter.ts +++ b/packages/chat/src/platform-adapter.ts @@ -76,6 +76,8 @@ export type CreateHubChatPlatformDeps = { toolGrantsForPins: FoldedRunsDeps["toolGrantsForPins"]; /** See `FoldedRunsDeps.mcpCredentialBindingsFor`. */ mcpCredentialBindingsFor?: FoldedRunsDeps["mcpCredentialBindingsFor"]; + /** See `FoldedRunsDeps.pinnedPackageCredentialBindingsFor`. */ + pinnedPackageCredentialBindingsFor?: FoldedRunsDeps["pinnedPackageCredentialBindingsFor"]; /** * Decrypts credential secrets when an invited agent's launch resolves * inference sources against the tenant catalog — see @@ -207,6 +209,12 @@ export function createHubChatPlatform( ...(deps.mcpCredentialBindingsFor !== undefined ? { mcpCredentialBindingsFor: deps.mcpCredentialBindingsFor } : {}), + ...(deps.pinnedPackageCredentialBindingsFor !== undefined + ? { + pinnedPackageCredentialBindingsFor: + deps.pinnedPackageCredentialBindingsFor, + } + : {}), }; const cryptoProviders = createCryptoProviderCache(); diff --git a/packages/folded-runs/src/index.ts b/packages/folded-runs/src/index.ts index 5f061f1a9..5519fd370 100644 --- a/packages/folded-runs/src/index.ts +++ b/packages/folded-runs/src/index.ts @@ -1,6 +1,7 @@ export type { FoldedRunsDeps, McpCredentialBindingsFor, + PinnedPackageCredentialBindingsFor, PinnedToolGrantDeclaration, ToolGrantsForPins, SentFoldedMail, diff --git a/packages/folded-runs/src/launch.ts b/packages/folded-runs/src/launch.ts index 1d6f0e551..cf621d8fc 100644 --- a/packages/folded-runs/src/launch.ts +++ b/packages/folded-runs/src/launch.ts @@ -245,6 +245,7 @@ export async function deployAtHead( | "assetService" | "toolGrantsForPins" | "mcpCredentialBindingsFor" + | "pinnedPackageCredentialBindingsFor" >, params: { tenantId: string; @@ -397,9 +398,29 @@ export async function deployAtHead( isMcpToolsPin && deps.mcpCredentialBindingsFor !== undefined ? await deps.mcpCredentialBindingsFor(params.tenantId) : []; + // Static-handle packages (`@corbits/manus-tools`, granola-tools, …) declare + // `interchange.credentials`, but the assistant does not require those + // bindings — a required bind would throw MissingCredentialError on first + // chat. When this port is supplied, fold in only the bindings for pins + // whose connector the tenant already has, skipping handles the definition + // itself already bound. + const pinnedPackageBindings: readonly CredentialBinding[] = + deps.pinnedPackageCredentialBindingsFor !== undefined + ? await deps.pinnedPackageCredentialBindingsFor( + params.tenantId, + params.foldedBody.toolPackagePins, + ) + : []; + const definedHandles = new Set( + params.foldedBody.credentialBindings.map((binding) => binding.handle), + ); + const extraPinnedBindings = pinnedPackageBindings.filter( + (binding) => !definedHandles.has(binding.handle), + ); const credentialBindings = [ ...params.foldedBody.credentialBindings, ...mcpBindings, + ...extraPinnedBindings, ]; // The deploy front resolves the credential MATERIAL itself from the @@ -464,9 +485,10 @@ export async function deployAtHead( // The definition's own `credentialBindings` are what the workflow // host's per-step credential snapshot // (`vendor/intx/workflow-host/src/supervisor/credentials.ts`) derives - // its consumer bindings from, which is why the pinned-package MCP - // bindings folded in above have to reach the rendered config and not - // just the delivery: without them `env.credentials.resolve("mcp.")` + // its consumer bindings from, which is why the pinned-package bindings + // folded in above — MCP `mcp.` handles and static connector + // handles such as `manus` — have to reach the rendered config and not + // just the delivery: without them `env.credentials.resolve(...)` // fails "not connected" even when the material was delivered. const runtimeConfig: AgentRuntimeConfig = { workflowId: `wf_${params.instanceId}`, diff --git a/packages/folded-runs/src/types.ts b/packages/folded-runs/src/types.ts index f1b47c1e5..5ff0efeff 100644 --- a/packages/folded-runs/src/types.ts +++ b/packages/folded-runs/src/types.ts @@ -80,6 +80,28 @@ export type McpCredentialBindingsFor = ( tenantId: string, ) => Promise; +/** + * Derives extra credential bindings for a folded run's pinned tool packages + * whose handles are static (known at package-publish time) but whose + * workflow definition does not require them. A required assistant binding + * would throw `MissingCredentialError` on signup / first chat when the + * tenant has not connected the provider; a pin with no matching binding is + * otherwise inert at tool time (`env.credentials.resolve(handle)` fails + * "not connected" even when Settings already has the key). + * + * `deployAtHead` calls this whenever it is supplied, with the launch's + * `toolPackagePins`, and concatenates the result onto the definition's own + * bindings (skipping handles already present). The composition root + * (`apps/hub`) supplies the real implementation from + * `CONNECTOR_REGISTRY.feedsTools` plus the tenant's connected providers — + * `folded-runs` never imports that registry itself. Optional: a caller that + * never pins a connector-fed package has no need to supply it. + */ +export type PinnedPackageCredentialBindingsFor = ( + tenantId: string, + pins: readonly ToolPackagePin[], +) => Promise; + export type FoldedRunsDeps = { db: DB["db"]; /** @@ -112,6 +134,12 @@ export type FoldedRunsDeps = { * composition today) has no need to supply it. */ mcpCredentialBindingsFor?: McpCredentialBindingsFor; + /** + * See `PinnedPackageCredentialBindingsFor`'s own doc. Optional: a caller + * that never pins a connector-fed package (granola-tools, manus-tools, …) + * has no need to supply it. + */ + pinnedPackageCredentialBindingsFor?: PinnedPackageCredentialBindingsFor; }; export type SentFoldedMail = { From a4b742420a33db9b5f3377714a9c3b5efbfc25db Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 17:59:31 -0700 Subject: [PATCH 42/75] Name Manus in probes, assistant pins, and credential-wiring docs The probes header still listed four connectors, the assistant pin comment still counted four manager-tools bundles, and credential-wiring said four sidecar plugins while five are registered. --- docs/credential-wiring.md | 10 ++++++++-- packages/connections/src/probes.ts | 2 +- workflows/assistant/src/index.ts | 11 +++++++---- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/credential-wiring.md b/docs/credential-wiring.md index 8cf35968f..e0c71a6e5 100644 --- a/docs/credential-wiring.md +++ b/docs/credential-wiring.md @@ -56,9 +56,15 @@ registers: `x-manus-api-key`. A Manus provider row MUST set this plugin -- seeding it as `"http"` or `"http-x-api-key"` sends the wrong header name and Manus rejects the call. +- **`mcp-streamable-http`** -- `@corbits/credential-providers`'s + `createMcpStreamableHttpCredentialProvider`. For a token-bearing MCP + server it sends `authorization: Bearer `; for a keyless one + (`MCP_NO_TOKEN_SENTINEL`) it sends no authorization header. The vendored + `http` plugin cannot express the keyless case. -All four plugins mirror the same origin-pinning and `redirect: "manual"` -protections; only the injected header differs. +All five plugins the sidecar registers mirror the same origin-pinning and +`redirect: "manual"` protections; only the injected header (or its +absence, for keyless MCP) differs. `packages/connections` (the Connections-surface registry) is the other place this plugin id needs to be correct: whatever seeds or registers a diff --git a/packages/connections/src/probes.ts b/packages/connections/src/probes.ts index fefec4ab9..a1fb426d3 100644 --- a/packages/connections/src/probes.ts +++ b/packages/connections/src/probes.ts @@ -1,5 +1,5 @@ // Real, free credential probes for the tool connectors this ticket -// adds — Granola, Exa, ScrapeCreators, Linear, and GitHub — each hitting the +// adds — Granola, Exa, ScrapeCreators, Linear, GitHub, and Manus — each hitting the // same production endpoint its tool client (`packages/*-tools/src/ // client.ts`) already calls, authenticated with the real key. This // mirrors `@workbench/hub-client/credential-test`'s diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index a1fc16884..a45d3fc11 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -31,14 +31,17 @@ export const ASSISTANT_STEP_ID = "assistant"; /** * The tool packages this deployment pins. `@corbits/memory-tools` - * (CL-5852) is the original pin; `@corbits/capability-tools` - * (CL-6084/CL-6086) lets Myra self-service a missing tool, skill, or - * model; the remaining four are the manager-tools bundles giving Myra + * is the original pin; `@corbits/capability-tools` lets Myra self-service + * a missing tool, skill, or model; the manager-tools bundles give Myra * real workbench-management capability — a specialist agent she can * create (each gets their own chat), this workbench's routines, connection * visibility, and skill capture — each a thin wrapper over an existing * platform primitive (see each package's own file-header comment for - * which one). + * which one). `@corbits/mcp-tools` and `@corbits/interaction-tools` + * expose tenant-connected MCP servers and the ask-user card; + * `@corbits/manus-tools` is pinned so Manus tools exist when the tenant + * has connected Manus (launch folds the binding only then — the pin + * itself does not require a credential). */ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/memory-tools", version: "0.0.4" }, From a4fd8f2612332d406f267da01174de56ac161cc0 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:18:30 -0700 Subject: [PATCH 43/75] Add factory tests for pinned-package connector credentials The factory currently lists model catalog providers, so a connected Manus key never emits a binding. These cases pin the owning check: a live Manus connector plus a manus-tools pin binds, while a catalog-only Anthropic connection does not. --- ...pinned-package-credential-bindings.test.ts | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/apps/hub/src/pinned-package-credential-bindings.test.ts b/apps/hub/src/pinned-package-credential-bindings.test.ts index 24cbfe836..96a3c59ba 100644 --- a/apps/hub/src/pinned-package-credential-bindings.test.ts +++ b/apps/hub/src/pinned-package-credential-bindings.test.ts @@ -1,5 +1,8 @@ import { describe, expect, test } from "bun:test"; -import { bindingsForConnectedPins } from "./pinned-package-credential-bindings"; +import { + bindingsForConnectedPins, + createPinnedPackageCredentialBindingsFor, +} from "./pinned-package-credential-bindings"; const MANUS_PIN = { name: "@corbits/manus-tools", version: "*" }; const GRANOLA_PIN = { name: "@corbits/granola-tools", version: "*" }; @@ -39,3 +42,26 @@ describe("bindingsForConnectedPins", () => { expect(bindingsForConnectedPins([], ["manus", "granola"])).toEqual([]); }); }); + +describe("createPinnedPackageCredentialBindingsFor", () => { + test("emits a manus tenant binding when isConnectorConnected is true for manus", async () => { + const bindingsFor = createPinnedPackageCredentialBindingsFor( + async (_tenantId, connectorId) => connectorId === "manus", + ); + expect(await bindingsFor("tenant-1", [MANUS_PIN])).toEqual([ + { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant", + }, + ]); + }); + + test("emits none when only a catalog-style inference connector is connected", async () => { + const bindingsFor = createPinnedPackageCredentialBindingsFor( + async (_tenantId, connectorId) => connectorId === "anthropic", + ); + expect(await bindingsFor("tenant-1", [MANUS_PIN])).toEqual([]); + }); +}); From 728634839f7d6726a939dafbb789855fe3f6b67a Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:19:23 -0700 Subject: [PATCH 44/75] Resolve pinned-package credentials via connector ownership MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit listConnectedProviders only sees model catalog rows, so a pasted Manus key never folded a tenant binding at launch. Ask isConnectorConnected instead — the same resolveCredentialRequirement check GET /connections already uses. --- apps/hub/src/index.ts | 30 ++++++++++--------- .../src/pinned-package-credential-bindings.ts | 25 ++++++++++++---- 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index 03257051a..cda992755 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -715,9 +715,20 @@ export async function createHub(config: HubConfig) { ); // See `./mcp-credential-bindings.ts`'s own doc. const mcpCredentialBindingsFor = createMcpCredentialBindingsFor(db); - // See `./pinned-package-credential-bindings.ts`'s own doc. + // Same owning check GET /connections uses — see + // `@workbench/connections`' `workflow-connection-routes.ts` and the + // `createWorkflowConnectionRoutes` wiring below. Not + // `listConnectedProviders` (catalog-only). + const isConnectorConnected = async (tenantId: string, connectorId: string) => + (await resolveCredentialRequirement( + db, + tenantId, + { providerName: connectorId, source: "tenant" }, + null, + null, + )) !== null; const pinnedPackageCredentialBindingsFor = - createPinnedPackageCredentialBindingsFor(db); + createPinnedPackageCredentialBindingsFor(isConnectorConnected); const sidecarRouter = createSidecarRouter({ hubPublicKey, authenticateSidecar: createSidecarTokenAuthenticator({ db }), @@ -2439,18 +2450,9 @@ export async function createHub(config: HubConfig) { "/api/workflow-connections", createWorkflowConnectionRoutes({ authenticator: createWorkflowRunAuthenticator({ db }), - // The same resolution `buildCredentialDelivery` uses at agent-launch - // time to decide whether a tool actually gets a credential — so - // `list_connections` reports exactly what an agent could really use, - // for an inference provider and a tool connector alike (CL-6492). - isConnectorConnected: async (tenantId, connectorId) => - (await resolveCredentialRequirement( - db, - tenantId, - { providerName: connectorId, source: "tenant" }, - null, - null, - )) !== null, + // Same `isConnectorConnected` the pinned-package factory is wired + // with above (CL-6492). + isConnectorConnected, listMcpServers: (tenantId) => listMcpServerConnections(db, tenantId), }), ); diff --git a/apps/hub/src/pinned-package-credential-bindings.ts b/apps/hub/src/pinned-package-credential-bindings.ts index bfcba09c1..f3893abcc 100644 --- a/apps/hub/src/pinned-package-credential-bindings.ts +++ b/apps/hub/src/pinned-package-credential-bindings.ts @@ -7,14 +7,19 @@ // would throw `MissingCredentialError` on signup / first chat. This // factory emits a tenant binding only when a pin names a package a // `CONNECTOR_REGISTRY` entry `feedsTools` AND the tenant already has a -// connected credential for that connector (`listConnectedProviders`). -import type { DB } from "@intx/db"; +// connected credential for that connector (`isConnectorConnected`, the +// same owning check `createWorkflowConnectionRoutes` uses — not +// `@corbits/chat`'s catalog-only `listConnectedProviders`). import type { CredentialBinding } from "@intx/types"; import type { ToolPackagePin } from "@intx/types/tool-packages"; import type { PinnedPackageCredentialBindingsFor } from "@corbits/folded-runs"; -import { listConnectedProviders } from "@corbits/chat"; import { CONNECTOR_REGISTRY } from "@workbench/connections/registry"; +export type IsConnectorConnected = ( + tenantId: string, + connectorId: string, +) => Promise; + export function bindingsForConnectedPins( pins: readonly ToolPackagePin[], connectedConnectorIds: readonly string[], @@ -39,10 +44,18 @@ export function bindingsForConnectedPins( } export function createPinnedPackageCredentialBindingsFor( - db: DB["db"], + isConnectorConnected: IsConnectorConnected, ): PinnedPackageCredentialBindingsFor { return async (tenantId, pins) => { - const connected = await listConnectedProviders(db, tenantId); - return bindingsForConnectedPins(pins, connected); + const pinNames = new Set(pins.map((pin) => pin.name)); + if (pinNames.size === 0) return []; + const connectedConnectorIds: string[] = []; + for (const descriptor of Object.values(CONNECTOR_REGISTRY)) { + if (!descriptor.feedsTools.some((name) => pinNames.has(name))) continue; + if (await isConnectorConnected(tenantId, descriptor.id)) { + connectedConnectorIds.push(descriptor.id); + } + } + return bindingsForConnectedPins(pins, connectedConnectorIds); }; } From 018afecc54aa165fc4fe8887a311a90dc673c8f1 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:26:17 -0700 Subject: [PATCH 45/75] Bump @corbits/manus-tools after source changes --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index ffd17b9af..6cacf236a 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.1", + "version": "0.0.2", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index a45d3fc11..f09f815f6 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.1" }, + { name: "@corbits/manus-tools", version: "0.0.2" }, ]; /** From b92d240def92f03c1fbfa718c360ac5e6b897108 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:34:49 -0700 Subject: [PATCH 46/75] Stop pinning manus-tools version in its manifest test --- packages/manus-tools/src/manifest.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/manus-tools/src/manifest.test.ts b/packages/manus-tools/src/manifest.test.ts index 0f36b5454..55d82b5c9 100644 --- a/packages/manus-tools/src/manifest.test.ts +++ b/packages/manus-tools/src/manifest.test.ts @@ -18,5 +18,4 @@ test("declares exactly one credential handle: manus", () => { throw new Error(parsed.summary); } expect(parsed.interchange?.credentials).toEqual([{ handle: "manus" }]); - expect(parsed.version).toBe("0.0.1"); }); From 69f41ff1f8be8e9c11a635df96308d87addf3056 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 18:42:51 -0700 Subject: [PATCH 47/75] Bump @corbits/manus-tools after the manifest test change --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 6cacf236a..67c50ef44 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.2", + "version": "0.0.3", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index f09f815f6..6bf5edc6b 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.2" }, + { name: "@corbits/manus-tools", version: "0.0.3" }, ]; /** From 877d99ae889eb8b306a46163c5414785f948e17f Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:29:50 -0700 Subject: [PATCH 48/75] Add tests for Manus task skill and ContentPart fields --- packages/manus-tools/src/client.test.ts | 102 +++++++++++++++++- packages/manus-tools/src/tool.test.ts | 134 +++++++++++++++++++++++- 2 files changed, 230 insertions(+), 6 deletions(-) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index ae8b42e6f..6ceea6f58 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -42,12 +42,58 @@ test("createTask posts to /v2/task.create and parses the ok envelope", async () expect(captured.headers?.get("authorization")).toBeNull(); expect(captured.headers?.get("x-api-key")).toBeNull(); expect(JSON.parse(captured.body)).toEqual({ - message: { content: "Make slides" }, + message: { content: [{ type: "text", text: "Make slides" }] }, }); expect(created.task_id).toBe("task_1"); expect(created.task_url).toBe("https://manus.im/app/task_1"); }); +test("createTask posts skill, connector, and schema fields only when set", async () => { + const captured: { body: string } = { body: "" }; + const fetchImpl = (async (_input: URL | string, init?: RequestInit) => { + captured.body = typeof init?.body === "string" ? init.body : ""; + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_2", + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await createTask( + { fetchImpl }, + { + content: "Use the listed skill", + enable_skills: ["skill_abc"], + force_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + structured_output_schema: { + type: "object", + properties: { title: { type: "string" } }, + required: ["title"], + additionalProperties: false, + }, + }, + ); + expect(JSON.parse(captured.body)).toEqual({ + message: { + content: [{ type: "text", text: "Use the listed skill" }], + enable_skills: ["skill_abc"], + force_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + }, + structured_output_schema: { + type: "object", + properties: { title: { type: "string" } }, + required: ["title"], + additionalProperties: false, + }, + }); +}); + test("listTaskMessages GETs /v2/task.listMessages without an auth header", async () => { const captured: { url: string; headers: Headers | null } = { url: "", @@ -128,8 +174,13 @@ test("createSlideDeck treats mixed [stopped, running] desc as terminal", async ( JSON.parse(typeof init?.body === "string" ? init.body : ""), ).toEqual({ message: { - content: - "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + content: [ + { + type: "text", + text: + "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + }, + ], }, }); return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { @@ -277,3 +328,48 @@ test("default slide-deck wait is several minutes", () => { 5 * 60 * 1000, ); }); + +test("createSlideDeck forwards optional skill fields on create", async () => { + let createBody = ""; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + createBody = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await createSlideDeck( + { fetchImpl }, + { + content: "Onboarding", + enable_skills: ["skill_slides"], + force_skills: ["skill_slides"], + pollIntervalMs: 0, + maxPolls: 1, + }, + ); + const body = JSON.parse(createBody) as { + message: { + enable_skills?: string[]; + force_skills?: string[]; + }; + }; + expect(body.message.enable_skills).toEqual(["skill_slides"]); + expect(body.message.force_skills).toEqual(["skill_slides"]); +}); diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index 9fd80fe37..56ef6153d 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -122,11 +122,18 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio if (url.includes("/v2/task.create")) { expect(init?.method).toBe("POST"); const body = JSON.parse(typeof init?.body === "string" ? init.body : ""); - expect(body.message.content).toContain("slide presentation"); - expect(body.message.content).toContain("pptx"); - expect(body.message.content).toContain( + expect(body.message.content).toEqual([ + expect.objectContaining({ + type: "text", + }), + ]); + expect(body.message.content[0].text).toContain("slide presentation"); + expect(body.message.content[0].text).toContain("pptx"); + expect(body.message.content[0].text).toContain( "Make a five-slide deck about onboarding", ); + expect(body.message.enable_skills).toBeUndefined(); + expect(body.message.force_skills).toBeUndefined(); return new Response( JSON.stringify({ ok: true, @@ -234,3 +241,124 @@ test("degrades to an error result (never throws) when the underlying call fails" globalThis.fetch = originalFetch; } }); + +test("task_create and task_send_msg expose skill and connector fields", () => { + const create = MANUS_ENDPOINTS.find((spec) => spec.name === "task_create"); + const send = MANUS_ENDPOINTS.find((spec) => spec.name === "task_send_msg"); + for (const spec of [create, send]) { + expect(spec?.properties["enable_skills"]?.type).toBe("array"); + expect(spec?.properties["force_skills"]?.type).toBe("array"); + expect(spec?.properties["connectors"]?.type).toBe("array"); + expect(spec?.properties["task_references"]?.type).toBe("array"); + } + expect(create?.properties["structured_output_schema"]?.type).toBe("object"); + expect(send?.properties["structured_output_schema"]).toBeUndefined(); +}); + +test("task_create omits skill fields unless the assistant passes ids", async () => { + const originalFetch = globalThis.fetch; + let createBody = ""; + globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { + createBody = typeof init?.body === "string" ? init.body : ""; + return new Response( + JSON.stringify({ ok: true, task_id: "task_1" }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const omitted = await bundle.run( + { + id: "call_create", + name: "task_create", + arguments: { content: "Hello" }, + }, + new AbortController().signal, + ); + expect(omitted.isError).toBeUndefined(); + expect(JSON.parse(createBody)).toEqual({ + message: { content: [{ type: "text", text: "Hello" }] }, + }); + + const present = await bundle.run( + { + id: "call_create_skills", + name: "task_create", + arguments: { + content: "Hello with skills", + enable_skills: ["skill_abc"], + force_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + structured_output_schema: { type: "object" }, + }, + }, + new AbortController().signal, + ); + expect(present.isError).toBeUndefined(); + expect(JSON.parse(createBody)).toEqual({ + message: { + content: [{ type: "text", text: "Hello with skills" }], + enable_skills: ["skill_abc"], + force_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + }, + structured_output_schema: { type: "object" }, + }); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("task_send_msg posts ContentPart content and optional skill fields", async () => { + const originalFetch = globalThis.fetch; + let sendBody = ""; + globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { + sendBody = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true }), { status: 200 }); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const omitted = await bundle.run( + { + id: "call_send", + name: "task_send_msg", + arguments: { task_id: "task_1", content: "Follow up" }, + }, + new AbortController().signal, + ); + expect(omitted.isError).toBeUndefined(); + expect(JSON.parse(sendBody)).toEqual({ + task_id: "task_1", + message: { content: [{ type: "text", text: "Follow up" }] }, + }); + + const present = await bundle.run( + { + id: "call_send_skills", + name: "task_send_msg", + arguments: { + task_id: "task_1", + content: "Follow up with skills", + enable_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + }, + }, + new AbortController().signal, + ); + expect(present.isError).toBeUndefined(); + expect(JSON.parse(sendBody)).toEqual({ + task_id: "task_1", + message: { + content: [{ type: "text", text: "Follow up with skills" }], + enable_skills: ["skill_abc"], + connectors: ["conn_1"], + task_references: ["task_ref_1"], + }, + }); + } finally { + globalThis.fetch = originalFetch; + } +}); From cb96bbc057aed69226c082ead883591979fd39b5 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:32:02 -0700 Subject: [PATCH 49/75] Wire Manus task messages as ContentPart with optional skills --- packages/manus-tools/src/client.ts | 58 ++++++++++++++- packages/manus-tools/src/index.ts | 4 ++ packages/manus-tools/src/tool.ts | 111 +++++++++++++++++++++++++++-- 3 files changed, 168 insertions(+), 5 deletions(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index c46a72f27..f4fe0d5b7 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -198,14 +198,67 @@ export type CreateTaskParams = { readonly hide_in_task_list?: boolean; readonly share_visibility?: string; readonly agent_profile?: string; + readonly enable_skills?: readonly string[]; + readonly force_skills?: readonly string[]; + readonly connectors?: readonly string[]; + readonly task_references?: readonly string[]; + readonly structured_output_schema?: Readonly>; }; +export type TaskTextContentPart = { + readonly type: "text"; + readonly text: string; +}; + +export type TaskMessageSkillFields = { + readonly enable_skills?: readonly string[]; + readonly force_skills?: readonly string[]; + readonly connectors?: readonly string[]; + readonly task_references?: readonly string[]; +}; + +export type TaskMessageBody = { + readonly content: readonly TaskTextContentPart[]; +} & TaskMessageSkillFields; + +/** + * Builds the v2 `message` object: prompt as a ContentPart array, with + * skill/connector/reference arrays omitted when unset. + */ +export function buildTaskMessage( + content: string, + fields?: TaskMessageSkillFields, +): TaskMessageBody { + const message: { + content: readonly TaskTextContentPart[]; + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + } = { + content: [{ type: "text", text: content }], + }; + if (fields?.enable_skills !== undefined) { + message.enable_skills = fields.enable_skills; + } + if (fields?.force_skills !== undefined) { + message.force_skills = fields.force_skills; + } + if (fields?.connectors !== undefined) { + message.connectors = fields.connectors; + } + if (fields?.task_references !== undefined) { + message.task_references = fields.task_references; + } + return message; +} + export async function createTask( config: ManusClientConfig, params: CreateTaskParams, ): Promise { const body: Record = { - message: { content: params.content }, + message: buildTaskMessage(params.content, params), }; if (params.title !== undefined) body["title"] = params.title; if (params.project_id !== undefined) body["project_id"] = params.project_id; @@ -222,6 +275,9 @@ export async function createTask( if (params.agent_profile !== undefined) { body["agent_profile"] = params.agent_profile; } + if (params.structured_output_schema !== undefined) { + body["structured_output_schema"] = params.structured_output_schema; + } const raw = await manusRequest(config, { method: "POST", path: "/v2/task.create", diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index 7013c25b1..c3eb3f291 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -1,6 +1,7 @@ export { CreateTaskResponse, ListMessagesResponse, + buildTaskMessage, createSlideDeck, createTask, extractOutputFiles, @@ -20,6 +21,9 @@ export type { OutputFile, TaskAttachment, TaskEvent, + TaskMessageBody, + TaskMessageSkillFields, + TaskTextContentPart, } from "./client"; export { CREATE_SLIDES_TOOL, diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index 4f9ab756e..e330433a7 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -7,6 +7,7 @@ import type { CredentialCapability } from "@intx/types"; import type { ToolCall, ToolResult } from "@intx/types/runtime"; import { + buildTaskMessage, createSlideDeck, createTask, listTaskMessages, @@ -25,6 +26,7 @@ export const CREATE_SLIDES_TOOL = "create_slides"; type JsonSchemaProperty = { readonly type: string; readonly description: string; + readonly items?: { readonly type: string }; }; type EndpointSpec = { @@ -52,6 +54,26 @@ const OBJECT = (description: string): JsonSchemaProperty => ({ type: "object", description, }); +const STRING_ARRAY = (description: string): JsonSchemaProperty => ({ + type: "array", + description, + items: { type: "string" }, +}); + +const MESSAGE_SKILL_PROPERTIES = { + enable_skills: STRING_ARRAY( + "Skill ids from skill_list to make available. If omitted, the account default skills are used.", + ), + force_skills: STRING_ARRAY( + "Skill ids the agent must invoke. Forced skills are available even when not listed in enable_skills.", + ), + connectors: STRING_ARRAY( + "Connector ids from connector_list to attach to this message.", + ), + task_references: STRING_ARRAY( + "Task ids (up to 20) the agent may browse. Pass the 22-character id, not a URL.", + ), +} as const; export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ { @@ -59,7 +81,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ method: "POST", path: "/v2/task.create", description: - "Creates a Manus task. Pass content as the prompt text (sent as message.content). Poll task_list_msgs for progress.", + "Creates a Manus task. Pass content as the prompt text (sent as message.content ContentPart text). Poll task_list_msgs for progress. Pass skill ids from skill_list via enable_skills or force_skills.", required: ["content"], properties: { content: STRING("Prompt text that starts the task."), @@ -74,6 +96,10 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ ), share_visibility: STRING("private, team, or public."), agent_profile: STRING("manus-1.6, manus-1.6-lite, or manus-1.6-max."), + ...MESSAGE_SKILL_PROPERTIES, + structured_output_schema: OBJECT( + "JSON Schema for structured output extraction. Sent on the create body, not inside message.", + ), }, }, { @@ -135,12 +161,16 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ name: "task_send_msg", method: "POST", path: "/v2/task.sendMessage", - description: "Sends a follow-up message to an existing Manus task.", + description: + "Sends a follow-up message to an existing Manus task. Pass skill ids from skill_list via enable_skills or force_skills.", required: ["task_id", "content"], properties: { task_id: STRING("Task id."), - content: STRING("Follow-up prompt text (sent as message.content)."), + content: STRING( + "Follow-up prompt text (sent as message.content ContentPart text).", + ), agent_profile: STRING("Optional agent profile override."), + ...MESSAGE_SKILL_PROPERTIES, }, }, { @@ -507,7 +537,7 @@ async function runEndpoint( } const body: Record = { task_id: taskId, - message: { content }, + message: buildTaskMessage(content, messageSkillFields(call)), }; const profile = stringArg(call, "agent_profile"); if (profile !== undefined) body["agent_profile"] = profile; @@ -561,6 +591,11 @@ function optionalCreateFields(call: ToolCall): { hide_in_task_list?: boolean; share_visibility?: string; agent_profile?: string; + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + structured_output_schema?: Readonly>; } { const fields: { title?: string; @@ -570,6 +605,11 @@ function optionalCreateFields(call: ToolCall): { hide_in_task_list?: boolean; share_visibility?: string; agent_profile?: string; + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + structured_output_schema?: Readonly>; } = {}; const title = stringArg(call, "title"); if (title !== undefined) fields.title = title; @@ -587,6 +627,69 @@ function optionalCreateFields(call: ToolCall): { if (visibility !== undefined) fields.share_visibility = visibility; const profile = stringArg(call, "agent_profile"); if (profile !== undefined) fields.agent_profile = profile; + const skills = messageSkillFields(call); + if (skills.enable_skills !== undefined) { + fields.enable_skills = skills.enable_skills; + } + if (skills.force_skills !== undefined) { + fields.force_skills = skills.force_skills; + } + if (skills.connectors !== undefined) { + fields.connectors = skills.connectors; + } + if (skills.task_references !== undefined) { + fields.task_references = skills.task_references; + } + const schema = objectArg(call, "structured_output_schema"); + if (schema !== undefined) fields.structured_output_schema = schema; + return fields; +} + +function stringArrayArg( + call: ToolCall, + key: string, +): readonly string[] | undefined { + const value = call.arguments[key]; + if (!Array.isArray(value)) return undefined; + if (!value.every((item) => typeof item === "string")) return undefined; + return value; +} + +function objectArg( + call: ToolCall, + key: string, +): Readonly> | undefined { + const value = call.arguments[key]; + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return undefined; + } + const record: Record = {}; + for (const [field, fieldValue] of Object.entries(value)) { + record[field] = fieldValue; + } + return record; +} + +function messageSkillFields(call: ToolCall): { + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; +} { + const fields: { + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + } = {}; + const enableSkills = stringArrayArg(call, "enable_skills"); + if (enableSkills !== undefined) fields.enable_skills = enableSkills; + const forceSkills = stringArrayArg(call, "force_skills"); + if (forceSkills !== undefined) fields.force_skills = forceSkills; + const connectors = stringArrayArg(call, "connectors"); + if (connectors !== undefined) fields.connectors = connectors; + const taskReferences = stringArrayArg(call, "task_references"); + if (taskReferences !== undefined) fields.task_references = taskReferences; return fields; } From 6e88e22ea95d3a1acbd9e6028cff4c8661d58393 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:32:19 -0700 Subject: [PATCH 50/75] Bump @corbits/manus-tools after skill field wiring --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 67c50ef44..e05e742ad 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.3", + "version": "0.0.4", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 6bf5edc6b..2997aba70 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.3" }, + { name: "@corbits/manus-tools", version: "0.0.4" }, ]; /** From a68ee9b00b98491b00f03dd4c03f5119c05dbd59 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:34:36 -0700 Subject: [PATCH 51/75] Add tests for Manus slide-deck lite agent profile --- packages/manus-tools/src/client.test.ts | 64 +++++++++++++++++++++++++ packages/manus-tools/src/tool.test.ts | 1 + 2 files changed, 65 insertions(+) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 6ceea6f58..94ff04361 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -182,6 +182,7 @@ test("createSlideDeck treats mixed [stopped, running] desc as terminal", async ( }, ], }, + agent_profile: "manus-1.6-lite", }); return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { status: 200, @@ -365,6 +366,7 @@ test("createSlideDeck forwards optional skill fields on create", async () => { }, ); const body = JSON.parse(createBody) as { + agent_profile?: string; message: { enable_skills?: string[]; force_skills?: string[]; @@ -372,4 +374,66 @@ test("createSlideDeck forwards optional skill fields on create", async () => { }; expect(body.message.enable_skills).toEqual(["skill_slides"]); expect(body.message.force_skills).toEqual(["skill_slides"]); + expect(body.agent_profile).toBe("manus-1.6-lite"); +}); + +test("createTask omits agent_profile unless the caller sets it", async () => { + const captured: { body: string } = { body: "" }; + const fetchImpl = (async (_input: URL | string, init?: RequestInit) => { + captured.body = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + }) as unknown as typeof fetch; + + await createTask({ fetchImpl }, { content: "Hello" }); + expect(JSON.parse(captured.body)).toEqual({ + message: { content: [{ type: "text", text: "Hello" }] }, + }); + + await createTask( + { fetchImpl }, + { content: "Hello", agent_profile: "manus-1.6-max" }, + ); + expect(JSON.parse(captured.body)).toEqual({ + message: { content: [{ type: "text", text: "Hello" }] }, + agent_profile: "manus-1.6-max", + }); +}); + +test("createSlideDeck keeps a caller-supplied agent_profile", async () => { + let createBody = ""; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + createBody = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await createSlideDeck( + { fetchImpl }, + { + content: "Onboarding", + agent_profile: "manus-1.6-max", + pollIntervalMs: 0, + maxPolls: 1, + }, + ); + expect(JSON.parse(createBody).agent_profile).toBe("manus-1.6-max"); }); diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index 56ef6153d..f4c26f90c 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -134,6 +134,7 @@ test("create_slides creates a task, polls messages, and surfaces the presentatio ); expect(body.message.enable_skills).toBeUndefined(); expect(body.message.force_skills).toBeUndefined(); + expect(body.agent_profile).toBe("manus-1.6-lite"); return new Response( JSON.stringify({ ok: true, From 5cecd580e201809a871e8ff6c9677b9da5dc8c0e Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:34:51 -0700 Subject: [PATCH 52/75] Default Manus slide-deck creates to the lite agent profile --- packages/manus-tools/src/client.ts | 7 +++++++ packages/manus-tools/src/index.ts | 1 + 2 files changed, 8 insertions(+) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index f4fe0d5b7..850b2cfe6 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -386,6 +386,9 @@ export const DEFAULT_SLIDE_POLL_INTERVAL_MS = 2_000; /** 5 minutes at the default interval — a real deck takes longer than 60s. */ export const DEFAULT_SLIDE_MAX_POLLS = 150; +/** Free/personal accounts persist tasks only on the lite profile. */ +export const SLIDE_DECK_AGENT_PROFILE = "manus-1.6-lite"; + const SLIDE_DECK_PROMPT_PREFIX = "Create a slide presentation in pptx format. Produce a presentation " + "deck, not a document. Topic and requirements:\n\n"; @@ -447,6 +450,10 @@ export async function createSlideDeck( const created = await createTask(config, { ...taskParams, content: `${SLIDE_DECK_PROMPT_PREFIX}${taskParams.content}`, + agent_profile: + taskParams.agent_profile !== undefined + ? taskParams.agent_profile + : SLIDE_DECK_AGENT_PROFILE, }); const intervalMs = pollIntervalMs ?? DEFAULT_SLIDE_POLL_INTERVAL_MS; const polls = maxPolls ?? DEFAULT_SLIDE_MAX_POLLS; diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index c3eb3f291..15e93490a 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -11,6 +11,7 @@ export { DEFAULT_MANUS_BASE_URL, DEFAULT_SLIDE_MAX_POLLS, DEFAULT_SLIDE_POLL_INTERVAL_MS, + SLIDE_DECK_AGENT_PROFILE, SLIDES_FORMAT_PPTX, } from "./client"; export type { From f0ebfeb9ae3c1320947ef6fb1398eecea79fbbc4 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:34:57 -0700 Subject: [PATCH 53/75] Bump @corbits/manus-tools after the lite profile default --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index e05e742ad..dd61482a9 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.4", + "version": "0.0.5", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 2997aba70..5b78f8d32 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.4" }, + { name: "@corbits/manus-tools", version: "0.0.5" }, ]; /** From 0bb54fdcca761eed9f0c9a70c1810b22903e1133 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:49:33 -0700 Subject: [PATCH 54/75] Add tests for Manus createTask lite agent profile default --- packages/manus-tools/src/client.test.ts | 15 +++++++++++- packages/manus-tools/src/tool.test.ts | 32 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 94ff04361..db1eab933 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -43,6 +43,7 @@ test("createTask posts to /v2/task.create and parses the ok envelope", async () expect(captured.headers?.get("x-api-key")).toBeNull(); expect(JSON.parse(captured.body)).toEqual({ message: { content: [{ type: "text", text: "Make slides" }] }, + agent_profile: "manus-1.6-lite", }); expect(created.task_id).toBe("task_1"); expect(created.task_url).toBe("https://manus.im/app/task_1"); @@ -91,6 +92,7 @@ test("createTask posts skill, connector, and schema fields only when set", async required: ["title"], additionalProperties: false, }, + agent_profile: "manus-1.6-lite", }); }); @@ -377,7 +379,7 @@ test("createSlideDeck forwards optional skill fields on create", async () => { expect(body.agent_profile).toBe("manus-1.6-lite"); }); -test("createTask omits agent_profile unless the caller sets it", async () => { +test("createTask defaults agent_profile to manus-1.6-lite when omitted", async () => { const captured: { body: string } = { body: "" }; const fetchImpl = (async (_input: URL | string, init?: RequestInit) => { captured.body = typeof init?.body === "string" ? init.body : ""; @@ -389,7 +391,18 @@ test("createTask omits agent_profile unless the caller sets it", async () => { await createTask({ fetchImpl }, { content: "Hello" }); expect(JSON.parse(captured.body)).toEqual({ message: { content: [{ type: "text", text: "Hello" }] }, + agent_profile: "manus-1.6-lite", }); +}); + +test("createTask keeps a caller-supplied agent_profile", async () => { + const captured: { body: string } = { body: "" }; + const fetchImpl = (async (_input: URL | string, init?: RequestInit) => { + captured.body = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + }) as unknown as typeof fetch; await createTask( { fetchImpl }, diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index f4c26f90c..2c2cb9d43 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -254,6 +254,36 @@ test("task_create and task_send_msg expose skill and connector fields", () => { } expect(create?.properties["structured_output_schema"]?.type).toBe("object"); expect(send?.properties["structured_output_schema"]).toBeUndefined(); + expect(create?.properties["agent_profile"]?.description).toContain( + "manus-1.6-lite", + ); + expect(create?.properties["agent_profile"]?.description).toMatch(/default/i); +}); + +test("task_create without agent_profile posts manus-1.6-lite", async () => { + const originalFetch = globalThis.fetch; + let createBody = ""; + globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { + createBody = typeof init?.body === "string" ? init.body : ""; + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + { + id: "call_create_default_profile", + name: "task_create", + arguments: { content: "Hello" }, + }, + new AbortController().signal, + ); + expect(result.isError).toBeUndefined(); + expect(JSON.parse(createBody).agent_profile).toBe("manus-1.6-lite"); + } finally { + globalThis.fetch = originalFetch; + } }); test("task_create omits skill fields unless the assistant passes ids", async () => { @@ -279,6 +309,7 @@ test("task_create omits skill fields unless the assistant passes ids", async () expect(omitted.isError).toBeUndefined(); expect(JSON.parse(createBody)).toEqual({ message: { content: [{ type: "text", text: "Hello" }] }, + agent_profile: "manus-1.6-lite", }); const present = await bundle.run( @@ -306,6 +337,7 @@ test("task_create omits skill fields unless the assistant passes ids", async () task_references: ["task_ref_1"], }, structured_output_schema: { type: "object" }, + agent_profile: "manus-1.6-lite", }); } finally { globalThis.fetch = originalFetch; From 5c1c589c5dc877a5d7017b34970060252f248a6f Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:50:24 -0700 Subject: [PATCH 55/75] Default Manus createTask to the lite agent profile --- packages/manus-tools/src/client.ts | 10 +++++----- packages/manus-tools/src/index.ts | 1 + packages/manus-tools/src/tool.ts | 4 +++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 850b2cfe6..02d840ba3 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -189,6 +189,9 @@ export async function manusRequest( return parseOkBody(body); } +/** Free/personal accounts persist tasks only on the lite profile. */ +export const DEFAULT_AGENT_PROFILE = "manus-1.6-lite"; + export type CreateTaskParams = { readonly content: string; readonly title?: string; @@ -272,9 +275,7 @@ export async function createTask( if (params.share_visibility !== undefined) { body["share_visibility"] = params.share_visibility; } - if (params.agent_profile !== undefined) { - body["agent_profile"] = params.agent_profile; - } + body["agent_profile"] = params.agent_profile ?? DEFAULT_AGENT_PROFILE; if (params.structured_output_schema !== undefined) { body["structured_output_schema"] = params.structured_output_schema; } @@ -386,8 +387,7 @@ export const DEFAULT_SLIDE_POLL_INTERVAL_MS = 2_000; /** 5 minutes at the default interval — a real deck takes longer than 60s. */ export const DEFAULT_SLIDE_MAX_POLLS = 150; -/** Free/personal accounts persist tasks only on the lite profile. */ -export const SLIDE_DECK_AGENT_PROFILE = "manus-1.6-lite"; +export const SLIDE_DECK_AGENT_PROFILE = DEFAULT_AGENT_PROFILE; const SLIDE_DECK_PROMPT_PREFIX = "Create a slide presentation in pptx format. Produce a presentation " + diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index 15e93490a..682f0eef1 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -11,6 +11,7 @@ export { DEFAULT_MANUS_BASE_URL, DEFAULT_SLIDE_MAX_POLLS, DEFAULT_SLIDE_POLL_INTERVAL_MS, + DEFAULT_AGENT_PROFILE, SLIDE_DECK_AGENT_PROFILE, SLIDES_FORMAT_PPTX, } from "./client"; diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index e330433a7..5268ee1b9 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -95,7 +95,9 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ "When true, hide the task from the Manus task list.", ), share_visibility: STRING("private, team, or public."), - agent_profile: STRING("manus-1.6, manus-1.6-lite, or manus-1.6-max."), + agent_profile: STRING( + "Defaults to manus-1.6-lite. Other values: manus-1.6, manus-1.6-max.", + ), ...MESSAGE_SKILL_PROPERTIES, structured_output_schema: OBJECT( "JSON Schema for structured output extraction. Sent on the create body, not inside message.", From 635203b5b7c5f809ffcf251f2bb1f246dd831a87 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:50:40 -0700 Subject: [PATCH 56/75] Bump @corbits/manus-tools after the createTask lite default --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index dd61482a9..64d43a594 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.5", + "version": "0.0.6", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 5b78f8d32..32d2e7f6f 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.5" }, + { name: "@corbits/manus-tools", version: "0.0.6" }, ]; /** From 1ddddf233d4cbc1347ecfe4bf8a19b3f06654b22 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:55:37 -0700 Subject: [PATCH 57/75] Add tests for Manus slide-deck listMessages not_found retry --- packages/manus-tools/src/client.test.ts | 107 ++++++++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index db1eab933..27c63d857 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -450,3 +450,110 @@ test("createSlideDeck keeps a caller-supplied agent_profile", async () => { ); expect(JSON.parse(createBody).agent_profile).toBe("manus-1.6-max"); }); + +test("createSlideDeck retries listMessages not_found then succeeds when the task is readable", async () => { + let listCalls = 0; + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listCalls += 1; + if (listCalls === 1) { + return new Response( + JSON.stringify({ + ok: false, + error: { code: "not_found", message: "Task not found" }, + }), + { status: 404 }, + ); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + const result = await createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 3 }, + ); + expect(result.agent_status).toBe("stopped"); + expect(listCalls).toBe(2); +}); + +test("createSlideDeck still throws unrelated listMessages errors", async () => { + let listCalls = 0; + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listCalls += 1; + return new Response( + JSON.stringify({ + ok: false, + error: { code: "permission_denied", message: "bad key" }, + }), + { status: 401 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 3 }, + ), + ).rejects.toThrow(/permission_denied: bad key/); + expect(listCalls).toBe(1); +}); + +test("createSlideDeck throws when listMessages stays not_found through the poll budget", async () => { + let listCalls = 0; + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listCalls += 1; + return new Response( + JSON.stringify({ + ok: false, + error: { code: "not_found", message: "Task not found" }, + }), + { status: 404 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 2 }, + ), + ).rejects.toThrow(/did not stop in time|not_found: Task not found/); + expect(listCalls).toBe(2); +}); From 040adc8840a183bdfd463c56d34f4380515016fb Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:56:11 -0700 Subject: [PATCH 58/75] Retry Manus slide-deck polls on listMessages not_found --- packages/manus-tools/src/client.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 02d840ba3..11ff3455e 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -399,6 +399,13 @@ export type CreateSlideDeckParams = CreateTaskParams & { readonly signal?: AbortSignal; }; +function isManusTaskNotFoundError(error: unknown): boolean { + return ( + error instanceof Error && + error.message.includes("Manus request failed: not_found: Task not found") + ); +} + function throwIfSlideWaitAborted(signal: AbortSignal | undefined): void { if (signal?.aborted) { throw new Error("Manus slide-deck wait was cancelled"); @@ -460,10 +467,18 @@ export async function createSlideDeck( let messages: ListMessagesResponse | undefined; for (let i = 0; i < polls; i += 1) { throwIfSlideWaitAborted(signal); - messages = await listTaskMessages(config, { - task_id: created.task_id, - slides_format: SLIDES_FORMAT_PPTX, - }); + try { + messages = await listTaskMessages(config, { + task_id: created.task_id, + slides_format: SLIDES_FORMAT_PPTX, + }); + } catch (error) { + if (!isManusTaskNotFoundError(error)) throw error; + if (i < polls - 1) { + await sleep(intervalMs, signal); + } + continue; + } const status = latestAgentStatus(messages.messages); if (status !== undefined && TERMINAL_STATUSES.has(status)) break; if (status === "waiting") { From 006c24ade10e22c70eb53e6ae41b6caa5d46e573 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:56:31 -0700 Subject: [PATCH 59/75] Bump @corbits/manus-tools after listMessages not_found retry --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 64d43a594..d9d2f0a1c 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.6", + "version": "0.0.7", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 32d2e7f6f..fa369f7b9 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.6" }, + { name: "@corbits/manus-tools", version: "0.0.7" }, ]; /** From d159d8f8a7db0ac7086e13c32bdc7cdb454cef15 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:59:33 -0700 Subject: [PATCH 60/75] Add tests for Manus listMessages string timestamps Live list-messages bodies send ISO strings on timestamp. Pin that parse path, keep numeric timestamps, and still extract agent_status and attachments. --- packages/manus-tools/src/client.test.ts | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 27c63d857..736799bfa 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -5,6 +5,7 @@ import { createTask, DEFAULT_SLIDE_MAX_POLLS, DEFAULT_SLIDE_POLL_INTERVAL_MS, + extractOutputFiles, latestAgentStatus, listTaskMessages, manusRequest, @@ -132,6 +133,69 @@ test("listTaskMessages GETs /v2/task.listMessages without an auth header", async expect(listed.messages?.[0]?.status_update?.agent_status).toBe("stopped"); }); +test("listTaskMessages parses ISO string timestamps and still extracts status and attachments", async () => { + const fetchImpl = (async () => + new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + timestamp: "2026-08-26T12:00:00.000Z", + status_update: { agent_status: "stopped" }, + }, + { + type: "assistant_message", + timestamp: "2026-08-26T12:00:01.000Z", + assistant_message: { + content: "Here is the deck.", + attachments: [ + { + filename: "onboarding.pptx", + url: "https://files.manus.ai/onboarding.pptx", + }, + ], + }, + }, + ], + }), + { status: 200 }, + )) as unknown as typeof fetch; + + const listed = await listTaskMessages({ fetchImpl }, { task_id: "task_1" }); + expect(listed.messages?.[0]?.timestamp).toBe("2026-08-26T12:00:00.000Z"); + expect(latestAgentStatus(listed.messages)).toBe("stopped"); + expect(extractOutputFiles(listed.messages)).toEqual([ + { + filename: "onboarding.pptx", + url: "https://files.manus.ai/onboarding.pptx", + }, + ]); +}); + +test("listTaskMessages parses numeric timestamps", async () => { + const fetchImpl = (async () => + new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + timestamp: 1756224000, + status_update: { agent_status: "running" }, + }, + ], + }), + { status: 200 }, + )) as unknown as typeof fetch; + + const listed = await listTaskMessages({ fetchImpl }, { task_id: "task_1" }); + expect(listed.messages?.[0]?.timestamp).toBe(1756224000); + expect(listed.messages?.[0]?.status_update?.agent_status).toBe("running"); +}); + test("maps a non-ok HTTP body with a Manus error envelope", async () => { const fetchImpl = (async () => new Response( From 26de5b6804164f01e952a10c5cf97ffe58c83592 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:59:45 -0700 Subject: [PATCH 61/75] Accept string or number timestamps on Manus TaskEvent Live list-messages returns ISO strings. The plugin does not use timestamp for status or files, so both shapes must parse. --- packages/manus-tools/src/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 11ff3455e..3ec6cbb83 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -43,7 +43,7 @@ export type TaskAttachment = typeof TaskAttachment.infer; const TaskEvent = type({ "id?": "string", "type?": "string", - "timestamp?": "number", + "timestamp?": "number | string", "assistant_message?": { "content?": "string", "attachments?": TaskAttachment.array(), From 2c7b8a0ed08fe2ed603a6a76a3350b301793bc17 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 22:59:50 -0700 Subject: [PATCH 62/75] Bump @corbits/manus-tools after string timestamp parse --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index d9d2f0a1c..6ff56e436 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.7", + "version": "0.0.8", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index fa369f7b9..a0a2040ab 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.7" }, + { name: "@corbits/manus-tools", version: "0.0.8" }, ]; /** From b85a6b9d88fefd621eb325916b452d84c1934b63 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 23:02:30 -0700 Subject: [PATCH 63/75] Add tests for lowercase Manus listMessages not_found Live create_slides 404s with "task not found". Pin retry on that casing while keeping the capital-T envelope. --- packages/manus-tools/src/client.test.ts | 45 +++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 736799bfa..af04a9f5f 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -560,6 +560,51 @@ test("createSlideDeck retries listMessages not_found then succeeds when the task expect(listCalls).toBe(2); }); +test("createSlideDeck retries listMessages not_found with lowercase task not found", async () => { + let listCalls = 0; + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + if (url.includes("/v2/task.listMessages")) { + listCalls += 1; + if (listCalls === 1) { + return new Response( + JSON.stringify({ + ok: false, + error: { code: "not_found", message: "task not found" }, + }), + { status: 404 }, + ); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "stopped" }, + }, + ], + }), + { status: 200 }, + ); + } + return new Response("unexpected", { status: 500 }); + }) as unknown as typeof fetch; + + const result = await createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 3 }, + ); + expect(result.agent_status).toBe("stopped"); + expect(listCalls).toBe(2); +}); + test("createSlideDeck still throws unrelated listMessages errors", async () => { let listCalls = 0; const fetchImpl = (async (input: URL | string) => { From dae34fc15af68f5ee7feb887aa6c78a713eb5a02 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 23:02:53 -0700 Subject: [PATCH 64/75] Match Manus listMessages not_found without Task casing Live 404s say "task not found". Treat any Manus not_found as retryable during listMessages poll. --- packages/manus-tools/src/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 3ec6cbb83..06db73539 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -402,7 +402,7 @@ export type CreateSlideDeckParams = CreateTaskParams & { function isManusTaskNotFoundError(error: unknown): boolean { return ( error instanceof Error && - error.message.includes("Manus request failed: not_found: Task not found") + error.message.toLowerCase().includes("manus request failed: not_found") ); } From 1fe58e6b10030e523f7faf66e592954f6e1db38a Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Wed, 26 Aug 2026 23:03:08 -0700 Subject: [PATCH 65/75] Bump @corbits/manus-tools after lowercase not_found match --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 6ff56e436..51472bb5b 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.8", + "version": "0.0.9", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index a0a2040ab..5e9195d3b 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.8" }, + { name: "@corbits/manus-tools", version: "0.0.9" }, ]; /** From d9acaf08376166517e62cc55a406e063812c05c3 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Thu, 27 Aug 2026 11:56:44 -0700 Subject: [PATCH 66/75] Validate Manus task detail responses --- packages/manus-tools/package.json | 2 +- packages/manus-tools/src/client.test.ts | 19 +++++- packages/manus-tools/src/client.ts | 45 ++++++++++++++ packages/manus-tools/src/index.ts | 3 + packages/manus-tools/src/tool.test.ts | 79 +++++++++++++++++++++++-- packages/manus-tools/src/tool.ts | 17 ++++++ workflows/assistant/src/index.ts | 2 +- 7 files changed, 159 insertions(+), 8 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index 51472bb5b..fdd07422f 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.9", + "version": "0.0.10", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index af04a9f5f..7b9f2075c 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -6,6 +6,7 @@ import { DEFAULT_SLIDE_MAX_POLLS, DEFAULT_SLIDE_POLL_INTERVAL_MS, extractOutputFiles, + getTaskDetail, latestAgentStatus, listTaskMessages, manusRequest, @@ -97,6 +98,21 @@ test("createTask posts skill, connector, and schema fields only when set", async }); }); +test("getTaskDetail rejects a malformed successful task payload", async () => { + const fetchImpl = (async () => + new Response( + JSON.stringify({ + ok: true, + task: { id: "task_1", status: "completed" }, + }), + { status: 200 }, + )) as unknown as typeof fetch; + + await expect(getTaskDetail({ fetchImpl }, "task_1")).rejects.toThrow( + /task-detail response did not match the expected shape/, + ); +}); + test("listTaskMessages GETs /v2/task.listMessages without an auth header", async () => { const captured: { url: string; headers: Headers | null } = { url: "", @@ -243,8 +259,7 @@ test("createSlideDeck treats mixed [stopped, running] desc as terminal", async ( content: [ { type: "text", - text: - "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + text: "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", }, ], }, diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 06db73539..860267e62 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -71,6 +71,33 @@ export const CreateTaskResponse = type({ }); export type CreateTaskResponse = typeof CreateTaskResponse.infer; +const TaskCreatorAPIKey = type({ + id: "string", + name: "string", +}); + +const TaskDetail = type({ + id: "string", + status: "'running' | 'stopped' | 'waiting' | 'error'", + "created_at?": "number", + "updated_at?": "number", + "task_type?": "'standard' | 'project' | 'agent_subtask'", + "share_visibility?": "'private' | 'team' | 'public'", + "title?": "string", + "credit_usage?": "number", + "task_url?": "string", + "created_by_api_key?": TaskCreatorAPIKey.or("null"), + "agent_profile?": "'manus-1.6' | 'manus-1.6-lite' | 'manus-1.6-max'", +}); +export type TaskDetail = typeof TaskDetail.infer; + +export const TaskDetailResponse = type({ + ok: "true", + "request_id?": "string", + task: TaskDetail, +}); +export type TaskDetailResponse = typeof TaskDetailResponse.infer; + export const ListMessagesResponse = type({ ok: "true", "request_id?": "string", @@ -293,6 +320,24 @@ export async function createTask( return parsed; } +export async function getTaskDetail( + config: ManusClientConfig, + taskId: string, +): Promise { + const raw = await manusRequest(config, { + method: "GET", + path: "/v2/task.detail", + params: { task_id: taskId }, + }); + const parsed = TaskDetailResponse(raw); + if (parsed instanceof type.errors) { + throw new Error( + `Manus task-detail response did not match the expected shape: ${parsed.summary}`, + ); + } + return parsed; +} + export type ListMessagesParams = { readonly task_id: string; readonly limit?: number; diff --git a/packages/manus-tools/src/index.ts b/packages/manus-tools/src/index.ts index 682f0eef1..5c570ae8d 100644 --- a/packages/manus-tools/src/index.ts +++ b/packages/manus-tools/src/index.ts @@ -1,10 +1,12 @@ export { CreateTaskResponse, ListMessagesResponse, + TaskDetailResponse, buildTaskMessage, createSlideDeck, createTask, extractOutputFiles, + getTaskDetail, latestAgentStatus, listTaskMessages, manusRequest, @@ -22,6 +24,7 @@ export type { ManusClientConfig, OutputFile, TaskAttachment, + TaskDetail, TaskEvent, TaskMessageBody, TaskMessageSkillFields, diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index 2c2cb9d43..598e1c5d1 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -286,15 +286,86 @@ test("task_create without agent_profile posts manus-1.6-lite", async () => { } }); +test("task_create result feeds task_detail through the validated GET boundary", async () => { + const originalFetch = globalThis.fetch; + const createdTaskId = "task_created_42"; + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + const url = String(input); + if (url === "https://api.manus.ai/v2/task.create") { + return new Response( + JSON.stringify({ ok: true, task_id: createdTaskId }), + { status: 200 }, + ); + } + expect(url).toBe( + `https://api.manus.ai/v2/task.detail?task_id=${createdTaskId}`, + ); + expect(init?.method).toBe("GET"); + return new Response( + JSON.stringify({ + ok: true, + request_id: "req_detail_1", + task: { + id: createdTaskId, + status: "running", + title: "Deterministic read", + task_type: "standard", + share_visibility: "private", + agent_profile: "manus-1.6-lite", + }, + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const created = await bundle.run( + { + id: "call_create_then_read", + name: "task_create", + arguments: { content: "Create a deterministic task" }, + }, + new AbortController().signal, + ); + expect(created.isError).toBeUndefined(); + const createResult = JSON.parse(created.content as string) as { + task_id: string; + }; + + const detail = await bundle.run( + { + id: "call_task_detail", + name: "task_detail", + arguments: { task_id: createResult.task_id }, + }, + new AbortController().signal, + ); + expect(detail.isError).toBeUndefined(); + expect(JSON.parse(detail.content as string)).toEqual({ + ok: true, + request_id: "req_detail_1", + task: { + id: createdTaskId, + status: "running", + title: "Deterministic read", + task_type: "standard", + share_visibility: "private", + agent_profile: "manus-1.6-lite", + }, + }); + } finally { + globalThis.fetch = originalFetch; + } +}); + test("task_create omits skill fields unless the assistant passes ids", async () => { const originalFetch = globalThis.fetch; let createBody = ""; globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { createBody = typeof init?.body === "string" ? init.body : ""; - return new Response( - JSON.stringify({ ok: true, task_id: "task_1" }), - { status: 200 }, - ); + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); }) as unknown as typeof fetch; try { const bundle = manusTools(fakeEnv(fakeCredentials("key"))); diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index 5268ee1b9..e55e854b2 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -10,6 +10,7 @@ import { buildTaskMessage, createSlideDeck, createTask, + getTaskDetail, listTaskMessages, manusRequest, type ManusClientConfig, @@ -527,6 +528,22 @@ async function runEndpoint( return errorResult(call.id, err); } } + if (spec.name === "task_detail") { + const taskId = stringArg(call, "task_id"); + if (taskId === undefined || taskId === "") { + return { + callId: call.id, + content: "task_detail requires a non-empty task_id argument", + isError: true, + }; + } + try { + const detail = await getTaskDetail(asClientConfig(credential), taskId); + return { callId: call.id, content: JSON.stringify(detail) }; + } catch (err) { + return errorResult(call.id, err); + } + } if (spec.name === "task_send_msg") { const content = stringArg(call, "content"); const taskId = stringArg(call, "task_id"); diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index 5e9195d3b..a0eb94e77 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.9" }, + { name: "@corbits/manus-tools", version: "0.0.10" }, ]; /** From 439d8039a646e64fba0e9769b847ac0a2edefaa6 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Thu, 27 Aug 2026 15:55:12 -0700 Subject: [PATCH 67/75] Gate mutating Manus tools and flag create_slides agent errors Webhook, website publish/update, and task/file delete now declare approval ask so an assistant pin cannot auto-allow those calls. create_slides maps agent_status error to a thrown failure so the tool result is isError. --- apps/hub/src/tool-grants.test.ts | 19 +++++++++ packages/manus-tools/src/client.test.ts | 31 ++++++++++++++ packages/manus-tools/src/client.ts | 15 +++++-- packages/manus-tools/src/tool.test.ts | 56 +++++++++++++++++++++++++ packages/manus-tools/src/tool.ts | 15 ++++++- 5 files changed, 132 insertions(+), 4 deletions(-) diff --git a/apps/hub/src/tool-grants.test.ts b/apps/hub/src/tool-grants.test.ts index 7a69eb3d2..b2636f304 100644 --- a/apps/hub/src/tool-grants.test.ts +++ b/apps/hub/src/tool-grants.test.ts @@ -4,6 +4,7 @@ // `@corbits/folded-runs`' `deployAtHead`, which mints these into // `config.grants`. import { describe, expect, test } from "bun:test"; +import { describeCorbitsToolPackages } from "@corbits/tool-registry-publish"; import { createToolGrantsForPins } from "./tool-grants"; const DESCRIPTIONS = [ @@ -85,4 +86,22 @@ describe("createToolGrantsForPins", () => { const toolGrantsForPins = createToolGrantsForPins(DESCRIPTIONS); expect(toolGrantsForPins([])).toEqual([]); }); + + test("assistant pin of webhook_create is ask, not allow", async () => { + const toolGrantsForPins = createToolGrantsForPins( + await describeCorbitsToolPackages(), + ); + const grants = toolGrantsForPins([ + { name: "@corbits/manus-tools", version: "*" }, + ]); + expect( + grants.find((g) => g.resource.endsWith(":webhook_create"))?.effect, + ).toBe("ask"); + expect( + grants.find((g) => g.resource.endsWith(":create_slides"))?.effect, + ).toBe("allow"); + expect(grants.find((g) => g.resource.endsWith(":task_list"))?.effect).toBe( + "allow", + ); + }); }); diff --git a/packages/manus-tools/src/client.test.ts b/packages/manus-tools/src/client.test.ts index 7b9f2075c..992018ac7 100644 --- a/packages/manus-tools/src/client.test.ts +++ b/packages/manus-tools/src/client.test.ts @@ -365,6 +365,37 @@ test("createSlideDeck throws when the agent is waiting", async () => { ).rejects.toThrow(/waiting for confirmation/); }); +test("createSlideDeck throws when the agent_status is error", async () => { + const fetchImpl = (async (input: URL | string) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "error" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + + await expect( + createSlideDeck( + { fetchImpl }, + { content: "Onboarding", pollIntervalMs: 0, maxPolls: 5 }, + ), + ).rejects.toThrow(/agent_status error/); +}); + test("createSlideDeck aborts polling instead of waiting out the timeout", async () => { const controller = new AbortController(); const fetchImpl = (async (input: URL | string) => { diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts index 860267e62..900a300e3 100644 --- a/packages/manus-tools/src/client.ts +++ b/packages/manus-tools/src/client.ts @@ -483,9 +483,10 @@ function sleep(ms: number, signal?: AbortSignal): Promise { /** * Creates a task whose prompt asks Manus to produce a slide deck, then - * polls `task.listMessages` until the agent stops (or errors) and returns - * any output files so a caller can retrieve them. A timeout, a still-running - * or waiting agent, or an abort is a thrown error — never a successful deck. + * polls `task.listMessages` until the agent stops and returns any output + * files so a caller can retrieve them. A timeout, a still-running or + * waiting agent, an `error` status, or an abort is a thrown error — + * never a successful deck. */ export async function createSlideDeck( config: ManusClientConfig, @@ -542,6 +543,14 @@ export async function createSlideDeck( (status !== undefined ? ` (agent_status: ${status})` : ""), ); } + if (status === "error") { + const errorEvent = messages?.messages?.find((event) => event.error_message); + const detail = errorEvent?.error_message?.content; + throw new Error( + `Manus task ${created.task_id} ended with agent_status error` + + (detail !== undefined ? `: ${detail}` : ""), + ); + } const files = extractOutputFiles(messages?.messages); const errorEvent = messages?.messages?.find((event) => event.error_message); const result: { diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts index 598e1c5d1..ec66e6e69 100644 --- a/packages/manus-tools/src/tool.test.ts +++ b/packages/manus-tools/src/tool.test.ts @@ -82,6 +82,26 @@ test("declares create_slides plus thin tools covering the v2 surface", () => { expect(names.length).toBe(MANUS_ENDPOINTS.length + 1); }); +test("mutating admin tools declare approval ask; create_slides and read-ish tools stay ungated", () => { + const byName = new Map(manusTools.definitions.map((d) => [d.name, d])); + for (const name of [ + "webhook_create", + "webhook_delete", + "webhook_list", + "webhook_pubkey", + "website_publish", + "website_update", + "task_delete", + "file_delete", + ] as const) { + expect(byName.get(name)).toEqual({ name, approval: "ask" }); + } + expect(byName.get(CREATE_SLIDES_TOOL)).toEqual({ name: CREATE_SLIDES_TOOL }); + expect(byName.get("task_list")).toEqual({ name: "task_list" }); + expect(byName.get("task_list_msgs")).toEqual({ name: "task_list_msgs" }); + expect(byName.get("file_detail")).toEqual({ name: "file_detail" }); +}); + test("task_list_msgs describes slides_format as pptx or html, never pdf", () => { const listMsgs = MANUS_ENDPOINTS.find( (spec) => spec.name === "task_list_msgs", @@ -227,6 +247,42 @@ test("create_slides returns isError when the agent is waiting", async () => { } }); +test("create_slides returns isError when the agent_status is error", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async (input: unknown) => { + const url = String(input); + if (url.includes("/v2/task.create")) { + return new Response(JSON.stringify({ ok: true, task_id: "task_1" }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + ok: true, + task_id: "task_1", + messages: [ + { + type: "status_update", + status_update: { agent_status: "error" }, + }, + ], + }), + { status: 200 }, + ); + }) as unknown as typeof fetch; + try { + const bundle = manusTools(fakeEnv(fakeCredentials("key"))); + const result = await bundle.run( + CREATE_SLIDES_CALL, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toMatch(/agent_status error/); + } finally { + globalThis.fetch = originalFetch; + } +}); + test("degrades to an error result (never throws) when the underlying call fails", async () => { const originalFetch = globalThis.fetch; globalThis.fetch = (async () => diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts index e55e854b2..68730af10 100644 --- a/packages/manus-tools/src/tool.ts +++ b/packages/manus-tools/src/tool.ts @@ -37,6 +37,7 @@ type EndpointSpec = { readonly description: string; readonly required: readonly string[]; readonly properties: Readonly>; + readonly approval?: "ask"; }; const STRING = (description: string): JsonSchemaProperty => ({ @@ -159,6 +160,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Deletes a Manus task.", required: ["task_id"], properties: { task_id: STRING("Task id.") }, + approval: "ask", }, { name: "task_send_msg", @@ -284,6 +286,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Deletes a Manus file.", required: ["file_id"], properties: { file_id: STRING("File id.") }, + approval: "ask", }, { name: "webhook_create", @@ -292,6 +295,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Creates a Manus webhook.", required: ["url"], properties: { url: STRING("Webhook callback URL.") }, + approval: "ask", }, { name: "webhook_list", @@ -300,6 +304,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Lists Manus webhooks.", required: [], properties: {}, + approval: "ask", }, { name: "webhook_delete", @@ -308,6 +313,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Deletes a Manus webhook.", required: ["webhook_id"], properties: { webhook_id: STRING("Webhook id.") }, + approval: "ask", }, { name: "webhook_pubkey", @@ -316,6 +322,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ description: "Returns the Manus webhook signing public key.", required: [], properties: {}, + approval: "ask", }, { name: "usage_list", @@ -400,6 +407,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ website_id: STRING("Website id."), visibility: STRING("Visibility."), }, + approval: "ask", }, { name: "website_update", @@ -413,6 +421,7 @@ export const MANUS_ENDPOINTS: readonly EndpointSpec[] = [ title: STRING("New title."), visibility: STRING("Visibility."), }, + approval: "ask", }, { name: "website_ckpts", @@ -799,7 +808,11 @@ export const manusTools = defineTool({ requires: ["credentials"], definitions: [ { name: CREATE_SLIDES_TOOL }, - ...MANUS_ENDPOINTS.map((spec) => ({ name: spec.name })), + ...MANUS_ENDPOINTS.map((spec) => + spec.approval === "ask" + ? { name: spec.name, approval: "ask" as const } + : { name: spec.name }, + ), ], factory: (env) => ({ definitions: [ From b2af57130d431af7fa5f2728692b76428273a0f2 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Thu, 27 Aug 2026 15:55:18 -0700 Subject: [PATCH 68/75] Bump @corbits/manus-tools after admin-tool gates --- packages/manus-tools/package.json | 2 +- workflows/assistant/src/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json index fdd07422f..7da533d97 100644 --- a/packages/manus-tools/package.json +++ b/packages/manus-tools/package.json @@ -2,7 +2,7 @@ "name": "@corbits/manus-tools", "private": true, "description": "Manus integration: a v2 API client and an @intx/agent tool bundle for running tasks and retrieving files", - "version": "0.0.10", + "version": "0.0.11", "license": "LGPL-2.1-or-later", "type": "module", "exports": { diff --git a/workflows/assistant/src/index.ts b/workflows/assistant/src/index.ts index a0eb94e77..13b474fc6 100644 --- a/workflows/assistant/src/index.ts +++ b/workflows/assistant/src/index.ts @@ -53,7 +53,7 @@ export const ASSISTANT_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ { name: "@corbits/skills-tools", version: "0.0.6" }, { name: "@corbits/mcp-tools", version: "0.0.9" }, { name: "@corbits/interaction-tools", version: "0.0.2" }, - { name: "@corbits/manus-tools", version: "0.0.10" }, + { name: "@corbits/manus-tools", version: "0.0.11" }, ]; /** From 671e9a79c2b699e7befb769fd7f54e62b6359949 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Sat, 29 Aug 2026 10:36:30 -0700 Subject: [PATCH 69/75] Pass DATABASE_URL into walking-skeleton package suites --- .github/workflows/ci.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b65995898..fd97c7d47 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -179,6 +179,7 @@ jobs: run: bun run test:e2e env: E2E_REQUIRED: "1" + DATABASE_URL: postgres://postgres:postgres@localhost:5432/workbench - name: Run the two-org isolation suite run: bun test test/isolation @@ -191,6 +192,7 @@ jobs: run: bun test apps/hub/test env: E2E_REQUIRED: "1" + DATABASE_URL: postgres://postgres:postgres@localhost:5432/workbench # Every DB-gated suite under packages/* and apps/hub/src gates on # DATABASE_URL and describe.skip's without one, so build-test (no @@ -203,3 +205,4 @@ jobs: bun test $(grep -rl DATABASE_URL --include='*.test.ts' packages apps | grep -v apps/hub/test) env: E2E_REQUIRED: "1" + DATABASE_URL: postgres://postgres:postgres@localhost:5432/workbench From b436e82a964bf2e4eb32e617c5ddbba1b1843e58 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Sat, 29 Aug 2026 10:47:36 -0700 Subject: [PATCH 70/75] Export .env before walking-skeleton package suites --- .github/workflows/ci.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd97c7d47..4d0835dca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -189,7 +189,11 @@ jobs: # Postgres. E2E_REQUIRED=1 turns a would-be skip here into a hard # failure, so a misconfigured invocation can't pass vacuously. - name: Run the hub's database-backed suites - run: bun test apps/hub/test + run: | + set -a + . ./.env + set +a + bun test apps/hub/test env: E2E_REQUIRED: "1" DATABASE_URL: postgres://postgres:postgres@localhost:5432/workbench @@ -202,6 +206,9 @@ jobs: # would-be skip into a hard failure. - name: Run the database-backed package suites run: | + set -a + . ./.env + set +a bun test $(grep -rl DATABASE_URL --include='*.test.ts' packages apps | grep -v apps/hub/test) env: E2E_REQUIRED: "1" From 8a5a92564b657a63776bb1562f2e61009ab87121 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Sat, 29 Aug 2026 10:57:56 -0700 Subject: [PATCH 71/75] Load root .env for walking-skeleton package suites --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d0835dca..07a378850 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -209,7 +209,7 @@ jobs: set -a . ./.env set +a - bun test $(grep -rl DATABASE_URL --include='*.test.ts' packages apps | grep -v apps/hub/test) + bun --env-file="${GITHUB_WORKSPACE}/.env" test $(grep -rl DATABASE_URL --include='*.test.ts' packages apps | grep -v apps/hub/test) env: E2E_REQUIRED: "1" DATABASE_URL: postgres://postgres:postgres@localhost:5432/workbench From d96895ccd70a7bf98adc013fb0f96bd934434a2b Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Sat, 29 Aug 2026 11:10:50 -0700 Subject: [PATCH 72/75] Read DATABASE_URL from .env in e2eDatabaseUrl --- scripts/e2e/harness.test.ts | 38 +++++++++++++++++++++++++ scripts/e2e/harness.ts | 56 ++++++++++++++++++++++++++++++++++++- 2 files changed, 93 insertions(+), 1 deletion(-) diff --git a/scripts/e2e/harness.test.ts b/scripts/e2e/harness.test.ts index cb7ccbc9e..5b4d14800 100644 --- a/scripts/e2e/harness.test.ts +++ b/scripts/e2e/harness.test.ts @@ -9,6 +9,7 @@ import { existsSync } from "node:fs"; import { createCleanupHarness, + parseEnvFileDatabaseUrl, runCleanups, type SpawnedApp, } from "./harness.ts"; @@ -65,3 +66,40 @@ describe("createCleanupHarness", () => { expect(cleanups).toHaveLength(0); }); }); + +describe("parseEnvFileDatabaseUrl", () => { + test("reads DATABASE_URL and ignores comments and blanks", () => { + expect( + parseEnvFileDatabaseUrl( + "# comment\n\nFOO=bar\nDATABASE_URL=postgres://localhost:5432/workbench\n", + ), + ).toBe("postgres://localhost:5432/workbench"); + }); + + test("strips surrounding quotes and trims", () => { + expect( + parseEnvFileDatabaseUrl( + ` DATABASE_URL="postgres://localhost:5432/workbench" \n`, + ), + ).toBe("postgres://localhost:5432/workbench"); + expect( + parseEnvFileDatabaseUrl( + `DATABASE_URL='postgres://localhost:5432/workbench'\n`, + ), + ).toBe("postgres://localhost:5432/workbench"); + }); + + test("ignores a commented DATABASE_URL and returns undefined when none is set", () => { + expect( + parseEnvFileDatabaseUrl("# DATABASE_URL=postgres://commented\nFOO=bar\n"), + ).toBeUndefined(); + }); + + test("last DATABASE_URL wins", () => { + expect( + parseEnvFileDatabaseUrl( + "DATABASE_URL=postgres://first/db\nDATABASE_URL=postgres://second/db\n", + ), + ).toBe("postgres://second/db"); + }); +}); diff --git a/scripts/e2e/harness.ts b/scripts/e2e/harness.ts index 3704c9ae7..a4d7f0caf 100644 --- a/scripts/e2e/harness.ts +++ b/scripts/e2e/harness.ts @@ -5,6 +5,7 @@ // real the suite fails and says which hop, it never fakes the result. import { afterAll } from "bun:test"; +import { readFileSync } from "node:fs"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -23,9 +24,17 @@ const SIDECAR_DIR = path.join(REPO_ROOT, "apps", "sidecar"); * database still runs the unit gates); in CI, E2E_REQUIRED=1 turns * that skip into a loud failure so the suite can never silently * vanish from the pipeline. + * + * `bun test` workers do not always inherit process.env.DATABASE_URL + * even when the shell sourced `.env`. Fall back to the same repo-root + * `.env` file `bun run` would load. */ export function e2eDatabaseUrl(): string | undefined { - const url = process.env["DATABASE_URL"]; + const fromProcess = process.env["DATABASE_URL"]; + const url = + fromProcess !== undefined && fromProcess !== "" + ? fromProcess + : databaseUrlFromRepoEnvFile(); if (url !== undefined && url !== "") return baseUrlToE2eUrl(url); if (process.env["E2E_REQUIRED"] === "1") { throw new Error( @@ -36,6 +45,51 @@ export function e2eDatabaseUrl(): string | undefined { return undefined; } +/** + * Pull DATABASE_URL from a dotenv-style file body. Ignores blanks and + * comments; trims; strips one layer of surrounding quotes. Last match + * wins. Does not expand interpolations. + */ +export function parseEnvFileDatabaseUrl(text: string): string | undefined { + let found: string | undefined; + for (const rawLine of text.split(/\r?\n/)) { + const line = rawLine.trim(); + if (line === "" || line.startsWith("#")) continue; + if (!line.startsWith("DATABASE_URL=")) continue; + let value = line.slice("DATABASE_URL=".length).trim(); + if (value.length >= 2) { + const start = value[0]; + const end = value[value.length - 1]; + if ((start === '"' && end === '"') || (start === "'" && end === "'")) { + value = value.slice(1, -1); + } + } + found = value; + } + if (found === undefined || found === "") return undefined; + return found; +} + +function databaseUrlFromRepoEnvFile(): string | undefined { + let text: string; + try { + text = readFileSync(path.join(REPO_ROOT, ".env"), "utf8"); + } catch (error) { + if (isEnoent(error)) return undefined; + throw error; + } + return parseEnvFileDatabaseUrl(text); +} + +function isEnoent(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + error.code === "ENOENT" + ); +} + /** * The suite tears its schema down and rebuilds it on every run, so it * must never run inside the developer's own database. It derives a From 1f92a69aef3d204f8a2bcba5844053149379b41d Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Sat, 29 Aug 2026 16:04:53 -0700 Subject: [PATCH 73/75] Add tests for relaunching a live assistant when Manus connects --- .../hub/src/connection-live-reconcile.test.ts | 46 ++++ packages/chat/test/platform-adapter.test.ts | 234 +++++++++++++++++- 2 files changed, 279 insertions(+), 1 deletion(-) create mode 100644 apps/hub/src/connection-live-reconcile.test.ts diff --git a/apps/hub/src/connection-live-reconcile.test.ts b/apps/hub/src/connection-live-reconcile.test.ts new file mode 100644 index 000000000..ef23ae213 --- /dev/null +++ b/apps/hub/src/connection-live-reconcile.test.ts @@ -0,0 +1,46 @@ +// The hub connect hook must relaunch a live assistant the moment a +// `feedsTools` connector (Manus) is stored — not wait for a new invite, +// and not persist-only. `createHub` is not booted here; this is the +// hook body `apps/hub/src/index.ts` fires from `settleServiceConnection`. +import { describe, expect, test } from "bun:test"; +import { CONNECTOR_REGISTRY } from "@workbench/connections/registry"; +import { reconcilePinnedToolPackagesAfterConnect } from "./connection-live-reconcile"; + +describe("reconcilePinnedToolPackagesAfterConnect", () => { + test("manus connect relaunches live assistants that pin @corbits/manus-tools", async () => { + const calls: { tenantId: string; packages: readonly string[] }[] = []; + const result = await reconcilePinnedToolPackagesAfterConnect( + { + reconcilePinnedToolPackages: async (tenantId, packageNames) => { + calls.push({ tenantId, packages: [...packageNames] }); + return { scanned: 1, relaunched: 1 }; + }, + }, + { tenantId: "ten_1", connectorId: "manus" }, + ); + + expect(CONNECTOR_REGISTRY["manus"]?.feedsTools).toEqual([ + "@corbits/manus-tools", + ]); + expect(result).toEqual({ scanned: 1, relaunched: 1 }); + expect(calls).toEqual([ + { tenantId: "ten_1", packages: ["@corbits/manus-tools"] }, + ]); + }); + + test("an inference-only connector does not relaunch for tool-package pins", async () => { + const calls: unknown[] = []; + const result = await reconcilePinnedToolPackagesAfterConnect( + { + reconcilePinnedToolPackages: async (...args) => { + calls.push(args); + return { scanned: 0, relaunched: 0 }; + }, + }, + { tenantId: "ten_1", connectorId: "anthropic" }, + ); + + expect(result).toBeUndefined(); + expect(calls).toEqual([]); + }); +}); diff --git a/packages/chat/test/platform-adapter.test.ts b/packages/chat/test/platform-adapter.test.ts index 62b08bf2e..480768214 100644 --- a/packages/chat/test/platform-adapter.test.ts +++ b/packages/chat/test/platform-adapter.test.ts @@ -73,6 +73,18 @@ mock.module("@intx/hub-api", () => ({ }, })); +const actualDb = await import("@intx/db"); + +type BuildCredentialDeliveryResult = Awaited< + ReturnType +>; + +let buildCredentialDeliveryResult: BuildCredentialDeliveryResult = { + ok: true, + delivery: undefined, +}; +const buildCredentialDeliveryCalls: unknown[] = []; + // `deployAtHead` (reached through `launchFoldedRun`/`launchInvite`) looks // up `listVisibleOfferings` once per launch to correct an Ollama // offering's adapter-registry key (CL-6586's `withOllamaAdapterKey`) -- @@ -80,9 +92,12 @@ mock.module("@intx/hub-api", () => ({ // minimal chainable fake `db` never implements. None of these fixtures // resolve against an Ollama offering, so an empty list is the correct // fake: nothing here should ever need its `provider` field corrected. -const actualDb = await import("@intx/db"); mock.module("@intx/db", () => ({ ...actualDb, + buildCredentialDelivery: async (...args: unknown[]) => { + buildCredentialDeliveryCalls.push(args[0]); + return buildCredentialDeliveryResult; + }, listVisibleOfferings: async () => [], })); @@ -521,6 +536,33 @@ function deployedDefinition( }; } +/** + * The credential bindings the rendered entry module default-exports — + * the snapshot `env.credentials.resolve` reads, not the launch body's + * own (optional) bindings. + */ +function deployedCredentialBindings( + trees: readonly Record[], +): unknown { + const tree = trees[trees.length - 1]; + if (tree === undefined) throw new Error("no source tree was ever rendered"); + const entry = tree[WORKFLOW_SOURCE_ENTRY_PATH]; + if (typeof entry !== "string") { + throw new Error("no workflow entry module in the rendered tree"); + } + const open = entry.indexOf("export default "); + const close = entry.lastIndexOf(";"); + if (open === -1 || close === -1) { + throw new Error( + `rendered entry module has no definition literal: ${entry}`, + ); + } + const definition = JSON.parse( + entry.slice(open + "export default ".length, close), + ) as { credentialBindings?: unknown }; + return definition.credentialBindings ?? []; +} + function createFakeAssetService( opts: { assetBlob?: Uint8Array; @@ -3328,3 +3370,193 @@ describe("createHubChatPlatform inference-source rotation reconciliation", () => ); }); }); + +// A live Myra launched at signup pins `@corbits/manus-tools` with no +// required binding. Connecting Manus later stores the credential but +// used to only `dispatchTurn` the existing run — the sidecar still +// resolved `manus` as not connected. Inference reconcile cannot see +// this: Manus is not an inference provider. The connect hook has to +// relaunch live runs whose pins include the connector's `feedsTools` +// packages so `deployAtHead` folds `pinnedPackageCredentialBindingsFor`. +describe("createHubChatPlatform pinned-tool-package connect reconciliation", () => { + const MANUS_PIN = { name: "@corbits/manus-tools", version: "*" }; + const MANUS_BINDING = { + package: "@corbits/manus-tools", + handle: "manus", + provider: "manus", + locator: "tenant" as const, + }; + const CATALOG_SOURCES = { + sources: [ + { + id: "off_1", + provider: "anthropic", + baseURL: "https://inference.invalid", + apiKey: "sk-ant-same", + model: "claude-sonnet-5", + }, + ], + defaultSource: "off_1", + }; + + function createManusPinFixture(opts: { + toolPackagePins: { name: string; version: string }[]; + }) { + resolveDefinitionSourcesResult = { + ok: true, + ...CATALOG_SOURCES, + }; + buildCredentialDeliveryCalls.length = 0; + buildCredentialDeliveryResult = { + ok: true, + delivery: { + bindings: [ + { + handle: "manus", + credentialId: "cred_manus_1", + consumer: "tool:@corbits/manus-tools", + }, + ], + materials: [ + { + credentialId: "cred_manus_1", + providerKey: "manus", + origin: "https://api.manus.ai", + secret: "n/a", + }, + ], + }, + }; + const foldedBody = { + systemPrompt: "be helpful", + toolPackagePins: opts.toolPackagePins, + grantRequirements: [], + credentialBindings: [], + model: null, + }; + const db = createFakeDb({ + assetRow: { + tenantId: "ten_1", + creatorPrincipalId: "prin_creator", + name: "workbench-1", + displayName: null, + }, + definitionId: "wfd_unused", + workflowRunRow: { + id: "run_live", + address: "run_live@ten1.workbench.test", + principalId: "prin_room1", + definitionId: "wfd_run_clone", + status: "running", + }, + workflowDefinitionRow: { + id: "wfd_run_clone", + tenantId: "ten_1", + status: "deployed", + assetId: "asst_myra", + name: "myra", + origin: "run", + }, + workflowDefinitionRows: [ + { + id: "wfd_run_clone", + tenantId: "ten_1", + status: "deployed", + name: "myra", + assetId: "asst_myra", + origin: "run", + }, + { + id: "wfd_myra_authored", + tenantId: "ten_1", + status: "deployed", + name: "myra", + assetId: "asst_myra", + origin: "authored", + }, + ], + workbenchLaunchRow: { + tenantId: "ten_1", + instanceId: "run_live", + currentRunId: "run_live", + foldedBody, + sourcesDigest: inferenceSourcesDigest(CATALOG_SOURCES), + }, + wireProjectionsByDefinitionId: { + wfd_run_clone: inertProjection({ + id: "wfd_run_clone", + systemPrompt: foldedBody.systemPrompt, + model: null, + toolPackagePins: opts.toolPackagePins, + }), + wfd_myra_authored: inertProjection({ + id: "wfd_myra_authored", + systemPrompt: foldedBody.systemPrompt, + model: null, + toolPackagePins: opts.toolPackagePins, + }), + }, + }); + const assetService = createFakeAssetService(); + const platform = createHubChatPlatform({ + toolGrantsForPins: () => [], + db: db as never, + sessionService: createFakeSessionService(), + assetService, + sidecarRouter: createFakeSidecarRouter({ + routableAddresses: ["run_live@ten1.workbench.test"], + }), + eventCollectors: createFakeEventCollectors(), + credentialCipher: {} as never, + pinnedPackageCredentialBindingsFor: async () => [MANUS_BINDING], + }); + return { db, platform, assetService }; + } + + function repointedLaunch(db: ReturnType) { + return db.updated.find((row) => row.table === workbenchLaunch)?.values as + { currentRunId: string } | undefined; + } + + test("connecting manus after a live launch relaunches and folds the manus CredentialBinding", async () => { + const { db, platform, assetService } = createManusPinFixture({ + toolPackagePins: [MANUS_PIN], + }); + + await platform.ensureAwake("run_live@ten1.workbench.test"); + expect(repointedLaunch(db)).toBeUndefined(); + expect(assetService.populatedTrees).toHaveLength(0); + + const swept = await platform.reconcilePinnedToolPackages("ten_1", [ + "@corbits/manus-tools", + ]); + + // Persist-only (stamp a pin/binding onto the launch row and leave + // `currentRunId` as `run_live`) is the bug: the sidecar keeps the + // snapshot that cannot `resolve("manus")`. A passing result must + // mint a fresh run and fold the binding into the deployed entry. + expect(swept).toEqual({ scanned: 1, relaunched: 1 }); + expect(repointedLaunch(db)?.currentRunId).not.toBe("run_live"); + expect(deployedCredentialBindings(assetService.populatedTrees)).toEqual([ + MANUS_BINDING, + ]); + expect(buildCredentialDeliveryCalls[0]).toMatchObject({ + tenantId: "ten_1", + bindings: [MANUS_BINDING], + }); + }); + + test("a live run that does not pin the connected package is left alone", async () => { + const { db, platform, assetService } = createManusPinFixture({ + toolPackagePins: [], + }); + + const swept = await platform.reconcilePinnedToolPackages("ten_1", [ + "@corbits/manus-tools", + ]); + + expect(swept).toEqual({ scanned: 1, relaunched: 0 }); + expect(repointedLaunch(db)).toBeUndefined(); + expect(assetService.populatedTrees).toHaveLength(0); + }); +}); From 0ec1033b6a65ef0e6a6c86963fee1abaf77b4076 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Sat, 29 Aug 2026 16:05:06 -0700 Subject: [PATCH 74/75] Relaunch live assistants when a pinned tool-package credential connects --- apps/hub/src/connection-live-reconcile.ts | 30 ++++++++++++++ apps/hub/src/index.ts | 36 ++++++++++++----- packages/chat/src/agent-binding.ts | 4 +- packages/chat/src/platform-adapter.ts | 49 +++++++++++++++++++++++ 4 files changed, 108 insertions(+), 11 deletions(-) create mode 100644 apps/hub/src/connection-live-reconcile.ts diff --git a/apps/hub/src/connection-live-reconcile.ts b/apps/hub/src/connection-live-reconcile.ts new file mode 100644 index 000000000..1e24d7ff7 --- /dev/null +++ b/apps/hub/src/connection-live-reconcile.ts @@ -0,0 +1,30 @@ +// After a connector's credential lands, live assistants that already +// pin that connector's `feedsTools` packages still run the snapshot +// deployed at launch. Bindings for those packages +// (`pinnedPackageCredentialBindingsFor`) fold only at deploy, so a Myra +// launched at signup before Manus was pasted cannot `resolve("manus")` +// until this pass relaunches it. Persist-only (stamp the pin onto the +// launch row and leave the run) is the bug: the sidecar keeps the old +// snapshot. +import { CONNECTOR_REGISTRY } from "@workbench/connections/registry"; + +export type PinnedToolPackageReconcile = { + reconcilePinnedToolPackages( + tenantId: string, + packageNames: readonly string[], + ): Promise<{ scanned: number; relaunched: number }>; +}; + +/** + * Relaunches live participants in `tenantId` whose pins include this + * connector's `feedsTools`. Returns `undefined` when the connector + * feeds no tool packages (inference-only, webhook, …). + */ +export async function reconcilePinnedToolPackagesAfterConnect( + platform: PinnedToolPackageReconcile, + info: { readonly tenantId: string; readonly connectorId: string }, +): Promise<{ scanned: number; relaunched: number } | undefined> { + const feedsTools = CONNECTOR_REGISTRY[info.connectorId]?.feedsTools ?? []; + if (feedsTools.length === 0) return undefined; + return platform.reconcilePinnedToolPackages(info.tenantId, feedsTools); +} diff --git a/apps/hub/src/index.ts b/apps/hub/src/index.ts index 9b38e449a..c277a9f73 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -358,9 +358,9 @@ import { createBootAssetWiring, REGISTRIES } from "./asset-service-factory"; import { createRoutineScheduler } from "./routine-scheduler"; import { createToolGrantsForPins } from "./tool-grants"; import { createMcpCredentialBindingsFor } from "./mcp-credential-bindings"; +import { reconcilePinnedToolPackagesAfterConnect } from "./connection-live-reconcile"; import { createPinnedPackageCredentialBindingsFor } from "./pinned-package-credential-bindings"; import { shutdownHub } from "./shutdown"; -import { createPinnedPackageCredentialBindingsFor } from "./pinned-package-credential-bindings"; // Host policy constants, not configuration. const MAX_TARBALL_BYTES = 10 * 1024 * 1024; @@ -2026,9 +2026,13 @@ export async function createHub(config: HubConfig) { // An inference provider's credential landing also re-checks every // live participant's deployed inference chain (CL-6687): a rotated // key only ever reaches an agent at deploy time, so the relaunch has - // to be kicked here, not left for the next message. Not awaited — a - // relaunch is a sidecar deploy round-trip, and the connect response - // must not wait on it. + // to be kicked here, not left for the next message. A tool-package + // connector (`feedsTools`, e.g. Manus) is the same shape for a + // different payload: `pinnedPackageCredentialBindingsFor` only folds + // at deploy, so a live Myra launched at signup before the key was + // pasted stays on a snapshot that cannot `resolve("manus")` until + // this pass relaunches it. Not awaited — a relaunch is a sidecar + // deploy round-trip, and the connect response must not wait on it. const settleServiceConnection: ServiceConnectedHook = async (info) => { await settleConnectedService( { @@ -2045,15 +2049,27 @@ export async function createHub(config: HubConfig) { displayName: info.displayName, }, ); - if (!isInferenceProvider(info.connectorId)) return; - void chatPlatform - .reconcileInferenceSources(info.tenantId) - .then(({ scanned, relaunched }) => { - log.info`inference credential ${info.connectorId} changed on tenant ${info.tenantId}: re-checked ${String(scanned)} live agents, relaunched ${String(relaunched)}`; + if (isInferenceProvider(info.connectorId)) { + void chatPlatform + .reconcileInferenceSources(info.tenantId) + .then(({ scanned, relaunched }) => { + log.info`inference credential ${info.connectorId} changed on tenant ${info.tenantId}: re-checked ${String(scanned)} live agents, relaunched ${String(relaunched)}`; + }) + .catch((cause: unknown) => { + reportError(cause, { + operation: "connections.reconcile-inference-sources", + tenantId: info.tenantId, + }); + }); + } + void reconcilePinnedToolPackagesAfterConnect(chatPlatform, info) + .then((result) => { + if (result === undefined) return; + log.info`tool-package connector ${info.connectorId} changed on tenant ${info.tenantId}: re-checked ${String(result.scanned)} live agents, relaunched ${String(result.relaunched)}`; }) .catch((cause: unknown) => { reportError(cause, { - operation: "connections.reconcile-inference-sources", + operation: "connections.reconcile-pinned-tool-packages", tenantId: info.tenantId, }); }); diff --git a/packages/chat/src/agent-binding.ts b/packages/chat/src/agent-binding.ts index c1f49aa29..6c109ff42 100644 --- a/packages/chat/src/agent-binding.ts +++ b/packages/chat/src/agent-binding.ts @@ -324,7 +324,9 @@ export async function recordSourcesDigest( * Every participant a tenant has launched, with its live run, for the * pass that re-checks each one's inference chain after a provider * credential changes (`platform-adapter.ts`'s - * `reconcileInferenceSources`). Bounded like `listLaunchesBeyondWake`. + * `reconcileInferenceSources`) and the pass that relaunches agents + * whose pins include a just-connected tool-package connector + * (`reconcilePinnedToolPackages`). Bounded like `listLaunchesBeyondWake`. */ export async function listLaunchesForTenant( db: DB["db"], diff --git a/packages/chat/src/platform-adapter.ts b/packages/chat/src/platform-adapter.ts index 5398d1b97..8f15235bc 100644 --- a/packages/chat/src/platform-adapter.ts +++ b/packages/chat/src/platform-adapter.ts @@ -204,6 +204,20 @@ export type HubChatPlatform = ChatPlatform & { reconcileInferenceSources( tenantId: string, ): Promise<{ scanned: number; relaunched: number }>; + /** + * Relaunches live participants in `tenantId` whose launch pins include + * any of `packageNames` — a tool-package connector's `feedsTools` the + * moment its credential is stored. Bindings for those packages are + * folded only at deploy time (`pinnedPackageCredentialBindingsFor`), + * so a Myra launched at signup before Manus was pasted stays on a + * snapshot that cannot `resolve("manus")` until this pass mints a + * fresh run. Best-effort per participant, same posture as + * `reconcileInferenceSources`. + */ + reconcilePinnedToolPackages( + tenantId: string, + packageNames: readonly string[], + ): Promise<{ scanned: number; relaunched: number }>; }; /** @@ -761,6 +775,40 @@ export function createHubChatPlatform( return { scanned: participants.length, relaunched }; } + async function reconcilePinnedToolPackages( + tenantId: string, + packageNames: readonly string[], + ): Promise<{ scanned: number; relaunched: number }> { + const wanted = new Set(packageNames); + const participants = await listLaunchesForTenant( + deps.db, + tenantId, + RECONCILE_SOURCES_LIMIT, + ); + let relaunched = 0; + for (const live of participants) { + const pinsWanted = live.binding.foldedBody.toolPackagePins.some((pin) => + wanted.has(pin.name), + ); + if (!pinsWanted) continue; + try { + if (await isBeyondWake(deps.db, live.run)) continue; + if (live.run.address === null || !isRoutable(live.run.address)) { + continue; + } + wakeLogger.info`relaunching ${live.binding.roomAddress}: run ${live.run.id} pins a just-connected tool package; minting a fresh run so deploy folds the new binding`; + sourcesCheckedAt.delete(live.binding.stableId); + await relaunchTerminalRun(live); + relaunched++; + } catch (cause: unknown) { + wakeLogger.error`pinned-tool-package reconcile for ${live.binding.roomAddress} (run ${live.run.id}) failed, leaving it as-is: ${ + cause instanceof Error ? cause.message : String(cause) + }`; + } + } + return { scanned: participants.length, relaunched }; + } + /** * The live run mail must actually be delivered to for a stable * participant id — not the room's own address, once anything has been @@ -1279,5 +1327,6 @@ export function createHubChatPlatform( recordActivity: (address: string) => lifecycle?.recordActivity(address), sweepTerminalRuns, reconcileInferenceSources, + reconcilePinnedToolPackages, }); } From 12bb75f054675242dd90d4c09d88000a3a7d6651 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Sat, 29 Aug 2026 16:16:34 -0700 Subject: [PATCH 75/75] Format launch.ts after Manus history merge --- packages/folded-runs/src/launch.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/folded-runs/src/launch.ts b/packages/folded-runs/src/launch.ts index 98d058a75..ccc4d10fa 100644 --- a/packages/folded-runs/src/launch.ts +++ b/packages/folded-runs/src/launch.ts @@ -285,7 +285,6 @@ export async function resolveLaunchSources( deps: Pick, params: ResolveLaunchSourcesParams, ): Promise { - const sourcesOverride = parseSourcesOverride(params.sources); const resolveAgainst = (model: string | null) => resolveDefinitionSources({