diff --git a/services/platform/backend/core/sandbox/tool_names.test.ts b/services/platform/backend/core/sandbox/tool_names.test.ts index 00e2379e2d..15f410acd1 100644 --- a/services/platform/backend/core/sandbox/tool_names.test.ts +++ b/services/platform/backend/core/sandbox/tool_names.test.ts @@ -5,6 +5,7 @@ import { IMAGE_GENERATION_TOOL, imageGenerationGuidance, KNOWLEDGE_READ_TOOLS, + KNOWLEDGE_TOOLS_GUIDANCE, normalizeToolGrants, PROJECT_AGENT_ONLY_TOOLS, readTurnOpRef, @@ -98,6 +99,18 @@ describe('the catalog', () => { }); describe('grantedToolsGuidance', () => { + it('names discovery as a separate MCP tool, never a grantable operation', () => { + for (const guidance of [ + KNOWLEDGE_TOOLS_GUIDANCE, + grantedToolsGuidance(['task_get']), + imageGenerationGuidance('/agent/output/task_1'), + ]) { + expect(guidance).toContain('separate workspace_status MCP tool with {}'); + } + expect(normalizeToolGrants(['workspace_status', 'task_get'])).toEqual([ + 'task_get', + ]); + }); it('is undefined when nothing beyond the baseline is granted', () => { expect(grantedToolsGuidance([])).toBeUndefined(); }); diff --git a/services/platform/backend/core/sandbox/tool_names.ts b/services/platform/backend/core/sandbox/tool_names.ts index 52015d2d82..dd48d3a9f3 100644 --- a/services/platform/backend/core/sandbox/tool_names.ts +++ b/services/platform/backend/core/sandbox/tool_names.ts @@ -44,7 +44,8 @@ export const KNOWLEDGE_TOOLS_GUIDANCE = '"workspace_tool" MCP tool: rag_search {query} finds the most relevant ' + "passages, rag_fetch {ref} reads one hit's full source (a document file " + 'id or a crawled page URL). Use them when you need organization facts ' + - 'that are not in your staged files; call workspace_status to see ' + + 'that are not in your staged files; call the separate workspace_status ' + + 'MCP tool with {} to see ' + 'everything granted.'; /** @@ -71,7 +72,8 @@ export function imageGenerationGuidance(outputDir: string): string { "organization's image model and saves them into " + `${outputDir}/ — name a file there (no subfolders: only the box's top ` + 'level is delivered) or a path under /agent/workspace/ — answering ' + - 'with the saved paths; call workspace_status for the argument details. ' + + 'with the saved paths; call the separate workspace_status MCP tool ' + + 'with {} for the argument details. ' + 'Every image is billed to the organization and counts against this ' + `turn's spend allowance, at most ${SANDBOX_TURN_MAX_GENERATED_IMAGES} ` + 'images a turn — create what the task needs, not variations for their ' + @@ -178,8 +180,8 @@ export function grantedToolsGuidance( 'This agent is additionally granted these workspace tools (call them ' + 'through the "workspace_tool" MCP tool as {tool, args}): ' + tools.join(', ') + - '. Call workspace_status once for their argument shapes before first ' + - 'use.' + + '. Call the separate workspace_status MCP tool with {} for their ' + + 'argument shapes.' + (hasWrite ? ' The write tools change real organization data (tasks, documents) ' + 'with no further approval — act deliberately and prefer the ' + diff --git a/services/platform/backend/domains/sandbox/dispatch-routes.test.ts b/services/platform/backend/domains/sandbox/dispatch-routes.test.ts index a0c8214384..76b859500d 100644 --- a/services/platform/backend/domains/sandbox/dispatch-routes.test.ts +++ b/services/platform/backend/domains/sandbox/dispatch-routes.test.ts @@ -137,6 +137,33 @@ describe('POST /api/tools/execute — the turn a token serves', () => { dispatchWorkspaceToolImpl.mockResolvedValue({ status: 'ok', output: {} }); }); + it('keeps discovery out of domain grants without disabling a granted task call [SBX-R6]', async () => { + getSessionTokenByHash.mockResolvedValue({ + ...TOKEN_ROW, + scope: { toolGrants: ['task_get'] }, + }); + const refused = await post( + JSON.stringify({ tool: 'workspace_status', args: {} }), + ); + expect(await refused.json()).toMatchObject({ + status: 'unavailable', + blockers: [{ code: 'not_granted' }], + }); + expect(dispatchWorkspaceToolImpl).not.toHaveBeenCalled(); + + const granted = await post( + JSON.stringify({ tool: 'task_get', args: { taskId: 'task_1' } }), + ); + expect(await granted.json()).toEqual({ status: 'ok', output: {} }); + expect(dispatchWorkspaceToolImpl).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.objectContaining({ + tool: 'task_get', + callArgs: { taskId: 'task_1' }, + }), + ); + }); + it('hands the token scope’s turnOp to the dispatch, never the body’s [SBX-R5]', async () => { getSessionTokenByHash.mockResolvedValue({ ...TOKEN_ROW, diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 98c707e820..ae7e663218 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -326,7 +326,7 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | An imported title or description is cut on a grapheme boundary (`Intl.Segmenter`): a ZWJ family, a flag, a skin-tone modifier, a keycap or a letter with its combining mark is kept whole or dropped whole, never split, and one grapheme longer than the cap leaves only the "…". The workflow natives `task.upsert` and `task.upsert_issues` answer a blank title with the shared empty-title sentence before any write (a batch names the item, `issues.:`), and return the title the task carries — cut on a create, the stored one after a source-snapshot reconcile — never the title sent; their connector mocks cut alike and refuse with the same sentence, which a test run reports under `MOCK_BODY_FAILED` where a live run answers `INPUT_INVALID`, and the action schema no longer pre-empts `''` with a generic `minLength`. The GitHub and GlitchTip importers seed a task's description with the domain's own cut, never a local 50,000-unit slice. The refusal guard also reads every `AutomationError` an automations-domain function reached from a task door throws, and every `AutomationError`, `ProjectError`, `RestRefusal` and `FolderError` a door's own file builds: `AUTOMATION_PROJECT_FORBIDDEN` no longer repeats the `workflowSlug` sent and is one shared sentence at both throw sites, and the REST task door's `AUTOMATION_NOT_DEPLOYED` no longer repeats the slug either. The board names the caps a save breaks: a description draft over 20,000 code units names the cap under the field — a sentence that stays the same while the draft stays over, so a screen reader hears it once — shows a `used / max` counter outside that live region — the trimmed length a save keeps, grouped in the reader's language, and describing the field so it is read on focus — and holds **Save** and **Create task**; `TASK_TITLE_INVALID` and `TASK_DESCRIPTION_INVALID` toast the cap in the reader's language instead of the generic error; the inline title takes at most 200; the label pickers use the shared label caps; the EN/DE/FR task pages state the two caps the domain holds. REST `data.issues` names a string cap in UTF-16 code units, as the OpenAPI and Markdown references' example does | 🔶 unit + Postgres | `backend/core/tasks/helpers.test.ts`, `lib/connectors/natives/platform-tasks.test.ts` (the mocks run in the node-vm runner against the domain helpers), `backend/domains/tasks/external-ref.test.ts`, `backend/domains/connectors/task-store.upsert.test.ts`, `backend/domains/tasks/errors.test.ts`, `backend/domains/automations/store.begin-run.test.ts`, `backend/rest/shared.test.ts`, `backend/rest/v1-tasks.test.ts`, `lib/connectors/dispatcher.test.ts`, `lib/connectors/issue-import.test.ts`, `lib/engine/core/validate/schema.test.ts`, `app/features/tasks/components/editable-description.test.tsx`, `app/features/tasks/components/task-modal.limits.test.tsx`, `packages/ui/src/components/forms/textarea.test.tsx`, `backend/core/tasks/limits_docs.test.ts`, `app/features/tasks/lib/task-limit-refusal.test.ts`, `backend/integration-check.ts` (`checkTaskExternalIssueSync`: a source reconcile and a batch create answer the stored title); how the over-cap line reads and wraps stays manual (`TASK-B11`) | | [tasks](../suites/tasks.md) | Native settled-review repair is a separate tagged `resumeFrom` branch: strict old-boundary refusal, stored decision readback, exact source and unchanged human intent, current delegation authority on new admissions and same-manager replay, original issuer provenance, concurrent dedupe, ordinary next-review completion, busy/dependency/hourly limits, and rollback of run, queue and status if receipt persistence fails. A newer human or pending review hides the historical native decision. No UI or model judgment is inferred. | ✅ unit + real PostgreSQL + native HTTP | `backend/core/node_only/sandbox/workspace_tools_bridge.repair.test.ts`, `backend/domains/tasks/review-decision.test.ts`, `backend/domains/tasks/review-repair.integration.ts` (through `checkAgentTaskReviews`), existing `checkDelegatedAgentStartTool` question controls | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | An agent's task reads cover a whole queue: `task_find` answers pages of at most 50 with `isDone` and a signed `continueCursor` bound to its order, filters and scope (another filter, order, project or organization, and a malformed, cut or edited cursor, answer `invalid_args`, never a first page), `totalFound` only when one page holds every match, and walks 260 tasks tied on rank and creation millisecond each once in the database's own `(status, rank, id)` or `(created_at, id)` order; in created order a pass lists a task at most once while the board moves, in board order a task moved past the cursor is listed again and one moved behind it is skipped. `task_get` names subtasks, blockers and comments by id (never another project's task), pages comments past the newest 50 with `commentCursor` and project-agent runs newest-created first with `runCursor`, reads a queued or running run as `live`, a finished one with `settledAt` and `failureCode`, and explicit `retryPending` using the task card's shared retry calculation (armed versus unarmed, retired, spent, superseded, historical and deleted-agent failures; an absent field on an older reader stays unknown), an automation run's `waitingFor` `ask`/`approval` and a `pendingReview`, with a 500-character feedback excerpt and no transcript, error text, result or workspace handle; a failed run read answers `error`, never an idle task. The routine-question protocol's read half: a worker's agent-authored question starts nothing (its @mention is inert), the manager's answer reads back as its comment, `done` stays refused and the review pending, and a pass checkpoint saved in a comment is found past the newest 50 by a later run, whose cursor resumes the pass so both legs list every task exactly once | ✅ unit + real Postgres | `backend/core/node_only/sandbox/workspace_tools_bridge.task_reads.test.ts`, `backend/domains/tasks/service.agent-list.test.ts`, `backend/domains/tasks/agent-work-state.test.ts`, `backend/domains/tasks/agent-runs.test.ts`, `backend/domains/chat/shim.test.ts`, `backend/domains/tasks/agent-read-tools.integration.ts` (`checkAgentTaskReadTools` in `backend:integration`); the restart itself (`task_start_agent`) is its own lane's | -| [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | `workspace_status` names the release label of the backend that answered: `platform.version` is that process's `TALE_VERSION` (the image's build stamp unless the environment overrides it), trimmed, when it has the release shape (`0.5.64`, a prerelease such as `0.6.0-rc.1`), and `null` with a fixed note otherwise — an unset or blank stamp, `dev`, the Build workflow's `candidate-sha-…`, `pr-…-sha-…` and `sha-…` images, a `v`-prefixed or partial label — whose label is never echoed. The door adds it after the session-token check, beside the tool listing it answers unchanged (the grants, or the no-tools note); nothing but the bearer token is read from the request, so a forged body, query or header changes nothing, and a refused token still gets the bare 401. The in-sandbox bridge relays the answer byte for byte and sends `{}` whatever the model passes; its tool description calls the value a label of that backend, not proof of what is deployed or of its health | ✅ unit + Postgres | `backend/domains/sandbox/dispatch-routes.test.ts`, `lib/shared/release-version.test.ts`, `services/sandbox-runtime/daemon/src/tale-connectors-mcp.test.ts`, `backend/integration-check.ts` (`checkSandboxSpawner`: a release stamp, a no-grants token, a forged body, an expired token and a candidate stamp through `/api/tools/status`) | +| [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | `workspace_status` names the release label of the backend that answered: `platform.version` is that process's `TALE_VERSION` (the image's build stamp unless the environment overrides it), trimmed, when it has the release shape (`0.5.64`, a prerelease such as `0.6.0-rc.1`), and `null` with a fixed note otherwise — an unset or blank stamp, `dev`, the Build workflow's `candidate-sha-…`, `pr-…-sha-…` and `sha-…` images, a `v`-prefixed or partial label — whose label is never echoed. The door adds it after the session-token check, beside the tool listing it answers unchanged (the grants, or the no-tools note); nothing but the bearer token is read from the request, so a forged body, query or header changes nothing, and a refused token still gets the bare 401. The in-sandbox bridge relays the answer byte for byte and sends `{}` whatever the model passes. A mistakenly nested `workspace_tool({tool:"workspace_status"})` uses that same authenticated status door, never the execution grant gate or an execution fallback; authentication failures remain failures, ordinary task calls remain grant-gated, and near-miss or missing names keep their existing refusals. Guidance names the separate `workspace_status` MCP tool with `{}`, never a new grant. Its tool description calls the value a label of that backend, not proof of what is deployed or of its health | ✅ unit + Postgres | `backend/domains/sandbox/dispatch-routes.test.ts`, `lib/shared/release-version.test.ts`, `services/sandbox-runtime/daemon/src/tale-connectors-mcp.test.ts`, `backend/integration-check.ts` (`checkSandboxSpawner`: a release stamp, a no-grants token, a forged body, an expired token and a candidate stamp through `/api/tools/status`) | | [accessibility](../suites/accessibility.md) / [tasks](../suites/tasks.md) | Error labels and explanations retain AA contrast on page, card and muted form surfaces in both themes; destructive alerts and actions remain readable | ✅ Chromium | `packages/ui/src/components/forms/label.browser.test.tsx`; over-cap copy wrapping remains manual (`TASK-B11`) | | [auth](../suites/auth.md) | Authenticator label and issuer name the client, the product and a non-production environment (`Example plus Tale Platform TE`; `Tale Platform` with neither set) in both enrollment and existing-secret URIs; re-display preserves the secret, and invalid client names or environment labels are refused. The web tier hands the page both settings, normalized, and leaves out one the backend would refuse; backup codes download under the same words from the enrollment wall and from Account | ✅ backend + server + component + e2e | `lib/shared/authenticator-name.test.ts`, `backend/auth/auth.totp-issuer.test.ts`, `backend/env.test.ts`, `server.test.ts`, `vite-plugins/inject-env.test.ts`, `app/features/settings/account/lib/download-backup-codes.test.ts`, `tests/e2e/specs/auth-account.spec.ts` (*enrolls with a generated TOTP code*); `AUTH-F31` checks a real authenticator app, `AUTH-F32` the saved file. | | [auth](../suites/auth.md) | Trusted headers: a key is minted once and only its hash stored, the door resolves the organization from the key, JIT-creates inside it with the clamped role, refuses strangers, paused organizations and revoked keys, and binds role + organization to the session; the card's switch, create and revoke flows | ✅ automated | `backend/domains/trusted_headers/service.test.ts`, `backend/domains/trusted_headers/routes.test.ts`, `backend/domains/sso/trusted-headers.test.ts`, `app/features/settings/trusted-headers/components/trusted-headers-section.test.tsx`, `app/features/settings/trusted-headers/components/embedding-section.test.tsx`, `lib/org-frame-ancestors.test.ts`, `server.test.ts` (frame ancestors), `backend/lib/http-hygiene.test.ts` (frameable variant), `backend/domains/sso/admin-routes.discovery.test.ts` (proxy probe), `backend/domains/sso/trusted-headers.mint.test.ts` (transparent sign-in on the app's own GET, hold cookie, no POST, no cross-site), `app/features/auth/login-proxy-handoff.test.tsx` (login page hands off, loop guard, hold + Continue, refusal shown in page, bfcache reload), `app/components/user-button.test.tsx` (no Log out for a proxied session), `app/hooks/use-session-idle-watchdog.test.tsx` (hold cookie on inactivity sign-out), `backend/integration-check.ts` (`checkTrustedHeaders`) | diff --git a/services/sandbox-runtime/daemon/src/tale-connectors-mcp.test.ts b/services/sandbox-runtime/daemon/src/tale-connectors-mcp.test.ts index 080e3303d5..1a9996973d 100644 --- a/services/sandbox-runtime/daemon/src/tale-connectors-mcp.test.ts +++ b/services/sandbox-runtime/daemon/src/tale-connectors-mcp.test.ts @@ -18,6 +18,7 @@ let server: ReturnType; let bridge: ChildProcessWithoutNullStreams; const lines: Array> = []; const bodies: unknown[] = []; +let statusCode = 200; const statusCalls: Array<{ path: string; authorization: string | null; @@ -60,11 +61,27 @@ beforeAll(() => { authorization: request.headers.get('authorization'), body: await request.text(), }); - return new Response(STATUS_TEXT, { - headers: { 'content-type': 'application/json' }, + return new Response( + statusCode === 200 + ? STATUS_TEXT + : JSON.stringify({ status: 'error', message: 'Unauthorized.' }), + { + status: statusCode, + headers: { 'content-type': 'application/json' }, + }, + ); + } + const body = asRecord(await request.json()); + bodies.push(body); + if (body.tool === 'task_get') { + return Response.json({ status: 'ok', output: { taskId: 'task_1' } }); + } + if (body.tool !== 'rag_search' && body.tool !== 'generate_image') { + return Response.json({ + status: 'unavailable', + blockers: [{ code: 'not_granted' }], }); } - bodies.push(await request.json()); // Slower than the ordinary bound, faster than the long one. await Bun.sleep(600); return Response.json({ status: 'ok', output: { saved: true } }); @@ -223,4 +240,101 @@ describe('workspace_status through the bridge', () => { 'not proof of what is deployed or of its health', ); }); + + test('routes an exact nested status name through the same authenticated discovery door', async () => { + const beforeStatus = statusCalls.length; + const beforeExecute = bodies.length; + send({ + id: 12, + method: 'tools/call', + params: { + name: 'workspace_tool', + arguments: { + tool: 'workspace_status', + args: { + toolGrants: ['task_create'], + organizationId: 'org_forged', + platform: { version: '9.9.9' }, + }, + }, + }, + }); + const response = await responseTo(12); + expect(textOf(response)).toBe(STATUS_TEXT); + expect(asRecord(response.result).isError).toBe(false); + expect(statusCalls.slice(beforeStatus)).toEqual([ + { + path: '/api/tools/status', + authorization: 'Bearer session-key', + body: '{}', + }, + ]); + expect(bodies.length).toBe(beforeExecute); + }); + + test('preserves status authentication failures without an execute fallback', async () => { + const beforeStatus = statusCalls.length; + const beforeExecute = bodies.length; + statusCode = 401; + try { + send({ + id: 13, + method: 'tools/call', + params: { + name: 'workspace_tool', + arguments: { tool: 'workspace_status' }, + }, + }); + const response = await responseTo(13); + expect(JSON.parse(textOf(response))).toEqual({ + status: 'error', + message: 'Unauthorized.', + }); + expect(asRecord(response.result).isError).toBe(true); + expect(statusCalls.length).toBe(beforeStatus + 1); + expect(bodies.length).toBe(beforeExecute); + } finally { + statusCode = 200; + } + }); + + test('keeps actual task calls and near-miss names on the execution grant gate', async () => { + const beforeStatus = statusCalls.length; + const calls = [ + { tool: 'task_get', args: { taskId: 'task_1' } }, + { tool: 'task_create', args: { title: 'blocked' } }, + { tool: 'workspace_status ', args: {} }, + ]; + for (const [index, args] of calls.entries()) { + const id = 20 + index; + send({ + id, + method: 'tools/call', + params: { name: 'workspace_tool', arguments: args }, + }); + const response = await responseTo(id); + expect(JSON.parse(textOf(response))).toEqual( + index === 0 + ? { status: 'ok', output: { taskId: 'task_1' } } + : { status: 'unavailable', blockers: [{ code: 'not_granted' }] }, + ); + expect(bodies.at(-1)).toEqual(args); + } + expect(statusCalls.length).toBe(beforeStatus); + }); + + test('still rejects a missing name locally without a discovery or execution request', async () => { + const beforeStatus = statusCalls.length; + const beforeExecute = bodies.length; + send({ + id: 30, + method: 'tools/call', + params: { name: 'workspace_tool', arguments: {} }, + }); + const response = await responseTo(30); + expect(textOf(response)).toBe('"tool" is required.'); + expect(asRecord(response.result).isError).toBe(true); + expect(statusCalls.length).toBe(beforeStatus); + expect(bodies.length).toBe(beforeExecute); + }); }); diff --git a/services/sandbox-runtime/tale-connectors-mcp b/services/sandbox-runtime/tale-connectors-mcp index 584b17244a..1dfd54f595 100755 --- a/services/sandbox-runtime/tale-connectors-mcp +++ b/services/sandbox-runtime/tale-connectors-mcp @@ -120,7 +120,8 @@ const TOOLS = [ 'write to them, document_create saves a file to the hub, and ' + 'generate_image (where the organization allows it) creates images ' + 'into your workspace. The exact ' + - 'set is per agent — call workspace_status FIRST to see which tools are ' + + 'set is per agent — call the separate workspace_status MCP tool with {} ' + + 'to see which tools are ' + 'granted and their argument shapes. If the result has status ' + '"unavailable" or "invalid_args", relay the message to the user and do ' + 'not retry blindly.', @@ -141,7 +142,9 @@ const TOOLS = [ description: 'List the platform workspace tools granted to this agent (each with its ' + 'argument shape and whether it only reads or also writes). Call this ' + - 'before relying on workspace_tool. Tools are granted per agent by the ' + + 'MCP tool directly with {} to discover workspace_tool operations. ' + + 'Discovery requires a live session, not a workspace_status grant. ' + + 'Tools are granted per agent by the ' + 'user when configuring the agent; an ungranted tool cannot be called. ' + 'The answer also carries platform.version: the release version the ' + 'platform backend that answered this call is labelled with (for ' + @@ -258,6 +261,16 @@ async function handleToolCall(name, args, progressToken) { const res = await callPlatform('/status', {}); return toolText(res.text, !res.ok); } + // Some clients put the discovery tool inside the generic workspace tool. + // It is the same read-only operation: retain the session credential and + // status timeout, discard supplied args, and never pass it to execution. + if ( + name === 'workspace_status' || + (name === 'workspace_tool' && args.tool === 'workspace_status') + ) { + const res = await callPlatform('/status', {}, TOOLS_BASE_URL); + return toolText(res.text, !res.ok); + } if (name === 'workspace_tool') { const tool = typeof args.tool === 'string' ? args.tool : ''; const callArgs = @@ -279,10 +292,6 @@ async function handleToolCall(name, args, progressToken) { stopProgress(); } } - if (name === 'workspace_status') { - const res = await callPlatform('/status', {}, TOOLS_BASE_URL); - return toolText(res.text, !res.ok); - } return toolText(`Unknown tool: ${name}`, true); }