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/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 ad714a3b7..c277a9f73 100644 --- a/apps/hub/src/index.ts +++ b/apps/hub/src/index.ts @@ -358,6 +358,8 @@ 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"; // Host policy constants, not configuration. @@ -717,6 +719,20 @@ export async function createHub(config: HubConfig) { ); // See `./mcp-credential-bindings.ts`'s own doc. const mcpCredentialBindingsFor = createMcpCredentialBindingsFor(db); + // 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(isConnectorConnected); const sidecarRouter = createSidecarRouter({ hubPublicKey, authenticateSidecar: createSidecarTokenAuthenticator({ db }), @@ -1281,6 +1297,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 @@ -1987,6 +2004,7 @@ export async function createHub(config: HubConfig) { eventCollectors, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, cryptoProviderCache: foldedRunCryptoProviders, launchMode: AGENT_SECTION_MODE, persistLaunch: workbenchLaunchPersistExtra, @@ -2008,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( { @@ -2027,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, }); }); @@ -2458,18 +2492,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), }), ); @@ -2537,6 +2562,7 @@ export async function createHub(config: HubConfig) { hubPublicKey, toolGrantsForPins, mcpCredentialBindingsFor, + pinnedPackageCredentialBindingsFor, }; // Every genuine top-level deployment run, folded runs (workbench hosts, @@ -2727,6 +2753,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..96a3c59ba --- /dev/null +++ b/apps/hub/src/pinned-package-credential-bindings.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from "bun:test"; +import { + bindingsForConnectedPins, + createPinnedPackageCredentialBindingsFor, +} 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([]); + }); +}); + +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([]); + }); +}); 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..f3893abcc --- /dev/null +++ b/apps/hub/src/pinned-package-credential-bindings.ts @@ -0,0 +1,61 @@ +// 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 (`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 { CONNECTOR_REGISTRY } from "@workbench/connections/registry"; + +export type IsConnectorConnected = ( + tenantId: string, + connectorId: string, +) => Promise; + +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( + isConnectorConnected: IsConnectorConnected, +): PinnedPackageCredentialBindingsFor { + return async (tenantId, pins) => { + 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); + }; +} 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/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/docs/credential-wiring.md b/docs/credential-wiring.md index ab801e887..d3e166b69 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,30 @@ 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. +- **`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 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 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/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 7338e6198..8f15235bc 100644 --- a/packages/chat/src/platform-adapter.ts +++ b/packages/chat/src/platform-adapter.ts @@ -81,6 +81,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 @@ -202,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 }>; }; /** @@ -225,6 +241,12 @@ export function createHubChatPlatform( ...(deps.mcpCredentialBindingsFor !== undefined ? { mcpCredentialBindingsFor: deps.mcpCredentialBindingsFor } : {}), + ...(deps.pinnedPackageCredentialBindingsFor !== undefined + ? { + pinnedPackageCredentialBindingsFor: + deps.pinnedPackageCredentialBindingsFor, + } + : {}), }; const cryptoProviders = createCryptoProviderCache(); @@ -753,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 @@ -1271,5 +1327,6 @@ export function createHubChatPlatform( recordActivity: (address: string) => lifecycle?.recordActivity(address), sweepTerminalRuns, reconcileInferenceSources, + reconcilePinnedToolPackages, }); } 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); + }); +}); 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.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/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.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/probes.ts b/packages/connections/src/probes.ts index cc4b401d3..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 @@ -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.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/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/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/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/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/folded-runs/src/index.ts b/packages/folded-runs/src/index.ts index f249d0335..9fb8471d3 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 2fdfe0d3d..ccc4d10fa 100644 --- a/packages/folded-runs/src/launch.ts +++ b/packages/folded-runs/src/launch.ts @@ -401,6 +401,7 @@ export async function deployAtHead( | "assetService" | "toolGrantsForPins" | "mcpCredentialBindingsFor" + | "pinnedPackageCredentialBindingsFor" >, params: ResolveLaunchSourcesParams & { instanceId: string; @@ -465,9 +466,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 @@ -532,9 +553,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 = { 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. 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/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 +``` diff --git a/packages/manus-tools/package.json b/packages/manus-tools/package.json new file mode 100644 index 000000000..7da533d97 --- /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.11", + "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.test.ts b/packages/manus-tools/src/client.test.ts new file mode 100644 index 000000000..992018ac7 --- /dev/null +++ b/packages/manus-tools/src/client.test.ts @@ -0,0 +1,714 @@ +import { expect, test } from "bun:test"; + +import { + createSlideDeck, + createTask, + DEFAULT_SLIDE_MAX_POLLS, + DEFAULT_SLIDE_POLL_INTERVAL_MS, + extractOutputFiles, + getTaskDetail, + 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 } = { + 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: [{ 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"); +}); + +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, + }, + agent_profile: "manus-1.6-lite", + }); +}); + +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: "", + 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("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( + 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/); +}); + +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: [ + { + type: "text", + text: "Create a slide presentation in pptx format. Produce a presentation deck, not a document. Topic and requirements:\n\nOnboarding", + }, + ], + }, + agent_profile: "manus-1.6-lite", + }); + 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 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) => { + 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, + ); +}); + +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 { + agent_profile?: string; + message: { + enable_skills?: string[]; + force_skills?: string[]; + }; + }; + 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 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 : ""; + 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" }] }, + 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 }, + { 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"); +}); + +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 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) => { + 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); +}); diff --git a/packages/manus-tools/src/client.ts b/packages/manus-tools/src/client.ts new file mode 100644 index 000000000..900a300e3 --- /dev/null +++ b/packages/manus-tools/src/client.ts @@ -0,0 +1,574 @@ +// 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 | string", + "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; + +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", + "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); +} + +/** 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; + 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; + 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: buildTaskMessage(params.content, params), + }; + 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; + } + body["agent_profile"] = params.agent_profile ?? DEFAULT_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", + 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 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; + 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; + // 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) return next; + } + return undefined; +} + +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"]); + +/** 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; + +export const SLIDE_DECK_AGENT_PROFILE = DEFAULT_AGENT_PROFILE; + +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 isManusTaskNotFoundError(error: unknown): boolean { + return ( + error instanceof Error && + error.message.toLowerCase().includes("manus request failed: not_found") + ); +} + +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 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, + 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 { pollIntervalMs, maxPolls, signal, ...taskParams } = params; + 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; + let messages: ListMessagesResponse | undefined; + for (let i = 0; i < polls; i += 1) { + throwIfSlideWaitAborted(signal); + 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") { + 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})` : ""), + ); + } + 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: { + 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..5c570ae8d --- /dev/null +++ b/packages/manus-tools/src/index.ts @@ -0,0 +1,40 @@ +export { + CreateTaskResponse, + ListMessagesResponse, + TaskDetailResponse, + buildTaskMessage, + createSlideDeck, + createTask, + extractOutputFiles, + getTaskDetail, + latestAgentStatus, + listTaskMessages, + manusRequest, + 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"; +export type { + CreateSlideDeckParams, + CreateTaskParams, + ListMessagesParams, + ManusClientConfig, + OutputFile, + TaskAttachment, + TaskDetail, + TaskEvent, + TaskMessageBody, + TaskMessageSkillFields, + TaskTextContentPart, +} 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/manifest.test.ts b/packages/manus-tools/src/manifest.test.ts new file mode 100644 index 000000000..55d82b5c9 --- /dev/null +++ b/packages/manus-tools/src/manifest.test.ts @@ -0,0 +1,21 @@ +// 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" }]); +}); diff --git a/packages/manus-tools/src/tool.test.ts b/packages/manus-tools/src/tool.test.ts new file mode 100644 index 000000000..ec66e6e69 --- /dev/null +++ b/packages/manus-tools/src/tool.test.ts @@ -0,0 +1,524 @@ +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.pptx", + url: "https://files.manus.ai/onboarding.pptx", + id: "file_deck_1", + content_type: + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + }, + ], + }, + }, + ], +}; + +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("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", + ); + 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( + 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"); + const body = JSON.parse(typeof init?.body === "string" ? init.body : ""); + 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(); + expect(body.agent_profile).toBe("manus-1.6-lite"); + 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")) { + 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 }); + }) 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.pptx", + url: "https://files.manus.ai/onboarding.pptx", + id: "file_deck_1", + type: "slides", + content_type: + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + }, + ]); + 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("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("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 () => + 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; + } +}); + +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(); + 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 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, + }); + }) 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" }] }, + agent_profile: "manus-1.6-lite", + }); + + 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" }, + agent_profile: "manus-1.6-lite", + }); + } 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; + } +}); diff --git a/packages/manus-tools/src/tool.ts b/packages/manus-tools/src/tool.ts new file mode 100644 index 000000000..68730af10 --- /dev/null +++ b/packages/manus-tools/src/tool.ts @@ -0,0 +1,845 @@ +// 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 { + buildTaskMessage, + createSlideDeck, + createTask, + getTaskDetail, + 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; + readonly items?: { readonly type: string }; +}; + +type EndpointSpec = { + readonly name: string; + readonly method: ManusHttpMethod; + readonly path: string; + readonly description: string; + readonly required: readonly string[]; + readonly properties: Readonly>; + readonly approval?: "ask"; +}; + +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, +}); +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[] = [ + { + name: "task_create", + method: "POST", + path: "/v2/task.create", + description: + "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."), + 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( + "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.", + ), + }, + }, + { + 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.") }, + approval: "ask", + }, + { + name: "task_send_msg", + method: "POST", + path: "/v2/task.sendMessage", + 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 ContentPart text).", + ), + agent_profile: STRING("Optional agent profile override."), + ...MESSAGE_SKILL_PROPERTIES, + }, + }, + { + 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: pptx or html."), + }, + }, + { + 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.") }, + approval: "ask", + }, + { + name: "webhook_create", + method: "POST", + path: "/v2/webhook.create", + description: "Creates a Manus webhook.", + required: ["url"], + properties: { url: STRING("Webhook callback URL.") }, + approval: "ask", + }, + { + name: "webhook_list", + method: "GET", + path: "/v2/webhook.list", + description: "Lists Manus webhooks.", + required: [], + properties: {}, + approval: "ask", + }, + { + name: "webhook_delete", + method: "POST", + path: "/v2/webhook.delete", + description: "Deletes a Manus webhook.", + required: ["webhook_id"], + properties: { webhook_id: STRING("Webhook id.") }, + approval: "ask", + }, + { + name: "webhook_pubkey", + method: "GET", + path: "/v2/webhook.publicKey", + description: "Returns the Manus webhook signing public key.", + required: [], + properties: {}, + approval: "ask", + }, + { + 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."), + }, + approval: "ask", + }, + { + 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."), + }, + approval: "ask", + }, + { + 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_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"); + 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: buildTaskMessage(content, messageSkillFields(call)), + }; + 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; + enable_skills?: readonly string[]; + force_skills?: readonly string[]; + connectors?: readonly string[]; + task_references?: readonly string[]; + structured_output_schema?: Readonly>; +} { + const fields: { + title?: string; + project_id?: string; + locale?: string; + interactive_mode?: boolean; + 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; + 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; + 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; +} + +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, + signal: AbortSignal, +): 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 } : {}), + signal, + }); + 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) => + spec.approval === "ask" + ? { name: spec.name, approval: "ask" as const } + : { 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, signal); + } + 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/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/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..13b474fc6 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" }, @@ -50,6 +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.11" }, ]; /** diff --git a/workflows/assistant/test/definition.test.ts b/workflows/assistant/test/definition.test.ts index a02fbb95d..5be5b32ab 100644 --- a/workflows/assistant/test/definition.test.ts +++ b/workflows/assistant/test/definition.test.ts @@ -125,6 +125,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 +150,14 @@ 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 pins manus-tools and does not require a Manus credential binding", () => { + const definition = buildAssistantWorkflow(INPUT); + 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", () => { const definition = buildAssistantWorkflow(INPUT); const revived: unknown = JSON.parse(serializeAssistantWorkflow(definition));