Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Make first-party tool schemas portable

wyt0bc8e7740cb4
diff --git a/bin/auto-tasks-contract.cjs b/bin/auto-tasks-contract.cjs
index 59a07509..074a7d6c 100644
--- a/bin/auto-tasks-contract.cjs
+++ b/bin/auto-tasks-contract.cjs
@@ -29,3 +29,38 @@ exports.shape = (z, bound) => {
limit: z.number().int().min(1).max(50).optional().describe('List only; default 20. Pages may be smaller to bound result size.'),
};
};
+
+/** Portable discovery only; shape() remains the strict execution validator. */
+exports.inputSchema = (z, bound) => {
+ const { zodToJsonSchema } = require('zod-to-json-schema');
+ const schema = zodToJsonSchema(z.object(exports.shape(z, bound)).strict(), { $refStrategy: 'none' });
+ const fields = schema.properties;
+ const flatten = (union, discriminator, description) => ({
+ type: 'object',
+ additionalProperties: false,
+ properties: {
+ ...Object.assign({}, ...union.anyOf.map(branch => branch.properties)),
+ [discriminator]: {
+ type: 'string',
+ enum: union.anyOf.map(branch => branch.properties[discriminator].const),
+ description,
+ },
+ },
+ required: [discriminator],
+ ...(union.description ? { description: union.description } : {}),
+ });
+ fields.schedule = flatten(fields.schedule, 'type', 'one_time requires at; hourly requires interval_hours; daily requires hour/minute; weekly also requires weekday; monthly also requires day. Omit fields belonging to other types.');
+ fields.recipient = flatten(fields.recipient, 'kind', 'commander takes kind only; agent also requires id and name.');
+ const cutoff = fields.end_condition;
+ fields.end_condition = {
+ ...flatten(cutoff.anyOf[0], 'type', 'date requires date; count requires max_runs. Omit fields belonging to the other type.'),
+ type: ['object', 'null'],
+ description: cutoff.description,
+ };
+ for (const name of ['project_id', 'skill', 'connector']) {
+ if (!fields[name]) continue;
+ const { anyOf, ...metadata } = fields[name];
+ fields[name] = { ...anyOf[0], ...metadata, type: [anyOf[0].type, 'null'] };
+ }
+ return schema;
+};
diff --git a/bin/orkas-bridge.cjs b/bin/orkas-bridge.cjs
index 6f254155..8088d53c 100644
--- a/bin/orkas-bridge.cjs
+++ b/bin/orkas-bridge.cjs
@@ -551,6 +551,19 @@ if (hasCapability('commander.handoff')) {
async function main() {
const transport = new StdioServerTransport();
+ if (hasCapability('automation')) {
+ const inputSchema = require('./auto-tasks-contract.cjs').inputSchema(z, true);
+ const send = transport.send.bind(transport);
+ // MCP's Zod conversion emits unions. Project only this owned discovery
+ // definition; keep the registered strict Zod validator for tools/call.
+ transport.send = (message, options) => send(
+ Array.isArray(message.result?.tools)
+ ? { ...message, result: { ...message.result, tools: message.result.tools.map(tool =>
+ tool.name === 'auto_tasks' ? { ...tool, inputSchema } : tool) } }
+ : message,
+ options,
+ );
+ }
await server.connect(transport);
}
diff --git a/src/core-agent/src/evolution/skill-tools.ts b/src/core-agent/src/evolution/skill-tools.ts
index a9b2f4bc..958e73c8 100644
--- a/src/core-agent/src/evolution/skill-tools.ts
+++ b/src/core-agent/src/evolution/skill-tools.ts
@@ -78,19 +78,6 @@ export function createSkillManageTool(
},
required: ["action"],
additionalProperties: false,
- oneOf: [
- { properties: { action: { enum: ["list"] } }, required: ["action"] },
- { properties: { action: { enum: ["read"] } }, required: ["action", "id"] },
- { properties: { action: { enum: ["delete"] } }, required: ["action", "id"] },
- {
- properties: { action: { enum: ["create"] } },
- required: ["action", "id", "name", "description", "body"],
- },
- {
- properties: { action: { enum: ["patch"] } },
- required: ["action", "id", "old_string", "new_string"],
- },
- ],
},
async execute(input) {
const action = input.action as SkillManageAction;
diff --git a/src/core-agent/test/evolution.test.ts b/src/core-agent/test/evolution.test.ts
index 9e7e91de..d9a8e985 100644
--- a/src/core-agent/test/evolution.test.ts
+++ b/src/core-agent/test/evolution.test.ts
@@ -451,12 +451,11 @@ describe("Evolution: skill_manage tool", () => {
expect(action.description).toContain("list: no fields");
expect(action.description).toContain("create: id/name/description/body");
expect(action.description).toContain("patch: id/old_string/new_string");
- const branches = Object.fromEntries(schema.oneOf.map((branch: any) => [
- branch.properties.action.enum[0],
- branch.required,
- ]));
- expect(branches.patch).toEqual(["action", "id", "old_string", "new_string"]);
- expect(branches.create).toEqual(["action", "id", "name", "description", "body"]);
+ expect(schema.type).toBe("object");
+ expect(schema.oneOf).toBeUndefined();
+ expect(schema.required).toEqual(["action"]);
+ expect(schema.additionalProperties).toBe(false);
+ expect(action.enum).toEqual(["create", "read", "patch", "list", "delete"]);
});
it("rejects fields from another skill action", async () => {
@@ -535,10 +534,28 @@ describe("Evolution: skill_manage tool", () => {
expect(readResult.isError).toBe(true);
});
- it("returns error for missing required fields on create", async () => {
- const result = await tool.execute({ action: "create", id: "x" }, ctx);
+ it.each([
+ ["read", "id"], ["delete", "id"],
+ ["create", "id"], ["create", "name"], ["create", "description"], ["create", "body"],
+ ["patch", "id"], ["patch", "old_string"], ["patch", "new_string"],
+ ])("rejects %s without %s before changing stored skills", async (action, missing) => {
+ await store.create({ id: "existing", name: "Existing", description: "Test", body: "original" });
+ const before = await store.read("existing");
+ const inputs: Record<string, Record<string, unknown>> = {
+ read: { action, id: "existing" },
+ delete: { action, id: "existing" },
+ create: { action, id: "new-skill", name: "New", description: "Test", body: "body" },
+ patch: { action, id: "existing", old_string: "original", new_string: "replacement" },
+ };
+ const input = inputs[action];
+ delete input[missing];
+ const created = vi.fn();
+ const result = await createSkillManageTool(store, created).execute(input, ctx);
expect(result.isError).toBe(true);
expect(result.content).toContain("required");
+ expect(await store.read("existing")).toEqual(before);
+ expect((await store.list()).map(skill => skill.id)).toEqual(["existing"]);
+ expect(created).not.toHaveBeenCalled();
});
it("returns error for unknown action", async () => {
@@ -617,6 +634,7 @@ describe("Evolution: AgentRunner integration", () => {
afterEach(cleanTmpDir);
it("registers skill_manage tool when evolution is enabled", async () => {
+ let definitions: CompletionParams["tools"];
const mockProvider = createMockProvider([
{
content: [{ type: "text", text: "Hello" }],
@@ -624,7 +642,7 @@ describe("Evolution: AgentRunner integration", () => {
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
model: "mock-model",
},
- ]);
+ ], params => { definitions = params.tools; });
const registry = new ProviderRegistry();
registry.registerFactory("mock", () => mockProvider);
@@ -636,6 +654,10 @@ describe("Evolution: AgentRunner integration", () => {
const runner = new AgentRunner({ config, providers: registry, tools: [] });
expect(runner.getSkillStore()).not.toBeNull();
+ await runner.run({ message: "Hello" });
+ const definition = definitions?.find(tool => tool.name === "skill_manage");
+ expect(definition?.inputSchema.type).toBe("object");
+ expect(definition?.inputSchema).not.toHaveProperty("oneOf");
});
it("advertises learned skills without assigning self-improvement work to the main task", async () => {
diff --git a/src/main/features/auto_tasks_tool.ts b/src/main/features/auto_tasks_tool.ts
index 922f76be..6f93e764 100644
--- a/src/main/features/auto_tasks_tool.ts
+++ b/src/main/features/auto_tasks_tool.ts
@@ -1,6 +1,5 @@
/** One host-bound automation executor shared by Commander, named Agents, and CLI. */
import { z } from 'zod';
-import { zodToJsonSchema } from 'zod-to-json-schema';
import type { AgentTool } from '../../core-agent/src/tools/base';
import * as autoTasks from './auto_tasks';
import { projectExists } from './projects';
@@ -42,7 +41,7 @@ export function createAutoTasksTool(opts: {
return {
name: 'auto_tasks',
description: contract.description,
- inputSchema: zodToJsonSchema(schema) as any,
+ inputSchema: contract.inputSchema(z, opts.projectId !== undefined),
async execute(input) {
const fail = (error: string) => ({ content: JSON.stringify({ ok: false, error }), isError: true });
const parsed = schema.safeParse(input);
diff --git a/src/main/model/core-agent/office-tools.ts b/src/main/model/core-agent/office-tools.ts
index 06ddb904..80c0231f 100644
--- a/src/main/model/core-agent/office-tools.ts
+++ b/src/main/model/core-agent/office-tools.ts
@@ -800,15 +800,8 @@ function createXlsxTool(opts: OfficeToolsOpts): AgentTool {
required: ['type'],
};
const cellSchema = {
- oneOf: [
- { type: 'string' },
- { type: 'number' },
- { type: 'boolean' },
- {
- type: 'object',
- properties: xlsxCellPropertySchema(),
- },
- ],
+ type: ['string', 'number', 'boolean', 'object'],
+ properties: xlsxCellPropertySchema(),
};
const columnSchema = {
type: 'object',
diff --git a/src/main/model/core-agent/tool-catalog-revision.ts b/src/main/model/core-agent/tool-catalog-revision.ts
index 8e5b0213..a777bf81 100644
--- a/src/main/model/core-agent/tool-catalog-revision.ts
+++ b/src/main/model/core-agent/tool-catalog-revision.ts
@@ -5,4 +5,4 @@
* it as their current-state oracle without pulling the Electron runtime or the
* tool catalog's logger/path dependency chain into model-eval processes.
*/
-export const TOOL_CATALOG_REVISION = '41';
+export const TOOL_CATALOG_REVISION = '43';
diff --git a/src/main/model/core-agent/tool-result-tools.ts b/src/main/model/core-agent/tool-result-tools.ts
index a1d05338..1043e61a 100644
--- a/src/main/model/core-agent/tool-result-tools.ts
+++ b/src/main/model/core-agent/tool-result-tools.ts
@@ -263,18 +263,6 @@ function createToolResultTool(opts: ToolResultToolsOpts): AgentTool {
type: 'string',
pattern: TOOL_RESULT_REF_SCHEMA_PATTERN,
});
- const searchRequest = {
- type: 'object',
- additionalProperties: false,
- properties: {
- ref: refProperty(),
- query: {
- type: 'string',
- description: 'Narrow text expression under 256 estimated tokens. Do not use for structured aggregation.',
- },
- },
- required: ['ref', 'query'],
- };
const structuredQueryProperties = () => ({
ref: refProperty(),
dataset: {
@@ -283,7 +271,7 @@ function createToolResultTool(opts: ToolResultToolsOpts): AgentTool {
},
explode: {
type: 'string',
- description: 'Expand one advertised array by its record-relative path; no dataset prefix or [].',
+ description: 'Expand one advertised array by its record-relative path; no dataset prefix or []. With explode, field, filters.field and group_by use $item.<field>, $parent.<field>, or $index; scalar items use $item.',
},
field: {
type: 'string',
@@ -313,33 +301,21 @@ function createToolResultTool(opts: ToolResultToolsOpts): AgentTool {
order: { type: 'string', enum: ['asc', 'desc'], description: 'Structured aggregate sort order; default desc.' },
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Maximum structured result groups; default 20.' },
});
- // One structured request covers count and numeric aggregates; the runtime
- // (`toolResultActionRequestError` + the query tool) enforces which fields
- // each operation needs, so the schema does not repeat the property set per
- // operation.
- const structuredRequest = {
+ // Conditional requirements and incompatible fields are checked by the
+ // action executor, independently of provider schema validation.
+ const requestSchema = {
type: 'object',
- description: 'With explode, field, filters.field and group_by use $item.<field>, $parent.<field>, or $index; scalar items use $item.',
additionalProperties: false,
properties: {
...structuredQueryProperties(),
- operation: {
+ query: {
type: 'string',
- enum: ['count', 'sum', 'average', 'minimum', 'maximum'],
- description: 'Structured aggregate. count needs no field; sum/average/minimum/maximum require field. Never include match or count_unit.',
+ description: 'Required for search: narrow text expression under 256 estimated tokens.',
},
- },
- required: ['ref', 'operation'],
- };
- const textCountRequest = {
- type: 'object',
- additionalProperties: false,
- properties: {
- ref: refProperty(),
operation: {
type: 'string',
- enum: ['count'],
- description: 'Exact count over a marker advertised as unstructured text.',
+ enum: ['count', 'sum', 'average', 'minimum', 'maximum'],
+ description: 'Required for query. Structured count needs no field; numeric aggregates require field. Unstructured text supports only count with match and count_unit; omit both for structured data.',
},
match: {
type: 'string',
@@ -350,29 +326,16 @@ function createToolResultTool(opts: ToolResultToolsOpts): AgentTool {
enum: ['matching_lines', 'occurrences'],
description: 'Required count unit. Use only for unstructured-text count.',
},
- },
- required: ['ref', 'operation', 'match', 'count_unit'],
- };
- const readRequest = {
- type: 'object',
- additionalProperties: false,
- properties: {
- ref: refProperty(),
- cursor: { type: 'integer', minimum: 0, description: 'Exact non-negative character cursor. Do not prefetch sequential chunks.' },
+ cursor: { type: 'integer', minimum: 0, description: 'Required for read: exact non-negative character cursor. Do not prefetch sequential chunks.' },
max_tokens: {
type: 'integer',
minimum: 256,
maximum: TOOL_RESULT_CHUNK_MAX_TOKENS,
- description: 'Slice budget including framing; defaults to 10000.',
+ description: 'Read slice budget including framing; defaults to 10000.',
},
},
- required: ['ref', 'cursor'],
- };
- const materializeRequest = {
- type: 'object',
- additionalProperties: false,
- properties: { ref: refProperty() },
required: ['ref'],
+ description: 'Use only fields for the selected action. materialize takes ref only.',
};
const actionProperty = {
type: 'string',
@@ -393,7 +356,7 @@ function createToolResultTool(opts: ToolResultToolsOpts): AgentTool {
minItems: 1,
maxItems: TOOL_RESULT_BATCH_MAX_ITEMS,
description: 'One to eight same-action requests. The whole batch shares 10000 tokens and remaining model-step capacity; earlier items use space first.',
- items: { oneOf: [searchRequest, structuredRequest, textCountRequest, readRequest, materializeRequest] },
+ items: requestSchema,
},
},
required: ['action', 'requests'],
diff --git a/test/main/features/auto_tasks_tool.test.ts b/test/main/features/auto_tasks_tool.test.ts
index 8dc17264..3f59fcc5 100644
--- a/test/main/features/auto_tasks_tool.test.ts
+++ b/test/main/features/auto_tasks_tool.test.ts
@@ -4,6 +4,7 @@ import nativeFs from 'node:fs';
import { syncBuiltinESMExports } from 'node:module';
import * as os from 'node:os';
import * as path from 'node:path';
+import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
const logProbe = vi.hoisted(() => ({ warn: vi.fn() }));
vi.mock('../../../src/main/logger', () => ({
@@ -43,6 +44,68 @@ const run = async (tool: ReturnType<typeof createTool>, args: Record<string, unk
};
describe('auto_tasks shared tool', () => {
+ it('exposes union-free definitions for each scope while retaining types, bounds and nullable clears', () => {
+ const validator = new AjvJsonSchemaValidator();
+ for (const projectId of [undefined, null, pid]) {
+ const schema = createTool({ userId: uid, projectId }).inputSchema;
+ expect(JSON.stringify(schema)).not.toMatch(/"(?:anyOf|oneOf|\$ref)":/);
+ const accepts = validator.getValidator(schema);
+ for (const args of [
+ { action: 'create', ...draft },
+ { action: 'update', skill: null, connector: null, end_condition: null },
+ { action: 'update', skill: { id: 's1', name: 'Skill' }, connector: { id: 'c1', name: 'Connector' } },
+ { action: 'update', recipient: { kind: 'agent', id: 'a1', name: 'Agent' } },
+ ]) expect(accepts(args).valid).toBe(true);
+ for (const fields of [
+ { schedule: null }, { schedule: { type: 'daily', hour: 24 } },
+ { recipient: null }, { skill: {} }, { connector: { id: '', name: 'Invalid' } },
+ { end_condition: { type: 'count', max_runs: 0 } }, { unknown: true },
+ ]) expect(accepts({ action: 'update', ...fields }).valid).toBe(false);
+ expect(accepts({ action: 'list', project_id: null }).valid).toBe(projectId === undefined);
+ expect(accepts({ action: 'list', project_id: '' }).valid).toBe(false);
+ }
+ });
+
+ it.each([
+ { type: 'one_time', at: '2099-01-01T09:00:00+08:00' },
+ { type: 'hourly', interval_hours: 2 },
+ { type: 'daily', hour: 9, minute: 5 },
+ { type: 'weekly', weekday: 1, hour: 9, minute: 5 },
+ { type: 'monthly', day: 31, hour: 9, minute: 5 },
+ ])('saves and reads the $type schedule through the real executor', async schedule => {
+ const tool = createTool({ userId: uid, projectId: pid });
+ const result = await run(tool, { action: 'create', ...draft, schedule });
+ expect(result).toMatchObject({ ok: true, isError: false });
+ expect(await tasks.getTask(uid, result.taskId)).toMatchObject({ schedule, enabled: false, project_id: pid });
+ expect((await run(tool, { action: 'get', task_id: result.taskId })).task.schedule).toEqual(schedule);
+ });
+
+ it('rejects conditional omissions and mixed variants without changing saved state, then clears nullable fields', async () => {
+ const tool = createTool({ userId: uid, projectId: pid });
+ const created = await run(tool, { action: 'create', ...draft, end_condition: { type: 'count', max_runs: 3 } });
+ expect(created.ok).toBe(true);
+ const before = await tasks.getTask(uid, created.taskId);
+ for (const fields of [
+ { schedule: { type: 'one_time' } }, { schedule: { type: 'hourly' } },
+ { schedule: { type: 'daily', hour: 9 } }, { schedule: { type: 'weekly', hour: 9, minute: 0 } },
+ { schedule: { type: 'monthly', hour: 9, minute: 0 } },
+ { schedule: { type: 'daily', hour: 9, minute: 0, day: 1 } },
+ { end_condition: { type: 'count' } }, { end_condition: { type: 'date' } },
+ { end_condition: { type: 'count', max_runs: 2, date: '2099-01-01' } },
+ { recipient: { kind: 'agent' } }, { recipient: { kind: 'commander', id: 'unrelated' } },
+ { skill: { id: 's1' } }, { connector: { name: 'Missing id' } },
+ ]) {
+ expect((await run(tool, { action: 'update', task_id: created.taskId, ...fields })).isError).toBe(true);
+ expect(await tasks.getTask(uid, created.taskId)).toEqual(before);
+ }
+ expect((await run(tool, { action: 'update', task_id: created.taskId, end_condition: { type: 'date', date: '2099-01-01' } })).ok).toBe(true);
+ expect(await tasks.getTask(uid, created.taskId)).toMatchObject({ end_condition: { type: 'date', date: '2099-01-01' } });
+ expect((await run(tool, { action: 'update', task_id: created.taskId, end_condition: null, skill: null, connector: null })).ok).toBe(true);
+ const cleared = await tasks.getTask(uid, created.taskId);
+ for (const name of ['end_condition', 'skill', 'connector']) expect(cleared).not.toHaveProperty(name);
+ expect(cleared).toMatchObject({ schedule: draft.schedule, content: draft.content, enabled: false, project_id: pid });
+ });
+
it('reports a saved automation for the host click-through, and nothing on delete', async () => {
// The retired `<auto-task>` container had the bus stage this offer; the tool
// is the only writer now, so it reports the save (2026-09-13, review P3-2).
diff --git a/test/main/features/local_agents/bridge_e2e.test.ts b/test/main/features/local_agents/bridge_e2e.test.ts
index 4f5cc187..77364c7c 100644
--- a/test/main/features/local_agents/bridge_e2e.test.ts
+++ b/test/main/features/local_agents/bridge_e2e.test.ts
@@ -656,6 +656,25 @@ describe('orkas-bridge.cjs › MCP stdio e2e', () => {
if (!bound) expect(await autoTasks.getTask(TEST_UID, automationId)).not.toHaveProperty('project_id');
const { createAutoTasksTool } = await import('../../../../src/main/features/auto_tasks_tool');
const nativeAuto = createAutoTasksTool({ userId: TEST_UID, projectId: scope || null });
+ const automationSchema = listed.result.tools.find((t: any) => t.name === 'auto_tasks').inputSchema;
+ expect(automationSchema).toEqual(nativeAuto.inputSchema);
+ expect(JSON.stringify(listed.result.tools)).not.toMatch(/"(?:oneOf|anyOf)":/);
+ const savedAutomation = await autoTasks.getTask(TEST_UID, automationId);
+ for (const fields of [
+ { schedule: { type: 'daily', hour: 9 } },
+ { schedule: { type: 'daily', hour: 9, minute: 0, day: 1 } },
+ { end_condition: { type: 'count' } },
+ { recipient: { kind: 'agent' } },
+ ]) {
+ const rejected = await client.request(1000, 'tools/call', { name: 'auto_tasks', arguments: { action: 'update', task_id: automationId, ...fields } });
+ expect(rejected.result?.isError || rejected.error).toBeTruthy();
+ expect(await autoTasks.getTask(TEST_UID, automationId)).toEqual(savedAutomation);
+ }
+ const cleared = await client.request(1001, 'tools/call', { name: 'auto_tasks', arguments: {
+ action: 'update', task_id: automationId, skill: null, connector: null, end_condition: null,
+ } });
+ expect(cleared.result.isError).toBeFalsy();
+ expect(await autoTasks.getTask(TEST_UID, automationId)).toMatchObject({ schedule: savedAutomation!.schedule, enabled: false });
const queryAuto = { action: 'list', enabled: false, offset: 0, limit: 1 };
const autoPage = await client.request(90, 'tools/call', { name: 'auto_tasks', arguments: queryAuto });
const nativeAutoPage = JSON.parse((await nativeAuto.execute(queryAuto, { state: {} })).content);
diff --git a/test/main/model/core-agent/injected-tool-fixture.ts b/test/main/model/core-agent/injected-tool-fixture.ts
index 447ae91f..679b52f2 100644
--- a/test/main/model/core-agent/injected-tool-fixture.ts
+++ b/test/main/model/core-agent/injected-tool-fixture.ts
@@ -1,3 +1,4 @@
+import { createAutoTasksTool } from '../../../../src/main/features/auto_tasks_tool';
import {
createExecutionPlanTool,
getBuiltinTools,
@@ -10,11 +11,30 @@ import { createFileTools, createLocalTools } from '../../../../src/main/model/co
import { createGenerateSpeechTool } from '../../../../src/main/model/core-agent/generate-speech-tool';
import { createImageGenTool } from '../../../../src/main/model/core-agent/image-gen-tool';
import { createImageStudioTool } from '../../../../src/main/model/core-agent/image-studio-tool';
-import { createVideoGenTool } from '../../../../src/main/model/core-agent/video-gen-tool';
import { createLibraryTool } from '../../../../src/main/model/core-agent/kb-tools';
import { createOfficeTools } from '../../../../src/main/model/core-agent/office-tools';
import { createPdfTools } from '../../../../src/main/model/core-agent/pdf-tools';
+import { createVideoGenTool } from '../../../../src/main/model/core-agent/video-gen-tool';
import { buildBrowserTool } from '../../../../src/main/features/group_chat/browser_tool';
+import { createSkillManageTool } from '../../../../src/core-agent/src/evolution/skill-tools';
+import type { SkillStore } from '../../../../src/core-agent/src/evolution/skill-store';
+import { createRunProgramTool } from '../../../../src/core-agent/src/tools/run-program';
+import { createProjectTasksTool } from '../../../../src/core-agent/src/tools/project-tasks-tool';
+import { createToolResultTools } from '../../../../src/main/model/core-agent/tool-result-tools';
+
+/** Late/runtime definitions omitted from the common actor-budget corpus below.
+ * Dependencies fail closed: schema inspection must not read or mutate state. */
+export function enumerateRuntimeSchemaTools(): AgentTool[] {
+ const fail = async () => { throw new Error('Schema probe must not execute tools'); };
+ const store = { list: fail, read: fail, touch: fail, create: fail, patch: fail, delete: fail };
+ return [
+ createSkillManageTool(store as unknown as SkillStore),
+ createAutoTasksTool({ userId: 'schema-probe' }),
+ createProjectTasksTool({ list: fail, get: fail, create: fail, update: fail, complete: fail }),
+ createRunProgramTool({ listToolNames: () => [], invokeTool: fail, loadSourceFile: fail }),
+ ...createToolResultTools({ toolResultsDir: '/unused', materializeDir: '/unused', isProgrammaticToolCallContext: () => false }),
+ ];
+}
/**
* Assemble the stable built-in tool corpus measured by both runner-facing
@@ -70,8 +90,8 @@ export function enumerateAllInjectedTools(): AgentTool[] {
tools.push(createLibraryTool({ userId }));
tools.push(createChatHistoryTool({ userId }));
tools.push(createImageGenTool({ userId, cid }));
- tools.push(createGenerateSpeechTool({ userId, cid }));
tools.push(createVideoGenTool({ userId, cid }));
+ tools.push(createGenerateSpeechTool({ userId, cid }));
tools.push(createImageStudioTool({ userId, cid }));
tools.push(...createOfficeTools({ userId, cid }));
tools.push(...createPdfTools({ userId, cid }));
diff --git a/test/main/model/core-agent/office-tools.test.ts b/test/main/model/core-agent/office-tools.test.ts
index 0b09afb3..19a82599 100644
--- a/test/main/model/core-agent/office-tools.test.ts
+++ b/test/main/model/core-agent/office-tools.test.ts
@@ -205,7 +205,7 @@ describe('Office built-in tools', () => {
});
expect(Object.keys(schema.properties)).toEqual(['path', 'sheets', 'preview']);
const sheetProps = schema.properties.sheets.items.properties;
- const cellObjectSchema = sheetProps.rows.items.items.oneOf.find((item: any) => item.type === 'object');
+ const cellObjectSchema = sheetProps.rows.items.items;
const cellProps = cellObjectSchema.properties;
const chartProps = sheetProps.charts.items.properties;
expect(cellProps).toEqual(expect.objectContaining({
@@ -819,8 +819,7 @@ describe('Office built-in tools', () => {
it('shares the XLSX cell property contract between create_xlsx and XLSX edit operations', () => {
const create = getTool('create_xlsx').inputSchema as any;
const edit = getTool('edit_office').inputSchema as any;
- const createCell = create.properties.sheets.items.properties.rows.items.items.oneOf
- .find((item: any) => item.type === 'object').properties;
+ const createCell = create.properties.sheets.items.properties.rows.items.items.properties;
const editProps = edit.properties.operations.items.properties.props;
for (const key of ['value', 'formula', 'format', 'type', 'bold', 'italic', 'fill', 'font.name', 'font.color']) {
diff --git a/test/main/model/core-agent/tool-catalog.test.ts b/test/main/model/core-agent/tool-catalog.test.ts
index 27bbc7ae..59e72975 100644
--- a/test/main/model/core-agent/tool-catalog.test.ts
+++ b/test/main/model/core-agent/tool-catalog.test.ts
@@ -28,6 +28,7 @@ import {
import {
enumerateAllInjectedToolNames,
enumerateAllInjectedTools,
+ enumerateRuntimeSchemaTools,
} from './injected-tool-fixture';
import { createToolSurfaceController } from '../../../../src/main/model/core-agent/tool-surface';
import {
@@ -511,10 +512,12 @@ describe('tool-catalog', () => {
// content or failing closed was touched.
// 2026-09-21: read_files advertises its existing nonempty path and
// nonnegative range bounds; file-tools tests pin the provider definition.
+ // 2026-09-21: XLSX cells use an equivalent primitive/object type array;
+ // tool-schema-compat tests compare accepted/rejected values to the old union.
expect(
fingerprint,
'A model-visible field, enum, bound, default, or required rule changed; review it as a schema change, not description cleanup.',
- ).toBe('5a0fc883f32fe8057b10014975c25a3e898316399c2cb17bbcedfbae656b21b0');
+ ).toBe('a40b858fb9236a98666aab74fa5c468a99f5f1eaf47b7cd5e2d077f3d3ad6d4e');
});
it('keeps the reviewed stable tool corpus within the description budgets', () => {
@@ -727,9 +730,10 @@ describe('isToolVisibleToAgent (ownerAgent gate)', () => {
});
it('keeps first-party provider roots compatible with object-only function interfaces', () => {
- for (const tool of enumerateAllInjectedTools()) {
+ for (const tool of [...enumerateAllInjectedTools(), ...enumerateRuntimeSchemaTools()]) {
const schema = toToolDefinition(tool).inputSchema;
expect(schema.type, tool.name).toBe('object');
+ expect(JSON.stringify(schema), tool.name).not.toMatch(/"(?:oneOf|anyOf)":/);
for (const key of ['oneOf', 'anyOf', 'allOf', 'not', 'const', 'enum']) {
expect(schema, `${tool.name}: ${key}`).not.toHaveProperty(key);
}
diff --git a/test/main/model/core-agent/tool-result-tools.test.ts b/test/main/model/core-agent/tool-result-tools.test.ts
index d3b123ca..5585f661 100644
--- a/test/main/model/core-agent/tool-result-tools.test.ts
+++ b/test/main/model/core-agent/tool-result-tools.test.ts
@@ -68,6 +68,24 @@ describe('persisted tool-result retrieval', () => {
afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
+ it('rejects incomplete or incompatible requests after schema flattening without materializing files or marking data as retrieved', async () => {
+ const tool = getTool(tools, 'tool_result');
+ const before = fs.readdirSync(dir);
+ for (const [action, request] of [
+ ['search', { ref }], ['search', { ref, query: 'needle', operation: 'count' }],
+ ['read', { ref }], ['read', { ref, cursor: 0, operation: 'count' }],
+ ['query', { ref }], ['query', { ref, operation: 'count', match: 'needle' }],
+ ['materialize', { ref, query: 'needle' }],
+ ] as const) {
+ const result = await tool.execute({ action, requests: [request] }, ctx);
+ expect(result.isError, JSON.stringify({ action, request })).toBe(true);
+ expect(fs.readdirSync(dir)).toEqual(before);
+ expect(fs.existsSync(materializeDir)).toBe(false);
+ // Error receipts may consume inline tokens, but never a successful read key.
+ expect((ctx.state.toolResultReadLedger as { readKeys: Set<string> }).readKeys.size).toBe(0);
+ }
+ });
+
it('reads beyond the retired 2K limit and finalizes without a second charge or spill', async () => {
const source = '界'.repeat(15_000);
const sourceRef = toolResultRefForPath(persistToolResult(dir, 'fixture', source));
@@ -327,15 +345,13 @@ describe('persisted tool-result retrieval', () => {
it('explains record-relative explode syntax at the provider boundary', () => {
const schema = toToolDefinition(getTool(tools, 'tool_result')).inputSchema as any;
- const structured = schema.properties.requests.items.oneOf.find(
- (shape: any) => shape.properties.explode,
- );
+ const structured = schema.properties.requests.items;
const description = structured.properties.explode.description;
expect(description).toMatch(/record-relative/i);
expect(description).toMatch(/no dataset prefix or \[\]/i);
- expect(structured.description).toMatch(/With explode, field, filters.field and group_by/);
- expect(structured.description).toMatch(/\$item\.<field>[\s\S]*\$parent\.<field>[\s\S]*\$index/);
- expect(structured.description).toContain('scalar items use $item');
+ expect(structured.properties.explode.description).toMatch(/With explode, field, filters.field and group_by/);
+ expect(structured.properties.explode.description).toMatch(/\$item\.<field>[\s\S]*\$parent\.<field>[\s\S]*\$index/);
+ expect(structured.properties.explode.description).toContain('scalar items use $item');
expect(description).not.toContain('Subsequent paths');
});
@@ -497,7 +513,6 @@ describe('persisted tool-result retrieval', () => {
pattern?: string;
properties?: Record<string, Schema>;
items?: Schema;
- oneOf?: Schema[];
};
const definitions = tools.map(toToolDefinition);
const refs: Schema[] = [];
@@ -506,12 +521,11 @@ describe('persisted tool-result retrieval', () => {
if (schema.properties?.ref) refs.push(schema.properties.ref);
for (const property of Object.values(schema.properties ?? {})) visit(property);
visit(schema.items);
- for (const branch of schema.oneOf ?? []) visit(branch);
};
for (const tool of definitions) visit(tool.inputSchema as Schema);
- // search, structured aggregate, text count, read, materialize: one ref each.
- expect(refs).toHaveLength(5);
+ // All five request forms share the same ref property.
+ expect(refs).toHaveLength(1);
for (const schema of refs) {
expect(schema.pattern).toBe(TOOL_RESULT_REF_SCHEMA_PATTERN);
expect(schema.description).toBeUndefined();
@@ -536,24 +550,18 @@ describe('persisted tool-result retrieval', () => {
expect(schema.oneOf).toBeUndefined();
expect(schema.required).toEqual(['action', 'requests']);
expect(schema.properties.action.enum).toEqual(['search', 'query', 'read', 'materialize']);
- const shapes = schema.properties.requests.items.oneOf as any[];
- expect(shapes).toHaveLength(5);
- const byKeys = (keys: string[]) => shapes.find(
- (shape) => JSON.stringify(Object.keys(shape.properties).sort()) === JSON.stringify([...keys].sort()),
- );
- expect(byKeys(['ref', 'query'])).toBeTruthy();
- expect(byKeys(['ref', 'cursor', 'max_tokens'])).toBeTruthy();
- expect(byKeys(['ref'])).toBeTruthy();
- const structured = shapes.find((shape) => shape.properties.operation?.enum?.includes('sum'));
- const textCount = shapes.find((shape) => shape.properties.match);
- expect(structured.properties.operation.enum).toEqual(['count', 'sum', 'average', 'minimum', 'maximum']);
- expect(structured.required).toEqual(['ref', 'operation']);
- expect(structured.properties).not.toHaveProperty('match');
- expect(structured.properties).not.toHaveProperty('count_unit');
- expect(structured.description)
- .toMatch(/\$item[\s\S]*\$parent[\s\S]*\$index/);
- expect(textCount.required).toEqual(['ref', 'operation', 'match', 'count_unit']);
- expect(textCount.properties).not.toHaveProperty('dataset');
+ const request = schema.properties.requests.items;
+ expect(request).not.toHaveProperty('anyOf');
+ expect(request).toMatchObject({ type: 'object', additionalProperties: false, required: ['ref'] });
+ expect(Object.keys(request.properties).sort()).toEqual([
+ 'ref', 'query', 'operation', 'dataset', 'explode', 'field', 'filters',
+ 'group_by', 'order', 'limit', 'match', 'count_unit', 'cursor', 'max_tokens',
+ ].sort());
+ expect(request.properties.operation.enum).toEqual(['count', 'sum', 'average', 'minimum', 'maximum']);
+ expect(request.properties.operation.description).toContain('Required for query');
+ expect(request.properties.query.description).toContain('Required for search');
+ expect(request.properties.cursor.description).toContain('Required for read');
+ expect(request.properties.explode.description).toMatch(/\$item[\s\S]*\$parent[\s\S]*\$index/);
expect(getTool(tools, 'tool_result').description).toMatch(/at most one tool_result call per model step/i);
const invalid = await getTool(tools, 'tool_result').execute({
diff --git a/test/main/model/core-agent/tool-schema-compat.test.ts b/test/main/model/core-agent/tool-schema-compat.test.ts
index 2a420a47..815190a2 100644
--- a/test/main/model/core-agent/tool-schema-compat.test.ts
+++ b/test/main/model/core-agent/tool-schema-compat.test.ts
@@ -1,42 +1,107 @@
import { describe, expect, it, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
import { createPiProvider } from '../../../../src/core-agent/src/providers/pi-provider';
import { toToolDefinition } from '../../../../src/core-agent/src/tools/base';
-import { createRunProgramTool } from '../../../../src/core-agent/src/tools/run-program';
-import { createProjectTasksTool } from '../../../../src/core-agent/src/tools/project-tasks-tool';
-import { createToolResultTools } from '../../../../src/main/model/core-agent/tool-result-tools';
import { buildCustomOpenAICompatibleModel } from '../../../../src/main/model/core-agent/external-providers';
-import { enumerateAllInjectedTools } from './injected-tool-fixture';
+import { enumerateAllInjectedTools, enumerateRuntimeSchemaTools } from './injected-tool-fixture';
+import { createToolResultTools } from '../../../../src/main/model/core-agent/tool-result-tools';
+import { persistToolResult, toolResultRefForPath } from '../../../../src/main/util/tool-result-cap';
+import type { Message } from '../../../../src/core-agent/src/shared/types';
function definitions() {
- const names = new Set(['cross_session_memory', 'metacognition', 'process_session', 'interactive_cli', 'chat_history', 'library']);
- const fail = async () => { throw new Error('Schema probe must not execute tools'); };
return [
- ...enumerateAllInjectedTools().filter(tool => names.has(tool.name)),
- createProjectTasksTool({ list: fail, get: fail, create: fail, update: fail, complete: fail }),
- createRunProgramTool({ listToolNames: () => [], invokeTool: fail, loadSourceFile: fail }),
- ...createToolResultTools({ toolResultsDir: '/unused', materializeDir: '/unused', isProgrammaticToolCallContext: () => false }),
- ].map(toToolDefinition);
+ ...enumerateAllInjectedTools(),
+ ...enumerateRuntimeSchemaTools(),
+ ].map(tool => ({ ...toToolDefinition(tool) }));
+}
+
+function containsUnion(value: unknown): boolean {
+ if (!value || typeof value !== 'object') return false;
+ return Object.entries(value).some(([key, child]) => ['oneOf', 'anyOf'].includes(key) || containsUnion(child));
+}
+
+function nestedUnion(tools: ReturnType<typeof definitions>, name: 'tool_result' | 'create_xlsx'): any {
+ const schema = tools.find(tool => tool.name === name)!.inputSchema as any;
+ return name === 'tool_result'
+ ? schema.properties.requests.items
+ : schema.properties.sheets.items.properties.rows.items.items;
}
-describe('custom endpoint root-schema compatibility through the real SDK', () => {
- it.each(['complete', 'stream'] as const)('admits all nine tools on %s and rejects the historical root union', async mode => {
- // Simulate the precise admission rule observed in global samples 8393/8395/8397.
+describe('Chat Completions root-schema compatibility through the real SDK', () => {
+ it('parses a streamed tool call, executes the real retrieval tool and replays its result through the SDK', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-schema-roundtrip-'));
+ const ref = toolResultRefForPath(persistToolResult(dir, 'fixture', 'Revenue: 42'));
+ const tool = createToolResultTools({ toolResultsDir: dir, materializeDir: path.join(dir, 'copies'), isProgrammaticToolCallContext: () => false })[0];
+ const input = { action: 'read', requests: [{ ref, cursor: 0 }] };
+ let calls = 0;
const requestFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
const payload = JSON.parse(String(init?.body));
- expect(payload.tools).toHaveLength(9);
+ expect(containsUnion(payload.tools)).toBe(false);
+ const replay = ++calls === 2;
+ if (replay) {
+ expect(payload.messages).toContainEqual(expect.objectContaining({ role: 'tool', tool_call_id: 'call_fixture', content: expect.stringContaining('Revenue: 42') }));
+ }
+ const deltas = replay ? [{ content: 'Revenue is 42.' }] : [
+ { role: 'assistant', tool_calls: [{ index: 0, id: 'call_fixture', type: 'function', function: { name: 'tool_result', arguments: '{"action":"read",' } }] },
+ { tool_calls: [{ index: 0, function: { arguments: `"requests":${JSON.stringify(input.requests)}}` } }] },
+ ];
+ const chunks = [...deltas.map(delta => ({ delta, finish_reason: null })), { delta: {}, finish_reason: replay ? 'stop' : 'tool_calls' }];
+ return new Response(chunks.map(choice => `data: ${JSON.stringify({ id: 'fixture', object: 'chat.completion.chunk', created: 1, model: 'schema-test', choices: [{ index: 0, ...choice }] })}\n\n`).join('') + 'data: [DONE]\n\n', { headers: { 'content-type': 'text/event-stream' } });
+ });
+ try {
+ const provider = createPiProvider({ provider: 'custom', apiKey: 'synthetic', customModel: buildCustomOpenAICompatibleModel('schema-test', { baseUrl: 'https://schema.example.test/v1', contextWindow: 128000, maxTokens: 1024 }) });
+ const messages: Message[] = [{ role: 'user', content: [{ type: 'text', text: 'Read the saved revenue.' }] }];
+ const request = { model: 'schema-test', messages, tools: definitions() };
+ const response = await provider.complete(request);
+ const call = response.content.find(item => item.type === 'tool_use');
+ expect(call).toEqual({ type: 'tool_use', id: 'call_fixture', name: 'tool_result', input });
+ if (!call || call.type !== 'tool_use') throw new Error('Expected executable tool call');
+ const result = await tool.execute(call.input, { state: {} });
+ expect(result.isError).toBeFalsy();
+ expect(result.content).toContain('Revenue: 42');
+ messages.push({ role: 'assistant', content: response.content }, { role: 'user', content: [{ type: 'tool_result', toolUseId: call.id, content: result.content }] });
+ expect((await provider.complete(request)).content).toContainEqual({ type: 'text', text: 'Revenue is 42.' });
+ expect(calls).toBe(2);
+ } finally {
+ requestFetch.mockRestore();
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it.each(['complete', 'stream'] as const)('admits common and runtime tools on %s and rejects root or nested unions', async mode => {
+ // Historical root rejection plus a stricter nested-union compatibility
+ // target. Nested rejection is a negative control, not a production trace.
+ const requestFetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
+ const payload = JSON.parse(String(init?.body));
+ expect(payload.tools).toHaveLength(43);
+ expect(payload.tools.map((tool: any) => tool.function.name)).toEqual(expect.arrayContaining([
+ 'skill_manage', 'tool_result', 'todo_tasks', 'run_program', 'cross_session_memory', 'create_xlsx', 'auto_tasks',
+ ]));
const invalid = payload.tools.some((tool: any) => {
const schema = tool.function.parameters;
- return schema.type !== 'object' || ['oneOf', 'anyOf', 'allOf', 'enum', 'const', 'not'].some(key => Object.hasOwn(schema, key));
+ return schema.type !== 'object' || containsUnion(schema)
+ || ['anyOf', 'allOf', 'enum', 'const', 'not'].some(key => Object.hasOwn(schema, key));
});
- if (invalid) return new Response(JSON.stringify({ error: { message: 'Tool root must be an object without composition keywords', type: 'invalid_request_error' } }), { status: 400, headers: { 'content-type': 'application/json' } });
+ if (invalid) return new Response(JSON.stringify({ error: { message: 'Unsupported root composition or union', type: 'invalid_request_error' } }), { status: 400, headers: { 'content-type': 'application/json' } });
const chunk = (delta: object, finish_reason: string | null) => ({ id: 'fixture', object: 'chat.completion.chunk', created: 1, model: 'schema-test', choices: [{ index: 0, delta, finish_reason }] });
return new Response([chunk({ role: 'assistant', content: 'hello' }, null), chunk({}, 'stop')].map(value => `data: ${JSON.stringify(value)}\n\n`).join('') + 'data: [DONE]\n\n', { headers: { 'content-type': 'text/event-stream' } });
});
try {
const provider = createPiProvider({ provider: 'custom', apiKey: 'synthetic', customModel: buildCustomOpenAICompatibleModel('schema-test', { baseUrl: 'https://schema.example.test/v1', contextWindow: 128000, maxTokens: 1024 }) });
- for (const legacy of [false, true]) {
+ for (const legacy of [null, 'root', 'tool_result', 'create_xlsx', 'auto_tasks'] as const) {
const tools = definitions();
- if (legacy) tools[0].inputSchema = { ...tools[0].inputSchema, oneOf: [{ required: ['action'] }] };
+ if (legacy === 'root') tools[0].inputSchema = { ...tools[0].inputSchema, oneOf: [{ required: ['action'] }] };
+ else if (legacy) {
+ // Clone before mutation: provider definitions share an identity cache.
+ const tool = tools.find(tool => tool.name === legacy)!;
+ tool.inputSchema = structuredClone(tool.inputSchema);
+ const node = legacy === 'auto_tasks'
+ ? (tool.inputSchema as any).properties.schedule : nestedUnion(tools, legacy);
+ node.anyOf = [{ type: 'object' }, { type: 'string' }];
+ }
const request = { model: 'schema-test', messages: [{ role: 'user' as const, content: [{ type: 'text' as const, text: 'hello' }] }], tools };
if (mode === 'complete') {
if (legacy) await expect(provider.complete(request)).rejects.toMatchObject({ statusCode: 400 });
@@ -44,11 +109,51 @@ describe('custom endpoint root-schema compatibility through the real SDK', () =>
} else {
const events = [];
for await (const event of provider.stream(request)) events.push(event);
- expect(events.some(event => event.type === 'error')).toBe(legacy);
+ expect(events.some(event => event.type === 'error')).toBe(Boolean(legacy));
if (!legacy) expect(events.some(event => event.type === 'message_end')).toBe(true);
}
}
- expect(requestFetch).toHaveBeenCalledTimes(2);
+ expect(requestFetch).toHaveBeenCalledTimes(5);
} finally { requestFetch.mockRestore(); }
});
});
+
+describe('portable field schemas', () => {
+ const ref = 'grep_files.0123456789abcdef';
+ it('retains request field types, bounds and closed properties', () => {
+ const schema = nestedUnion(definitions(), 'tool_result');
+ expect(containsUnion(schema)).toBe(false);
+ const accepts = new AjvJsonSchemaValidator().getValidator(schema);
+ for (const value of [{ ref, query: 'needle' }, { ref, operation: 'sum', field: 'amount' },
+ { ref, operation: 'count', match: 'needle', count_unit: 'occurrences' }, { ref, cursor: 0 }, { ref }]) {
+ expect(accepts(value).valid).toBe(true);
+ }
+ for (const value of [null, [], {}, { ref, cursor: -1 }, { ref, unexpected: true },
+ { ref, operation: 'unknown' }, { ref, count_unit: 'unknown' }, { ref, max_tokens: 255 }]) {
+ expect(accepts(value).valid).toBe(false);
+ }
+ // The provider may accept conditional omissions; owning executor tests
+ // verify they still fail without side effects at the execution boundary.
+ expect(accepts({ ref, operation: 'count', match: 'needle' }).valid).toBe(true);
+ });
+
+ it('preserves XLSX cell acceptance exactly using type arrays', () => {
+ const schema = nestedUnion(definitions(), 'create_xlsx');
+ expect(containsUnion(schema)).toBe(false);
+ expect(schema.type).toEqual(['string', 'number', 'boolean', 'object']);
+ const validator = new AjvJsonSchemaValidator();
+ const accepts = validator.getValidator(schema);
+ const previous = validator.getValidator({ oneOf: [
+ { type: 'string' }, { type: 'number' }, { type: 'boolean' },
+ { type: 'object', properties: schema.properties },
+ ] });
+ const valid = ['text', '', 0, -1.5, false, true, {}, { value: 3, bold: true }, { formula: 'SUM(A1:A3)', format: '0.00' }];
+ const invalid = [null, [], ['text'], { value: [] }, { formula: 3 }, { bold: 'yes' }, { type: 'unknown' }];
+ for (const [values, expected] of [[valid, true], [invalid, false]] as const) {
+ for (const value of values) {
+ expect(accepts(value).valid, JSON.stringify(value)).toBe(expected);
+ expect(previous(value).valid, JSON.stringify(value)).toBe(expected);
+ }
+ }
+ });
+});