Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix: tool type generation (#2931)
Eric Hayes27476aecf6a7
diff --git a/bun.lock b/bun.locknew file mode 100644index 0000000000..d79857ed6b--- /dev/null+++ b/bun.lock@@ -0,0 +1,20 @@+{+ "lockfileVersion": 1,+ "configVersion": 1,+ "workspaces": {+ "": {+ "devDependencies": {+ "@apidevtools/json-schema-ref-parser": "^15.3.5",+ },+ },+ },+ "packages": {+ "@apidevtools/json-schema-ref-parser": ["@apidevtools/[email protected]", "", { "dependencies": { "js-yaml": "^4.1.1" }, "peerDependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-orNOYXw3hYXxxisXMldjzjBzqqTLBPbwOtHg7ovBPvfBHDue1qM9YJENZ3W2BQuS+7z4ThogMbEzEsov57Itkg=="],++ "@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],++ "argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],++ "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],+ }+}diff --git a/js/app/package.json b/js/app/package.jsonindex 005492f6d6..e27fc3007f 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -117,6 +117,7 @@"zod": "^3.23.8"},"devDependencies": {+ "@apidevtools/json-schema-ref-parser": "^15.3.5","@biomejs/biome": "2.4.12","@playwright/test": "^1.55.1","@solidjs/meta": "^0.29.4",diff --git a/js/app/packages/core/component/AI/component/tool/ListEntities.tsx b/js/app/packages/core/component/AI/component/tool/ListEntities.tsxindex 5f8a25590f..3cac6309e1 100644--- a/js/app/packages/core/component/AI/component/tool/ListEntities.tsx+++ b/js/app/packages/core/component/AI/component/tool/ListEntities.tsx@@ -179,7 +179,8 @@ const handler = createToolRenderer({</span>{' '}ordered by{' '}<span class="text-accent">- {ctx.tool.data.sortBy.split('_').join(' ')}+ {ctx.tool.data.sortBy?.split('_').join(' ') ??+ 'recently viewed'}</span></span></div>diff --git a/js/app/packages/core/component/AI/component/tool/SendEmail.tsx b/js/app/packages/core/component/AI/component/tool/SendEmail.tsxindex e76a7a9555..f2ef81e402 100644--- a/js/app/packages/core/component/AI/component/tool/SendEmail.tsx+++ b/js/app/packages/core/component/AI/component/tool/SendEmail.tsx@@ -13,7 +13,7 @@ import { ComposeTool } from './email/ChatCompose';type SendEmailResponse = NamedTool<'SendEmail', 'response'>['data'];function getRecipientsLabel(data: SendEmail) {- const recipients = [...data.to, ...data.cc, ...data.bcc];+ const recipients = [...data.to, ...(data.cc ?? []), ...(data.bcc ?? [])];const labels = Array.from(new Map(recipients.map((recipient) => [diff --git a/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx b/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsxindex ac28a7186d..48d189fef9 100644--- a/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx+++ b/js/app/packages/core/component/AI/component/tool/email/ChatCompose.tsx@@ -44,7 +44,7 @@ type SendEmailSnapshot = {};function toEmailRecipients(- items: Array<{ email: string; name: string | null }>+ items: Array<{ email: string; name?: string | null }>): EmailRecipient[] {return items.map(convertContactInfoToEmailRecipient);}diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex 9271a2a994..04e57d2d15 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -1,361 +1,304 @@/* Generated by scripts/generate-dcs-tools.ts* *DO NOT EDIT MANUALLY*- **/import { z } from 'zod';-export const BashCodeExecutionToolCall = z.object({ command: z.string() });--export const BashCodeExecutionResponse = z.object({- content: z.any().superRefine((x, ctx) => {- const schemas = [- z.intersection(- z.object({- content: z- .union([z.array(z.object({ file_id: z.string() })), z.null()])- .optional(),- return_code: z.number().int(),- stderr: z.string(),- stdout: z.string(),- }),- z.object({ type: z.literal('bash_code_execution_result') })- ),- z.intersection(- z.object({- error_code: z.any().superRefine((x, ctx) => {- const schemas = [- z.literal('unavailable'),- z.literal('execution_time_exceeded'),- z.literal('container_expired'),- z.literal('invalid_input'),- z.literal('too_many_requests'),- z.literal('file_not_found'),- z.literal('string_not_found'),- ];- const errors = schemas.reduce<z.ZodError[]>(- (errors, schema) =>- ((result) =>- result.error ? [...errors, result.error] : errors)(- schema.safeParse(x)- ),- []- );- if (schemas.length - errors.length !== 1) {- ctx.addIssue({- path: ctx.path,- code: 'invalid_union',- unionErrors: errors,- message: 'Invalid input: Should pass single schema',- });- }- }),- }),- z.object({ type: z.literal('bash_code_execution_tool_result_error') })- ),- ];- const errors = schemas.reduce<z.ZodError[]>(- (errors, schema) =>- ((result) => (result.error ? [...errors, result.error] : errors))(- schema.safeParse(x)- ),- []- );- if (schemas.length - errors.length !== 1) {- ctx.addIssue({- path: ctx.path,- code: 'invalid_union',- unionErrors: errors,- message: 'Invalid input: Should pass single schema',- });- }- }),- tool_use_id: z.string(),+export const ContentSearch = z.object({+ entityTypes: z+ .array(+ z.enum([+ 'documents',+ 'chats',+ 'emails',+ 'channels',+ 'projects',+ 'call_records',+ ])+ )+ .default([]),+ query: z.string(),});-export const ContentSearch = z- .object({- entityTypes: z- .array(- z.enum([- 'documents',- 'chats',- 'emails',- 'channels',- 'projects',- 'call_records',- ])- )- .default([]),- query: z.string(),- })- .strict();-export const SearchToolResponse = z.object({results: z.array(z.any().superRefine((x, ctx) => {const schemas = [- z.object({- document_id: z.string().uuid(),- document_name: z.string(),- document_search_results: z.array(- z.object({- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- node_id: z.union([z.string(), z.null()]).optional(),- raw_content: z.union([z.string(), z.null()]).optional(),- score: z.union([z.number(), z.null()]).optional(),- })- ),- file_type: z.union([z.string(), z.null()]).optional(),- id: z.string().uuid(),- metadata: z- .union([+ z.intersection(+ z.object({+ document_id: z.string().uuid(),+ document_name: z.string(),+ document_search_results: z.array(z.object({- created_at: z.string().datetime({ offset: true }),- deleted_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- project_id: z.union([z.string(), z.null()]).optional(),- updated_at: z.string().datetime({ offset: true }),- viewed_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- }),- z.null(),- ])- .optional(),- name: z.string(),- owner_id: z.string(),- sub_type: z.union([z.literal('task'), z.null()]).optional(),- type: z.literal('document'),- }),- z.object({- chat_id: z.string().uuid(),- chat_search_results: z.array(- z.object({- chat_message_id: z- .union([z.string().uuid(), z.null()])- .optional(),- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- role: z.union([z.string(), z.null()]).optional(),- score: z.union([z.number(), z.null()]).optional(),- })- ),- id: z.string().uuid(),- metadata: z- .union([+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ node_id: z.union([z.string(), z.null()]).optional(),+ raw_content: z.union([z.string(), z.null()]).optional(),+ score: z.union([z.number(), z.null()]).optional(),+ })+ ),+ file_type: z.union([z.string(), z.null()]).optional(),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ deleted_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ project_id: z.union([z.string(), z.null()]).optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ }),+ z.null(),+ ])+ .optional(),+ name: z.string(),+ owner_id: z.string(),+ sub_type: z.union([z.literal('task'), z.null()]).optional(),+ }),+ z.object({ type: z.literal('document') })+ ),+ z.intersection(+ z.object({+ chat_id: z.string().uuid(),+ chat_search_results: z.array(z.object({- created_at: z.string().datetime({ offset: true }),- deleted_at: z- .union([z.string().datetime({ offset: true }), z.null()])+ chat_message_id: z+ .union([z.string().uuid(), z.null()]).optional(),- project_id: z.union([z.string(), z.null()]).optional(),- updated_at: z.string().datetime({ offset: true }),- viewed_at: z+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ role: z.union([z.string(), z.null()]).optional(),+ score: z.union([z.number(), z.null()]).optional(),+ })+ ),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ deleted_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ project_id: z.union([z.string(), z.null()]).optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ }),+ z.null(),+ ])+ .optional(),+ name: z.string(),+ owner_id: z.string(),+ user_id: z.string(),+ }),+ z.object({ type: z.literal('chat') })+ ),+ z.intersection(+ z.object({+ created_at: z.string().datetime({ offset: true }),+ email_message_search_results: z.array(+ z.object({+ bcc: z.array(z.string()),+ cc: z.array(z.string()),+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ labels: z.array(z.string()),+ message_id: z.union([z.string().uuid(), z.null()]).optional(),+ pretty_sender: z.string(),+ recipients: z.array(z.string()),+ score: z.union([z.number(), z.null()]).optional(),+ sender: z.string(),+ sent_at: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),- }),- z.null(),- ])- .optional(),- name: z.string(),- owner_id: z.string(),- type: z.literal('chat'),- user_id: z.string(),- }),- z.object({- created_at: z.string().datetime({ offset: true }),- email_message_search_results: z.array(- z.object({- bcc: z.array(z.string()),- cc: z.array(z.string()),- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- labels: z.array(z.string()),- message_id: z.union([z.string().uuid(), z.null()]).optional(),- pretty_sender: z.string(),- recipients: z.array(z.string()),- score: z.union([z.number(), z.null()]).optional(),- sender: z.string(),- sent_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- })- ),- id: z.string().uuid(),- inbox_visible: z.boolean(),- is_draft: z.boolean(),- is_important: z.boolean(),- is_read: z.boolean(),- name: z.union([z.string(), z.null()]).optional(),- owner_id: z.string(),- participants: z.array(- z.object({- email: z.string(),- name: z.union([z.string(), z.null()]).optional(),- })- ),- snippet: z.union([z.string(), z.null()]).optional(),- subject: z.union([z.string(), z.null()]).optional(),- thread_id: z.string().uuid(),- type: z.literal('email'),- updated_at: z.string().datetime({ offset: true }),- user_id: z.string(),- viewed_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- }),- z.object({- channel_id: z.string().uuid(),- channel_message_search_results: z.array(- z.object({- created_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),+ })+ ),+ id: z.string().uuid(),+ inbox_visible: z.boolean(),+ is_draft: z.boolean(),+ is_important: z.boolean(),+ is_read: z.boolean(),+ name: z.union([z.string(), z.null()]).optional(),+ owner_id: z.string(),+ participants: z.array(+ z.object({+ email: z.string(),name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- message_id: z.union([z.string().uuid(), z.null()]).optional(),- score: z.union([z.number(), z.null()]).optional(),- sender_id: z.union([z.string(), z.null()]).optional(),- thread_id: z.union([z.string().uuid(), z.null()]).optional(),- updated_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- })- ),- channel_type: z.string(),- id: z.string().uuid(),- metadata: z- .union([+ })+ ),+ snippet: z.union([z.string(), z.null()]).optional(),+ subject: z.union([z.string(), z.null()]).optional(),+ thread_id: z.string().uuid(),+ updated_at: z.string().datetime({ offset: true }),+ user_id: z.string(),+ viewed_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ }),+ z.object({ type: z.literal('email') })+ ),+ z.intersection(+ z.object({+ channel_id: z.string().uuid(),+ channel_message_search_results: z.array(z.object({- created_at: z.string().datetime({ offset: true }),- interacted_at: z+ created_at: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),- updated_at: z.string().datetime({ offset: true }),- viewed_at: z+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ message_id: z.union([z.string().uuid(), z.null()]).optional(),+ score: z.union([z.number(), z.null()]).optional(),+ sender_id: z.union([z.string(), z.null()]).optional(),+ thread_id: z.union([z.string().uuid(), z.null()]).optional(),+ updated_at: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),- }),- z.null(),- ])- .optional(),- owner_id: z.union([z.string(), z.null()]).optional(),- type: z.literal('channel'),- }),- z.object({- created_at: z.string().datetime({ offset: true }),- id: z.string().uuid(),- metadata: z- .union([+ })+ ),+ channel_type: z.string(),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ interacted_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ }),+ z.null(),+ ])+ .optional(),+ owner_id: z.union([z.string(), z.null()]).optional(),+ }),+ z.object({ type: z.literal('channel') })+ ),+ z.intersection(+ z.object({+ created_at: z.string().datetime({ offset: true }),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ created_at: z.string().datetime({ offset: true }),+ deleted_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ parent_project_id: z.union([z.string(), z.null()]).optional(),+ updated_at: z.string().datetime({ offset: true }),+ viewed_at: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ }),+ z.null(),+ ])+ .optional(),+ name: z.string(),+ owner_id: z.string(),+ project_search_results: z.array(+ z.object({+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ score: z.union([z.number(), z.null()]).optional(),+ })+ ),+ updated_at: z.string().datetime({ offset: true }),+ }),+ z.object({ type: z.literal('project') })+ ),+ z.intersection(+ z.object({+ call_id: z.string().uuid(),+ call_search_results: z.array(z.object({- created_at: z.string().datetime({ offset: true }),- deleted_at: z+ ended_at: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),- parent_project_id: z.union([z.string(), z.null()]).optional(),- updated_at: z.string().datetime({ offset: true }),- viewed_at: z+ highlight: z.object({+ bcc: z.array(z.string()).optional(),+ cc: z.array(z.string()).optional(),+ content: z.array(z.string()).optional(),+ name: z.union([z.string(), z.null()]).optional(),+ recipients: z.array(z.string()).optional(),+ sender: z.union([z.string(), z.null()]).optional(),+ user_id: z.union([z.string(), z.null()]).optional(),+ }),+ score: z.union([z.number(), z.null()]).optional(),+ sequence_num: z.union([z.number().int(), z.null()]).optional(),+ speaker_id: z.union([z.string(), z.null()]).optional(),+ started_at: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),- }),- z.null(),- ])- .optional(),- name: z.string(),- owner_id: z.string(),- project_search_results: z.array(- z.object({- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- score: z.union([z.number(), z.null()]).optional(),- })- ),- type: z.literal('project'),- updated_at: z.string().datetime({ offset: true }),- }),- z.object({- call_id: z.string().uuid(),- call_search_results: z.array(- z.object({- ended_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- highlight: z.object({- bcc: z.array(z.string()).optional(),- cc: z.array(z.string()).optional(),- content: z.array(z.string()).optional(),- name: z.union([z.string(), z.null()]).optional(),- recipients: z.array(z.string()).optional(),- sender: z.union([z.string(), z.null()]).optional(),- user_id: z.union([z.string(), z.null()]).optional(),- }),- score: z.union([z.number(), z.null()]).optional(),- sequence_num: z.union([z.number().int(), z.null()]).optional(),- speaker_id: z.union([z.string(), z.null()]).optional(),- started_at: z- .union([z.string().datetime({ offset: true }), z.null()])- .optional(),- transcript_id: z.union([z.string().uuid(), z.null()]).optional(),- })- ),- channel_id: z.string().uuid(),- id: z.string().uuid(),- metadata: z- .union([- z.object({- attended: z.boolean(),- channel_name: z.union([z.string(), z.null()]).optional(),- created_by: z.string(),- duration_ms: z.number().int(),- ended_at: z.string().datetime({ offset: true }),- started_at: z.string().datetime({ offset: true }),- updated_at: z.string().datetime({ offset: true }),- }),- z.null(),- ])- .optional(),- name: z.union([z.string(), z.null()]).optional(),- owner_id: z.string(),- participant_ids: z.array(z.string()),- type: z.literal('call'),- }),+ transcript_id: z+ .union([z.string().uuid(), z.null()])+ .optional(),+ })+ ),+ channel_id: z.string().uuid(),+ id: z.string().uuid(),+ metadata: z+ .union([+ z.object({+ attended: z.boolean(),+ channel_name: z.union([z.string(), z.null()]).optional(),+ created_by: z.string(),+ duration_ms: z.number().int(),+ ended_at: z.string().datetime({ offset: true }),+ started_at: z.string().datetime({ offset: true }),+ updated_at: z.string().datetime({ offset: true }),+ }),+ z.null(),+ ])+ .optional(),+ name: z.union([z.string(), z.null()]).optional(),+ owner_id: z.string(),+ participant_ids: z.array(z.string()),+ }),+ z.object({ type: z.literal('call') })+ ),];const errors = schemas.reduce<z.ZodError[]>((errors, schema) =>@@ -376,33 +319,29 @@ export const SearchToolResponse = z.object({),});-export const CreateDocument = z- .object({- documentName: z.string(),- fileContent: z.string(),- fileExtension: z.string(),- isTask: z.boolean().default(false),- })- .strict();+export const CreateDocument = z.object({+ documentName: z.string(),+ fileContent: z.string(),+ fileExtension: z.string(),+ isTask: z.boolean().default(false),+});export const CreateDocumentResponse = z.object({documentId: z.string().uuid(),});-export const GetEntityProperties = z- .object({- entity_id: z.string(),- entity_type: z.enum([- 'document',- 'task',- 'project',- 'chat',- 'thread',- 'channel',- 'user',- ]),- })- .strict();+export const GetEntityProperties = z.object({+ entity_id: z.string(),+ entity_type: z.enum([+ 'document',+ 'task',+ 'project',+ 'chat',+ 'thread',+ 'channel',+ 'user',+ ]),+});export const GetEntityPropertiesResponse = z.object({properties: z.array(@@ -425,12 +364,10 @@ export const GetEntityPropertiesResponse = z.object({summary: z.string(),});-export const GetThread = z- .object({- limit: z.union([z.number().int(), z.null()]).default(null),- threadId: z.string().uuid(),- })- .strict();+export const ReadThread = z.object({+ limit: z.union([z.number().int(), z.null()]).default(null),+ threadId: z.string().uuid(),+});export const GetThreadResponse = z.object({isRead: z.boolean(),@@ -467,12 +404,10 @@ export const GetThreadResponse = z.object({threadId: z.string().uuid(),});-export const ListCallRecords = z- .object({- attended: z.union([z.boolean(), z.null()]),- channelId: z.union([z.string().uuid(), z.null()]),- })- .strict();+export const ListCallRecords = z.object({+ attended: z.union([z.boolean(), z.null()]).optional(),+ channelId: z.union([z.string().uuid(), z.null()]).optional(),+});export const ListCallRecordsResponse = z.object({records: z.array(@@ -492,17 +427,19 @@ export const ListCallRecordsResponse = z.object({),});-export const ListEntities = z- .object({- includeTypes: z.union([+export const ListEntities = z.object({+ includeTypes: z+ .union([z.array(z.enum(['document', 'ai_chat', 'project', 'email', 'channel', 'call'])),z.null(),- ]),- sortBy: z.enum(['recently_viewed', 'recently_updated', 'recently_created']),- })- .strict();+ ])+ .optional(),+ sortBy: z+ .enum(['recently_viewed', 'recently_updated', 'recently_created'])+ .optional(),+});export const ListEntitiesResponse = z.object({items: z.array(@@ -559,25 +496,23 @@ export const ListEntitiesResponse = z.object({summary: z.string(),});-export const NameSearch = z- .object({- entityTypes: z- .array(- z.enum([- 'documents',- 'chats',- 'emails',- 'channels',- 'projects',- 'call_records',- ])- )- .default([]),- name: z.string(),- })- .strict();+export const NameSearch = z.object({+ entityTypes: z+ .array(+ z.enum([+ 'documents',+ 'chats',+ 'emails',+ 'channels',+ 'projects',+ 'call_records',+ ])+ )+ .default([]),+ name: z.string(),+});-export const ReadCallRecord = z.object({ callId: z.string().uuid() }).strict();+export const ReadCallRecord = z.object({ callId: z.string().uuid() });export const ReadCallRecordResponse = z.object({callId: z.string().uuid(),@@ -594,7 +529,7 @@ export const ReadCallRecordResponse = z.object({),});-export const ReadContent = z.object({ documentId: z.string().uuid() }).strict();+export const ReadContent = z.object({ documentId: z.string().uuid() });export const ReadContentResponse = z.object({comments: z.array(@@ -671,9 +606,7 @@ export const ReadContentResponse = z.object({}),});-export const ReadMetadata = z- .object({ documentId: z.string().uuid() })- .strict();+export const ReadMetadata = z.object({ documentId: z.string().uuid() });export const ReadMetadataResponse = z.object({documentMetadata: z.object({@@ -705,22 +638,6 @@ export const ReadMetadataResponse = z.object({userAccessLevel: z.enum(['view', 'comment', 'edit', 'owner']),});-export const ReadThread = z- .object({- contentType: z.enum([- 'channel',- 'channel-message',- 'chat-thread',- 'chat-message',- 'project',- ]),- ids: z.array(z.string()),- messagesSince: z- .union([z.string().datetime({ offset: true }), z.null()])- .default(null),- })- .strict();-export const ReadResponse = z.object({content: z.any().superRefine((x, ctx) => {const schemas = [@@ -769,37 +686,33 @@ export const ReadResponse = z.object({}),});-export const SendEmail = z- .object({- bcc: z.array(- z- .object({- email: z.string(),- name: z.union([z.string(), z.null()]).default(null),- })- .strict()- ),- body: z.string(),- cc: z.array(- z- .object({- email: z.string(),- name: z.union([z.string(), z.null()]).default(null),- })- .strict()- ),- replyingToId: z.union([z.string().uuid(), z.null()]).default(null),- subject: z.string(),- to: z.array(- z- .object({- email: z.string(),- name: z.union([z.string(), z.null()]).default(null),- })- .strict()- ),- })- .strict();+export const SendEmail = z.object({+ bcc: z+ .array(+ z.object({+ email: z.string(),+ name: z.union([z.string(), z.null()]).default(null),+ })+ )+ .optional(),+ body: z.string(),+ cc: z+ .array(+ z.object({+ email: z.string(),+ name: z.union([z.string(), z.null()]).default(null),+ })+ )+ .optional(),+ replyingToId: z.union([z.string().uuid(), z.null()]).default(null),+ subject: z.string(),+ to: z.array(+ z.object({+ email: z.string(),+ name: z.union([z.string(), z.null()]).default(null),+ })+ ),+});export const UserToolResponse = z.any().superRefine((x, ctx) => {const schemas = [@@ -860,16 +773,33 @@ export const UserToolResponse = z.any().superRefine((x, ctx) => {}});-export const SetEntityProperty = z- .object({- boolean_value: z.union([z.boolean(), z.null()]).default(null),- date_value: z- .union([z.string().datetime({ offset: true }), z.null()])- .default(null),- entity_id: z.string(),- entity_ref: z.union([- z- .object({+export const SetEntityProperty = z.object({+ boolean_value: z.union([z.boolean(), z.null()]).default(null),+ date_value: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .default(null),+ entity_id: z.string(),+ entity_ref: z+ .union([+ z.object({+ entityId: z.string(),+ entityType: z.enum([+ 'document',+ 'task',+ 'project',+ 'chat',+ 'thread',+ 'channel',+ 'user',+ ]),+ }),+ z.null(),+ ])+ .optional(),+ entity_refs: z+ .union([+ z.array(+ z.object({entityId: z.string(),entityType: z.enum(['document',@@ -881,118 +811,178 @@ export const SetEntityProperty = z'user',]),})- .strict(),- z.null(),- ]),- entity_refs: z.union([- z.array(- z- .object({- entityId: z.string(),- entityType: z.enum([- 'document',- 'task',- 'project',- 'chat',- 'thread',- 'channel',- 'user',- ]),- })- .strict()),z.null(),- ]),- entity_type: z.enum([- 'document',- 'task',- 'project',- 'chat',- 'thread',- 'channel',- 'user',- ]),- link_url: z.union([z.string(), z.null()]).default(null),- link_urls: z.union([z.array(z.string()), z.null()]).default(null),- number_value: z.union([z.number(), z.null()]).default(null),- option_id: z.union([z.string().uuid(), z.null()]).default(null),- option_ids: z.union([z.array(z.string().uuid()), z.null()]).default(null),- property_definition_id: z.string().uuid(),- string_value: z.union([z.string(), z.null()]).default(null),- })- .strict();+ ])+ .optional(),+ entity_type: z.enum([+ 'document',+ 'task',+ 'project',+ 'chat',+ 'thread',+ 'channel',+ 'user',+ ]),+ link_url: z.union([z.string(), z.null()]).default(null),+ link_urls: z.union([z.array(z.string()), z.null()]).default(null),+ number_value: z.union([z.number(), z.null()]).default(null),+ option_id: z.union([z.string().uuid(), z.null()]).default(null),+ option_ids: z.union([z.array(z.string().uuid()), z.null()]).default(null),+ property_definition_id: z.string().uuid(),+ string_value: z.union([z.string(), z.null()]).default(null),+});export const SetEntityPropertyResponse = z.object({message: z.string(),success: z.boolean(),});-export const Subagent = z.object({ task: z.string() }).strict();+export const Subagent = z.object({ task: z.string() });export const SubagentResponse = z.object({ result: z.string() });-export const TextEditorCodeExecutionToolCall = z.object({- command: z.string(),- file_text: z.union([z.string(), z.null()]).optional(),- new_str: z.union([z.string(), z.null()]).optional(),- old_str: z.union([z.string(), z.null()]).optional(),- path: z.string(),+export const UpdateThreadLabels = z.object({+ add: z.boolean(),+ label_id: z.string().uuid(),+ thread_id: z.string().uuid(),});-export const TextEditorCodeExecutionResponse = z.object({- content: z.any().superRefine((x, ctx) => {- const schemas = [- z.intersection(- z.object({- content: z.union([z.string(), z.null()]).optional(),- file_type: z.union([z.string(), z.null()]).optional(),- is_file_update: z.union([z.boolean(), z.null()]).optional(),- lines: z.union([z.array(z.string()), z.null()]).optional(),- newLines: z.union([z.number().int().gte(0), z.null()]).optional(),- newStart: z.union([z.number().int().gte(0), z.null()]).optional(),- numLines: z.union([z.number().int().gte(0), z.null()]).optional(),- oldLines: z.union([z.number().int().gte(0), z.null()]).optional(),- oldStart: z.union([z.number().int().gte(0), z.null()]).optional(),- startLine: z.union([z.number().int().gte(0), z.null()]).optional(),- totalLines: z.union([z.number().int().gte(0), z.null()]).optional(),+export const UpdateThreadLabelsResponse = z.object({+ failedCount: z.number().int().gte(0),+ successfulCount: z.number().int().gte(0),+ summary: z.string(),+});++export const WebSearchToolCall = z.object({ query: z.string() });++export const WebSearchResponse = z.object({+ content: z.array(+ z.object({+ title: z.string(),+ type: z.literal('web_search_result'),+ url: z.string(),+ })+ ),+ tool_use_id: z.string(),+});++export const WebFetchToolCall = z.object({ url: z.string() });++export const WebFetchResponse = z.object({+ content: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.intersection(+ z.object({+ content: z.object({+ citations: z+ .union([z.object({ enabled: z.boolean() }), z.null()])+ .optional(),+ source: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({+ data: z.string(),+ media_type: z.string(),+ type: z.literal('text'),+ }),+ z.object({+ data: z.string(),+ media_type: z.string(),+ type: z.literal('base64'),+ }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ title: z.union([z.string(), z.null()]).optional(),+ }),+ retrieved_at: z.string(),+ url: z.string(),}),- z.object({ type: z.literal('text_editor_code_execution_view_result') })+ z.object({ type: z.literal('web_fetch_result') })),z.intersection(z.object({- content: z.union([z.string(), z.null()]).optional(),- file_type: z.union([z.string(), z.null()]).optional(),- is_file_update: z.union([z.boolean(), z.null()]).optional(),- lines: z.union([z.array(z.string()), z.null()]).optional(),- newLines: z.union([z.number().int().gte(0), z.null()]).optional(),- newStart: z.union([z.number().int().gte(0), z.null()]).optional(),- numLines: z.union([z.number().int().gte(0), z.null()]).optional(),- oldLines: z.union([z.number().int().gte(0), z.null()]).optional(),- oldStart: z.union([z.number().int().gte(0), z.null()]).optional(),- startLine: z.union([z.number().int().gte(0), z.null()]).optional(),- totalLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ error_code: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('invalid_input'),+ z.literal('url_too_long'),+ z.literal('url_not_allowed'),+ z.literal('url_not_accessible'),+ z.literal('too_many_requests'),+ z.literal('unsupported_content_type'),+ z.literal('max_uses_exceeded'),+ z.literal('unavailable'),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),}),- z.object({- type: z.literal('text_editor_code_execution_create_result'),- })+ z.object({ type: z.literal('web_fetch_tool_result_error') })),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ tool_use_id: z.string(),+});++export const BashCodeExecutionToolCall = z.object({ command: z.string() });++export const BashCodeExecutionResponse = z.object({+ content: z.any().superRefine((x, ctx) => {+ const schemas = [z.intersection(z.object({- content: z.union([z.string(), z.null()]).optional(),- file_type: z.union([z.string(), z.null()]).optional(),- is_file_update: z.union([z.boolean(), z.null()]).optional(),- lines: z.union([z.array(z.string()), z.null()]).optional(),- newLines: z.union([z.number().int().gte(0), z.null()]).optional(),- newStart: z.union([z.number().int().gte(0), z.null()]).optional(),- numLines: z.union([z.number().int().gte(0), z.null()]).optional(),- oldLines: z.union([z.number().int().gte(0), z.null()]).optional(),- oldStart: z.union([z.number().int().gte(0), z.null()]).optional(),- startLine: z.union([z.number().int().gte(0), z.null()]).optional(),- totalLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ content: z+ .union([z.array(z.object({ file_id: z.string() })), z.null()])+ .optional(),+ return_code: z.number().int(),+ stderr: z.string(),+ stdout: z.string(),}),- z.object({- type: z.literal('text_editor_code_execution_str_replace_result'),- })+ z.object({ type: z.literal('bash_code_execution_result') })),z.intersection(z.object({@@ -1024,9 +1014,7 @@ export const TextEditorCodeExecutionResponse = z.object({}}),}),- z.object({- type: z.literal('text_editor_code_execution_tool_result_error'),- })+ z.object({ type: z.literal('bash_code_execution_tool_result_error') })),];const errors = schemas.reduce<z.ZodError[]>(@@ -1048,80 +1036,80 @@ export const TextEditorCodeExecutionResponse = z.object({tool_use_id: z.string(),});-export const UpdateThreadLabels = z- .object({- add: z.boolean(),- label_id: z.string().uuid(),- thread_id: z.string().uuid(),- })- .strict();--export const UpdateThreadLabelsResponse = z.object({- failedCount: z.number().int().gte(0),- successfulCount: z.number().int().gte(0),- summary: z.string(),+export const TextEditorCodeExecutionToolCall = z.object({+ command: z.string(),+ file_text: z.union([z.string(), z.null()]).optional(),+ new_str: z.union([z.string(), z.null()]).optional(),+ old_str: z.union([z.string(), z.null()]).optional(),+ path: z.string(),});-export const WebFetchToolCall = z.object({ url: z.string() });--export const WebFetchResponse = z.object({+export const TextEditorCodeExecutionResponse = z.object({content: z.any().superRefine((x, ctx) => {const schemas = [z.intersection(z.object({- content: z.object({- citations: z- .union([z.object({ enabled: z.boolean() }), z.null()])- .optional(),- source: z.any().superRefine((x, ctx) => {- const schemas = [- z.object({- data: z.string(),- media_type: z.string(),- type: z.literal('text'),- }),- z.object({- data: z.string(),- media_type: z.string(),- type: z.literal('base64'),- }),- ];- const errors = schemas.reduce<z.ZodError[]>(- (errors, schema) =>- ((result) =>- result.error ? [...errors, result.error] : errors)(- schema.safeParse(x)- ),- []- );- if (schemas.length - errors.length !== 1) {- ctx.addIssue({- path: ctx.path,- code: 'invalid_union',- unionErrors: errors,- message: 'Invalid input: Should pass single schema',- });- }- }),- title: z.union([z.string(), z.null()]).optional(),- }),- retrieved_at: z.string(),- url: z.string(),+ content: z.union([z.string(), z.null()]).optional(),+ file_type: z.union([z.string(), z.null()]).optional(),+ is_file_update: z.union([z.boolean(), z.null()]).optional(),+ lines: z.union([z.array(z.string()), z.null()]).optional(),+ newLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ newStart: z.union([z.number().int().gte(0), z.null()]).optional(),+ numLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ oldLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ oldStart: z.union([z.number().int().gte(0), z.null()]).optional(),+ startLine: z.union([z.number().int().gte(0), z.null()]).optional(),+ totalLines: z.union([z.number().int().gte(0), z.null()]).optional(),}),- z.object({ type: z.literal('web_fetch_result') })+ z.object({ type: z.literal('text_editor_code_execution_view_result') })+ ),+ z.intersection(+ z.object({+ content: z.union([z.string(), z.null()]).optional(),+ file_type: z.union([z.string(), z.null()]).optional(),+ is_file_update: z.union([z.boolean(), z.null()]).optional(),+ lines: z.union([z.array(z.string()), z.null()]).optional(),+ newLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ newStart: z.union([z.number().int().gte(0), z.null()]).optional(),+ numLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ oldLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ oldStart: z.union([z.number().int().gte(0), z.null()]).optional(),+ startLine: z.union([z.number().int().gte(0), z.null()]).optional(),+ totalLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ }),+ z.object({+ type: z.literal('text_editor_code_execution_create_result'),+ })+ ),+ z.intersection(+ z.object({+ content: z.union([z.string(), z.null()]).optional(),+ file_type: z.union([z.string(), z.null()]).optional(),+ is_file_update: z.union([z.boolean(), z.null()]).optional(),+ lines: z.union([z.array(z.string()), z.null()]).optional(),+ newLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ newStart: z.union([z.number().int().gte(0), z.null()]).optional(),+ numLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ oldLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ oldStart: z.union([z.number().int().gte(0), z.null()]).optional(),+ startLine: z.union([z.number().int().gte(0), z.null()]).optional(),+ totalLines: z.union([z.number().int().gte(0), z.null()]).optional(),+ }),+ z.object({+ type: z.literal('text_editor_code_execution_str_replace_result'),+ })),z.intersection(z.object({error_code: z.any().superRefine((x, ctx) => {const schemas = [+ z.literal('unavailable'),+ z.literal('execution_time_exceeded'),+ z.literal('container_expired'),z.literal('invalid_input'),- z.literal('url_too_long'),- z.literal('url_not_allowed'),- z.literal('url_not_accessible'),z.literal('too_many_requests'),- z.literal('unsupported_content_type'),- z.literal('max_uses_exceeded'),- z.literal('unavailable'),+ z.literal('file_not_found'),+ z.literal('string_not_found'),];const errors = schemas.reduce<z.ZodError[]>((errors, schema) =>@@ -1141,7 +1129,9 @@ export const WebFetchResponse = z.object({}}),}),- z.object({ type: z.literal('web_fetch_tool_result_error') })+ z.object({+ type: z.literal('text_editor_code_execution_tool_result_error'),+ })),];const errors = schemas.reduce<z.ZodError[]>(@@ -1162,16 +1152,3 @@ export const WebFetchResponse = z.object({}),tool_use_id: z.string(),});--export const WebSearchToolCall = z.object({ query: z.string() });--export const WebSearchResponse = z.object({- content: z.array(- z.object({- title: z.string(),- type: z.literal('web_search_result'),- url: z.string(),- })- ),- tool_use_id: z.string(),-});diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex 2d14ded4b1..0b455c74d5 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts@@ -1,6 +1,5 @@/* Generated by scripts/generate-dcs-tools.ts* *DO NOT EDIT MANUALLY*- **/import { err, type MaybeResult, ok } from 'core/util/maybeResult';@@ -24,7 +23,7 @@ type ToolParserMap = {call: types.GetEntityProperties;response: types.GetEntityPropertiesResponse;};- GetThread: { call: types.GetThread; response: types.GetThreadResponse };+ GetThread: { call: types.ReadThread; response: types.GetThreadResponse };ListCallRecords: {call: types.ListCallRecords;response: types.ListCallRecordsResponse;@@ -82,7 +81,7 @@ const toolParserMap = {call: schemas.GetEntityProperties,response: schemas.GetEntityPropertiesResponse,},- GetThread: { call: schemas.GetThread, response: schemas.GetThreadResponse },+ GetThread: { call: schemas.ReadThread, response: schemas.GetThreadResponse },ListCallRecords: {call: schemas.ListCallRecords,response: schemas.ListCallRecordsResponse,@@ -157,7 +156,7 @@ type ToolDataMap = {call: types.GetEntityProperties;response: types.GetEntityPropertiesResponse;};- GetThread: { call: types.GetThread; response: types.GetThreadResponse };+ GetThread: { call: types.ReadThread; response: types.GetThreadResponse };ListCallRecords: {call: types.ListCallRecords;response: types.ListCallRecordsResponse;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 03bfa78a7e..b3670d18eb 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -1,6 +1,5 @@/* Generated by scripts/generate-dcs-tools.ts* *DO NOT EDIT MANUALLY*- **//* eslint-disable *//**@@ -10,22 +9,9 @@*//**- * The expected shape of the streamed JSON following a `server_tool_use` for bash_code_execution- */-export interface BashCodeExecutionToolCall {- /**- * The bash command to execute- */- command: string;-}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * Ordered from least to most access top -> bottom*/-+export type AccessLevel = 'view' | 'comment' | 'edit' | 'owner';/*** Content of a bash code execution response - either a result or an error*/@@ -47,14 +33,210 @@ export type CodeExecutionErrorCode =| 'too_many_requests'| 'file_not_found'| 'string_not_found';-/**- * Response from bash_code_execution tool+ * The content of the document*/-export interface BashCodeExecutionResponse {- content: BashCodeExecutionContent;- tool_use_id: string;-}+export type Content =+ | {+ text: string;+ }+ | {+ markdown: MarkdownNode[];+ };+export type UnifiedSearchIndex =+ | 'documents'+ | 'chats'+ | 'emails'+ | 'channels'+ | 'projects'+ | 'call_records';+export type ContentType =+ | 'channel'+ | 'channel-message'+ | 'chat-thread'+ | 'chat-message'+ | 'project';+/**+ * The document sub type enum represents all values of document sub types.+ * These values should match the `document_sub_type_value` table in macrodb.+ */+export type DocumentSubType = 'task';+export type EntityItem =+ | {+ id: string;+ name: string;+ type: 'document';+ }+ | {+ id: string;+ name: string;+ type: 'aiChat';+ }+ | {+ id: string;+ name: string;+ type: 'project';+ }+ | {+ id: string;+ subject?: string | null;+ type: 'email';+ }+ | {+ id: string;+ name?: string | null;+ type: 'channel';+ }+ | {+ createdBy: string;+ id: string;+ type: 'call';+ };+export type ToolEntityType =+ | 'document'+ | 'task'+ | 'project'+ | 'chat'+ | 'thread'+ | 'channel'+ | 'user';+export type ItemType =+ | 'document'+ | 'ai_chat'+ | 'project'+ | 'email'+ | 'channel'+ | 'call';+export type SortBy =+ | 'recently_viewed'+ | 'recently_updated'+ | 'recently_created';+export type ReadThreadReadContent =+ | {+ channel_id: string;+ channel_name?: string | null;+ transcript: string;+ type: 'channel';+ }+ | {+ conversation: ConversationRecord[];+ type: 'chat';+ }+ | {+ formatted_preview: string;+ type: 'itemPreviews';+ };+/**+ * A single search result from web search+ */+export type SearchResult = {+ title: string;+ type: 'web_search_result';+ url: string;+};+export type UnifiedSearchResponseItem =+ | (DocumentSearchResponseItemWithMetadata & {+ type: 'document';+ })+ | (ChatSearchResponseItemWithMetadata & {+ type: 'chat';+ })+ | (EmailSearchResponseItemWithMetadata & {+ type: 'email';+ })+ | (ChannelSearchResponseItemWithMetadata & {+ type: 'channel';+ })+ | (ProjectSearchResponseItemWithMetadata & {+ type: 'project';+ })+ | (CallRecordSearchResponseItemWithMetadata & {+ type: 'call';+ });+/**+ * Response from the SendEmail tool.+ */+export type SendEmailResponse =+ | 'userEdited'+ | {+ sent: {+ /**+ * The database ID of the sent message.+ */+ message_id: string;+ /**+ * The thread ID the message belongs to.+ */+ thread_id: string;+ };+ }+ | {+ convertedToDraft: {+ draft_id: string;+ };+ };+/**+ * Content of a text editor code execution response - either a result or an error+ */+export type TextEditorCodeExecutionContent =+ | (TextEditorCodeExecutionResult & {+ type: 'text_editor_code_execution_view_result';+ })+ | (TextEditorCodeExecutionResult & {+ type: 'text_editor_code_execution_create_result';+ })+ | (TextEditorCodeExecutionResult & {+ type: 'text_editor_code_execution_str_replace_result';+ })+ | (TextEditorCodeExecutionToolError & {+ type: 'text_editor_code_execution_tool_result_error';+ });+/**+ * User tools are pending until a user executes them+ */+export type UserToolResponse =+ | 'PendingUserExecution'+ | 'Rejected'+ | {+ UserAction: SendEmailResponse;+ };+/**+ * Content of a web fetch response - either a successful result or an error+ */+export type WebFetchContent =+ | (WebFetchResult & {+ type: 'web_fetch_result';+ })+ | (WebFetchToolError & {+ type: 'web_fetch_tool_result_error';+ });+/**+ * Source content of a fetched document+ */+export type WebFetchSource =+ | {+ data: string;+ media_type: string;+ type: 'text';+ }+ | {+ data: string;+ media_type: string;+ type: 'base64';+ };+/**+ * Possible error codes for web fetch failures+ */+export type WebFetchErrorCode =+ | 'invalid_input'+ | 'url_too_long'+ | 'url_not_allowed'+ | 'url_not_accessible'+ | 'too_many_requests'+ | 'unsupported_content_type'+ | 'max_uses_exceeded'+ | 'unavailable';+/*** Successful bash code execution result*/@@ -91,593 +273,431 @@ export interface CodeExecutionFile {export interface BashCodeExecutionToolError {error_code: CodeExecutionErrorCode;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * Response from bash_code_execution tool*/-+export interface BashCodeExecutionResponse {+ content: BashCodeExecutionContent;+ tool_use_id: string;+}/**- * Search for items by their content. For documents, this searches the document body text. For emails, this searches the email message body. For chats, this searches the message content. For call records, this searches the call transcript text. This tool finds items based on what's inside them, not their titles or names.+ * The expected shape of the streamed JSON following a `server_tool_use` for bash_code_execution*/-export interface ContentSearch {+export interface BashCodeExecutionToolCall {/**- * Which types of items to search. Leave empty to search all types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records']+ * The bash command to execute+ */+ command: string;+}+export interface CallRecordMetadata {+ attended: boolean;+ channel_name?: string | null;+ created_by: string;+ duration_ms: number;+ ended_at: string;+ started_at: string;+ updated_at: string;+}+export interface CallRecordSearchResponseItemWithMetadata {+ call_id: string;+ call_search_results: CallRecordSearchResult[];+ channel_id: string;+ id: string;+ /**+ * `None` if the call has been deleted.+ */+ metadata?: CallRecordMetadata | null;+ name?: string | null;+ owner_id: string;+ participant_ids: string[];+}+export interface CallRecordSearchResult {+ ended_at?: string | null;+ highlight: SearchHighlight;+ score?: number | null;+ sequence_num?: number | null;+ speaker_id?: string | null;+ started_at?: string | null;+ transcript_id?: string | null;+}+export interface SearchHighlight {+ /**+ * The highlight match on the bcc (email only)*/- entityTypes: (- | 'documents'- | 'chats'- | 'emails'- | 'channels'- | 'projects'- | 'call_records'- )[];+ bcc?: string[];/**- * The text content to search for. This searches within the body of documents, emails, messages, and call transcripts.+ * The highlight match on the cc (email only)*/- query: string;+ cc?: string[];+ /**+ * The highlight match on the content field+ */+ content?: string[];+ /**+ * The highlight match on the name field+ */+ name?: string | null;+ /**+ * The highlight match on the recipients (email only)+ */+ recipients?: string[];+ /**+ * The highlight match on the sender (email only)+ */+ sender?: string | null;+ /**+ * The highlight match on the user (owner) of the entity+ */+ user_id?: string | null;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * A call-record summary. Intentionally omits the transcript — use+ * [`super::read_call_record::ReadCallRecord`] to fetch it.*/--export interface SearchToolResponse {- results: (- | {- /**- * The id of the document- */- document_id: string;- /**- * The name of the document- */- document_name: string;- /**- * The search results for the document- * This may be empty if the search result match was on the document name only- */- document_search_results: {- /**- * The highlights for the document- */- highlight: {- /**- * The highlight match on the bcc (email only)- */- bcc?: string[];- /**- * The highlight match on the cc (email only)- */- cc?: string[];- /**- * The highlight match on the content field- */- content?: string[];- /**- * The highlight match on the name field- */- name?: string | null;- /**- * The highlight match on the recipients (email only)- */- recipients?: string[];- /**- * The highlight match on the sender (email only)- */- sender?: string | null;- /**- * The highlight match on the user (owner) of the entity- */- user_id?: string | null;- };- /**- * The node id for the document.- * This is only useful for markdown at the moment- * This will only be provided if the match was on content- */- node_id?: string | null;- /**- * The raw content of the document.- * This is only included for markdown files and will be the raw json node of the match- */- raw_content?: string | null;- /**- * The score of the result- */- score?: number | null;- }[];- /**- * The file type of the document- */- file_type?: string | null;- /**- * Standardized fields that all item types will share.- * These field names are being aligned across all item types- * for consistency in our data model.- */- id: string;- /**- * Metadata from the database. None if the document doesn't exist in the database.- */- metadata?: {- created_at: string;- deleted_at?: string | null;- project_id?: string | null;- updated_at: string;- viewed_at?: string | null;- } | null;- name: string;- owner_id: string;- /**- * The sub type of the document if present.- */- sub_type?: 'task' | null;- type: 'document';- }- | {- /**- * The id of the chat- */- chat_id: string;- /**- * The search results for the chat- * This may be empty if the search result match was on the chat title only- */- chat_search_results: {- /**- * The chat message id for the chat- * This is only present if the search match was on the chat message content- */- chat_message_id?: string | null;- /**- * The highlights for the chat message- */- highlight: {- /**- * The highlight match on the bcc (email only)- */- bcc?: string[];- /**- * The highlight match on the cc (email only)- */- cc?: string[];- /**- * The highlight match on the content field- */- content?: string[];- /**- * The highlight match on the name field- */- name?: string | null;- /**- * The highlight match on the recipients (email only)- */- recipients?: string[];- /**- * The highlight match on the sender (email only)- */- sender?: string | null;- /**- * The highlight match on the user (owner) of the entity- */- user_id?: string | null;- };- /**- * The role of the chat message- * This is only present if the search match was on the chat message content- */- role?: string | null;- /**- * The score of the result- */- score?: number | null;- }[];- /**- * Standardized fields that all item types will share.- * These field names are being aligned across all item types- * for consistency in our data model.- */- id: string;- /**- * Metadata from the database. None if the chat doesn't exist in the database.- */- metadata?: {- created_at: string;- deleted_at?: string | null;- project_id?: string | null;- updated_at: string;- viewed_at?: string | null;- } | null;- name: string;- owner_id: string;- type: 'chat';- /**- * The id of the creator of the chat- */- user_id: string;- }- | {- created_at: string;- /**- * The search results for the document- * This may be empty if the search result match was on the email subject only- */- email_message_search_results: {- /**- * This is only present if the search result is on the message content- */- bcc: string[];- /**- * This is only present if the search result is on the message content- */- cc: string[];- /**- * The highlights for the email message- */- highlight: {- /**- * The highlight match on the bcc (email only)- */- bcc?: string[];- /**- * The highlight match on the cc (email only)- */- cc?: string[];- /**- * The highlight match on the content field- */- content?: string[];- /**- * The highlight match on the name field- */- name?: string | null;- /**- * The highlight match on the recipients (email only)- */- recipients?: string[];- /**- * The highlight match on the sender (email only)- */- sender?: string | null;- /**- * The highlight match on the user (owner) of the entity- */- user_id?: string | null;- };- /**- * This is only present if the search result is on the message content- */- labels: string[];- /**- * The email message id.- * This is only present if the search result is on the message content- */- message_id?: string | null;- /**- * The pretty sender.- * If the match is on the subject, the pretty sender is the latest sender on the thread.- * This could be the sender's email if there is no contact name for the sender.- */- pretty_sender: string;- /**- * This is only present if the search result is on the message content- */- recipients: string[];- /**- * The score of the result- */- score?: number | null;- /**- * The sender.- * If the match is on the subject, the sender is the latest sender on the thread.- */- sender: string;- /**- * When the email message was sent- * This is only present if the search result is on the message content- */- sent_at?: string | null;- }[];- /**- * Standardized fields that all item types will share.- * These field names are being aligned across all item types- * for consistency in our data model.- */- id: string;- inbox_visible: boolean;- is_draft: boolean;- is_important: boolean;- is_read: boolean;- /**- * Subject of the email thread- */- name?: string | null;- owner_id: string;- /**- * The participants (senders) in this email thread- */- participants: {- email: string;- name?: string | null;- }[];- snippet?: string | null;- /**- * The subject of the email- * This is only present if the search result is on the message content- */- subject?: string | null;- /**- * The id of the email thread- */- thread_id: string;- type: 'email';- updated_at: string;- /**- * The id of the owner of the email thread- */- user_id: string;- viewed_at?: string | null;- }- | {- /**- * The id of the channel- */- channel_id: string;- /**- * The search results for the channel- * This may be empty if the search result match was not on content- */- channel_message_search_results: {- /**- * When the channel message was created- * This is only prsent if the search result is on the message content- */- created_at?: string | null;- /**- * The highlights for the channel message- */- highlight: {- /**- * The highlight match on the bcc (email only)- */- bcc?: string[];- /**- * The highlight match on the cc (email only)- */- cc?: string[];- /**- * The highlight match on the content field- */- content?: string[];- /**- * The highlight match on the name field- */- name?: string | null;- /**- * The highlight match on the recipients (email only)- */- recipients?: string[];- /**- * The highlight match on the sender (email only)- */- sender?: string | null;- /**- * The highlight match on the user (owner) of the entity- */- user_id?: string | null;- };- /**- * The channel message id- * This is only prsent if the search result is on the message content- */- message_id?: string | null;- /**- * The score of the result- */- score?: number | null;- /**- * The sender id- * This is only prsent if the search result is on the message content- */- sender_id?: string | null;- /**- * The channel message thread id- */- thread_id?: string | null;- /**- * When the channel message was last updated- * This is only prsent if the search result is on the message content- */- updated_at?: string | null;- }[];- /**- * The type of channel- */- channel_type: string;- /**- * Standardized fields that all item types will share.- * These field names are being aligned across all item types- * for consistency in our data model.- */- id: string;- /**- * Metadata from the database. None if the channel doesn't exist in the database.- */- metadata?: {- created_at: string;- interacted_at?: string | null;- updated_at: string;- viewed_at?: string | null;- } | null;- /**- * we don't store this for channels atm but keeping it here for consistency- */- owner_id?: string | null;- type: 'channel';- }- | {- created_at: string;- /**- * Standardized fields that all item types will share.- * These field names are being aligned across all item types- * for consistency in our data model.- */- id: string;- /**- * Metadata from the database. None if the project doesn't exist in the database.- */- metadata?: {- created_at: string;- deleted_at?: string | null;- parent_project_id?: string | null;- updated_at: string;- viewed_at?: string | null;- } | null;- name: string;- owner_id: string;- project_search_results: {- highlight: {- /**- * The highlight match on the bcc (email only)- */- bcc?: string[];- /**- * The highlight match on the cc (email only)- */- cc?: string[];- /**- * The highlight match on the content field- */- content?: string[];- /**- * The highlight match on the name field- */- name?: string | null;- /**- * The highlight match on the recipients (email only)- */- recipients?: string[];- /**- * The highlight match on the sender (email only)- */- sender?: string | null;- /**- * The highlight match on the user (owner) of the entity- */- user_id?: string | null;- };- /**- * The score of the result- */- score?: number | null;- }[];- type: 'project';- updated_at: string;- }- | {- call_id: string;- call_search_results: {- ended_at?: string | null;- highlight: {- /**- * The highlight match on the bcc (email only)- */- bcc?: string[];- /**- * The highlight match on the cc (email only)- */- cc?: string[];- /**- * The highlight match on the content field- */- content?: string[];- /**- * The highlight match on the name field- */- name?: string | null;- /**- * The highlight match on the recipients (email only)- */- recipients?: string[];- /**- * The highlight match on the sender (email only)- */- sender?: string | null;- /**- * The highlight match on the user (owner) of the entity- */- user_id?: string | null;- };- score?: number | null;- sequence_num?: number | null;- speaker_id?: string | null;- started_at?: string | null;- transcript_id?: string | null;- }[];- channel_id: string;- id: string;- /**- * `None` if the call has been deleted.- */- metadata?: {- attended: boolean;- channel_name?: string | null;- created_by: string;- duration_ms: number;- ended_at: string;- started_at: string;- updated_at: string;- } | null;- name?: string | null;- owner_id: string;- participant_ids: string[];- type: 'call';- }- )[];+export interface CallRecordSummary {+ /**+ * The call's unique identifier.+ */+ callId: string;+ /**+ * The channel the call belongs to.+ */+ channelId: string;+ /**+ * The channel's display name, if resolvable.+ */+ channelName?: string | null;+ /**+ * The user who created the call.+ */+ createdBy: string;+ /**+ * Call duration in milliseconds. Absent if the call is still active.+ */+ durationMs?: number | null;+ /**+ * When the call ended. Absent if the call is still active.+ */+ endedAt?: string | null;+ /**+ * True if the call is currently active.+ */+ isActive: boolean;+ /**+ * IDs of users who participated in the call.+ */+ participants: string[];+ /**+ * When the call started.+ */+ startedAt: string;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * Metadata for a channel fetched from the database*/-+export interface ChannelMetadata {+ created_at: string;+ interacted_at?: string | null;+ updated_at: string;+ viewed_at?: string | null;+}/**- * Create a plaintext document.+ * ChannelSearchResponseItem object with channel metadata we fetch from macrodb. we don't store these+ * timestamps in opensearch as they would require us to update each chat message record for the chat+ * every time the chat updates (specifically for updated_at and viewed_at and interacted_at)*/-export interface CreateDocument {+export interface ChannelSearchResponseItemWithMetadata {/**- * The name of the document without the file extension+ * The id of the channel*/- documentName: string;+ channel_id: string;/**- * The string content of the document you are creating.+ * The search results for the channel+ * This may be empty if the search result match was not on content*/- fileContent: string;+ channel_message_search_results: ChannelSearchResult[];/**- * The extension of the plaintext file you are creating.+ * The type of channel*/- fileExtension: string;+ channel_type: string;/**- * Whether this document is a task. Only applies to md documents.+ * Standardized fields that all item types will share.+ * These field names are being aligned across all item types+ * for consistency in our data model.+ */+ id: string;+ /**+ * Metadata from the database. None if the channel doesn't exist in the database.+ */+ metadata?: ChannelMetadata | null;+ /**+ * we don't store this for channels atm but keeping it here for consistency*/- isTask: boolean;+ owner_id?: string | null;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * A channel message match for a given channel id*/-+export interface ChannelSearchResult {+ /**+ * When the channel message was created+ * This is only prsent if the search result is on the message content+ */+ created_at?: string | null;+ highlight: SearchHighlight;+ /**+ * The channel message id+ * This is only prsent if the search result is on the message content+ */+ message_id?: string | null;+ /**+ * The score of the result+ */+ score?: number | null;+ /**+ * The sender id+ * This is only prsent if the search result is on the message content+ */+ sender_id?: string | null;+ /**+ * The channel message thread id+ */+ thread_id?: string | null;+ /**+ * When the channel message was last updated+ * This is only prsent if the search result is on the message content+ */+ updated_at?: string | null;+}+/**+ * A chat match for a given message id+ */+export interface ChatMessageSearchResult {+ /**+ * The chat message id for the chat+ * This is only present if the search match was on the chat message content+ */+ chat_message_id?: string | null;+ highlight: SearchHighlight;+ /**+ * The role of the chat message+ * This is only present if the search match was on the chat message content+ */+ role?: string | null;+ /**+ * The score of the result+ */+ score?: number | null;+}+/**+ * Metadata for a chat fetched from the database+ */+export interface ChatMetadata {+ created_at: string;+ deleted_at?: string | null;+ project_id?: string | null;+ updated_at: string;+ viewed_at?: string | null;+}+/**+ * ChatSearchResponse object with channel metadata we fetch from macrodb. we don't store these+ * timestamps in opensearch as they would require us to update each chat message record for the chat+ * every time the chat updates (specifically for updated_at and viewed_at)+ */+export interface ChatSearchResponseItemWithMetadata {+ /**+ * The id of the chat+ */+ chat_id: string;+ /**+ * The search results for the chat+ * This may be empty if the search result match was on the chat title only+ */+ chat_search_results: ChatMessageSearchResult[];+ /**+ * Standardized fields that all item types will share.+ * These field names are being aligned across all item types+ * for consistency in our data model.+ */+ id: string;+ /**+ * Metadata from the database. None if the chat doesn't exist in the database.+ */+ metadata?: ChatMetadata | null;+ name: string;+ owner_id: string;+ /**+ * The id of the creator of the chat+ */+ user_id: string;+}+/**+ * Citations configuration for web fetch+ */+export interface CitationsConfig {+ enabled: boolean;+}+/**+ * A single comment in a thread.+ */+export interface Comment {+ /**+ * The unique id of the comment.+ */+ commentId: number;+ /**+ * When the comment was created.+ */+ createdAt?: string | null;+ /**+ * When the comment was deleted, if ever.+ */+ deletedAt?: string | null;+ /**+ * Arbitrary comment metadata.+ */+ metadata?: {+ [k: string]: unknown;+ };+ /**+ * Ordering position within the thread.+ */+ order?: number | null;+ /**+ * The user id of the comment owner.+ */+ owner: string;+ /**+ * Sender display string.+ */+ sender?: string | null;+ /**+ * Comment body.+ */+ text: string;+ /**+ * The thread this comment belongs to.+ */+ threadId: number;+ /**+ * When the comment was last updated.+ */+ updatedAt?: string | null;+}+/**+ * A thread bundled together with its ordered comments.+ */+export interface CommentThread {+ /**+ * The comments in the thread, ordered by `createdAt` ASC.+ */+ comments: Comment[];+ thread: Thread;+}+/**+ * A comment thread attached to a document.+ */+export interface Thread {+ /**+ * When the thread was created.+ */+ createdAt?: string | null;+ /**+ * When the thread was deleted, if ever.+ */+ deletedAt?: string | null;+ /**+ * The document the thread is attached to.+ */+ documentId: string;+ /**+ * Arbitrary thread metadata.+ */+ metadata?: {+ [k: string]: unknown;+ };+ /**+ * The user id of the thread owner.+ */+ owner: string;+ /**+ * Whether the thread has been resolved.+ */+ resolved: boolean;+ /**+ * The unique id of the thread.+ */+ threadId: number;+ /**+ * When the thread was last updated.+ */+ updatedAt?: string | null;+}+/**+ * Markdown node+ */+export interface MarkdownNode {+ /**+ * Human readable content+ */+ content: string;+ /**+ * The node id+ */+ nodeId: string;+ /**+ * Json respresentation+ */+ rawContent: string;+ /**+ * The style on the node, H1, em, code, etc.+ */+ type: string;+}+/**+ * Search for items by their content. For documents, this searches the document body text. For emails, this searches the email message body. For chats, this searches the message content. For call records, this searches the call transcript text. This tool finds items based on what's inside them, not their titles or names.+ */+export interface ContentSearch {+ /**+ * Which types of items to search. Leave empty to search all types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records']+ */+ entityTypes?: UnifiedSearchIndex[];+ /**+ * The text content to search for. This searches within the body of documents, emails, messages, and call transcripts.+ */+ query: string;+}+export interface ConversationRecord {+ chat_id: string;+ messages: MessageWithAttachments[];+ title: string;+}+export interface MessageWithAttachments {+ attachmentIds: string[];+ content: string;+ date: string;+}+/**+ * Create a plaintext document.+ */+export interface CreateDocument {+ /**+ * The name of the document without the file extension+ */+ documentName: string;+ /**+ * The string content of the document you are creating.+ */+ fileContent: string;+ /**+ * The extension of the plaintext file you are creating.+ */+ fileExtension: string;+ /**+ * Whether this document is a task. Only applies to md documents.+ */+ isTask?: boolean;+}/*** The read content response*/@@ -687,42 +707,202 @@ export interface CreateDocumentResponse {*/documentId: string;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * Metadata for a document fetched from the database*/-+export interface DocumentMetadata {+ created_at: string;+ deleted_at?: string | null;+ project_id?: string | null;+ updated_at: string;+ viewed_at?: string | null;+}/**- * Get all properties attached to an entity (document, task, project, etc.). Returns property definitions with their current values and available options for select-type properties. Use this to discover custom properties on an entity. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first.+ * DocumentSearchResponseItem object with document metadata we fetch from macrodb. we don't store these+ * timestamps in opensearch as they would require us to update document page record+ * every time the document updates (specifically for updated_at and viewed_at)*/-export interface GetEntityProperties {+export interface DocumentSearchResponseItemWithMetadata {/**- * The ID of the entity to get properties for.+ * The id of the document*/- entity_id: string;+ document_id: string;/**- * The type of entity.+ * The name of the document*/- entity_type:- | 'document'- | 'task'- | 'project'- | 'chat'- | 'thread'- | 'channel'- | 'user';+ document_name: string;+ /**+ * The search results for the document+ * This may be empty if the search result match was on the document name only+ */+ document_search_results: DocumentSearchResult[];+ /**+ * The file type of the document+ */+ file_type?: string | null;+ /**+ * Standardized fields that all item types will share.+ * These field names are being aligned across all item types+ * for consistency in our data model.+ */+ id: string;+ /**+ * Metadata from the database. None if the document doesn't exist in the database.+ */+ metadata?: DocumentMetadata | null;+ name: string;+ owner_id: string;+ /**+ * The sub type of the document if present.+ */+ sub_type?: DocumentSubType | null;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * A document match for a given node*/-+export interface DocumentSearchResult {+ highlight: SearchHighlight;+ /**+ * The node id for the document.+ * This is only useful for markdown at the moment+ * This will only be provided if the match was on content+ */+ node_id?: string | null;+ /**+ * The raw content of the document.+ * This is only included for markdown files and will be the raw json node of the match+ */+ raw_content?: string | null;+ /**+ * The score of the result+ */+ score?: number | null;+}+/**+ * A recipient for an email.+ */+export interface EmailRecipient {+ /**+ * The recipient's email address.+ */+ email: string;+ /**+ * The recipient's display name (optional).+ */+ name?: string | null;+}+/**+ * A participant (sender) in an email thread+ */+export interface EmailSearchParticipant {+ email: string;+ name?: string | null;+}+/**+ * EmailSearchResponseItem object with email metadata we fetch from email service. we don't store these+ * timestamps in opensearch as they would require us to update each email message record for the thread+ * every time the thread updates (specifically for updated_at and viewed_at)+ */+export interface EmailSearchResponseItemWithMetadata {+ created_at: string;+ /**+ * The search results for the document+ * This may be empty if the search result match was on the email subject only+ */+ email_message_search_results: EmailSearchResult[];+ /**+ * Standardized fields that all item types will share.+ * These field names are being aligned across all item types+ * for consistency in our data model.+ */+ id: string;+ inbox_visible: boolean;+ is_draft: boolean;+ is_important: boolean;+ is_read: boolean;+ /**+ * Subject of the email thread+ */+ name?: string | null;+ owner_id: string;+ /**+ * The participants (senders) in this email thread+ */+ participants: EmailSearchParticipant[];+ snippet?: string | null;+ /**+ * The subject of the email+ * This is only present if the search result is on the message content+ */+ subject?: string | null;+ /**+ * The id of the email thread+ */+ thread_id: string;+ updated_at: string;+ /**+ * The id of the owner of the email thread+ */+ user_id: string;+ viewed_at?: string | null;+}+/**+ * A email message match for a given thread id+ */+export interface EmailSearchResult {+ /**+ * This is only present if the search result is on the message content+ */+ bcc: string[];+ /**+ * This is only present if the search result is on the message content+ */+ cc: string[];+ highlight: SearchHighlight;+ /**+ * This is only present if the search result is on the message content+ */+ labels: string[];+ /**+ * The email message id.+ * This is only present if the search result is on the message content+ */+ message_id?: string | null;+ /**+ * The pretty sender.+ * If the match is on the subject, the pretty sender is the latest sender on the thread.+ * This could be the sender's email if there is no contact name for the sender.+ */+ pretty_sender: string;+ /**+ * This is only present if the search result is on the message content+ */+ recipients: string[];+ /**+ * The score of the result+ */+ score?: number | null;+ /**+ * The sender.+ * If the match is on the subject, the sender is the latest sender on the thread.+ */+ sender: string;+ /**+ * When the email message was sent+ * This is only present if the search result is on the message content+ */+ sent_at?: string | null;+}+/**+ * Get all properties attached to an entity (document, task, project, etc.). Returns property definitions with their current values and available options for select-type properties. Use this to discover custom properties on an entity. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first.+ */+export interface GetEntityProperties {+ /**+ * The ID of the entity to get properties for.+ */+ entity_id: string;+ entity_type: ToolEntityType;+}/*** Response from the GetEntityProperties tool.*/@@ -730,170 +910,131 @@ export interface GetEntityPropertiesResponse {/*** The properties attached to the entity.*/- properties: {- /**- * The current value, if set.- */- currentValue?: {- [k: string]: unknown;- };- /**- * The data type (boolean, date, number, string, select_number, select_string, entity, link).- */- dataType: string;- /**- * Human-readable name of the property.- */- displayName: string;- /**- * Whether this property supports multiple values.- */- isMultiSelect: boolean;- /**- * Whether this is a system-defined property.- */- isSystem: boolean;- /**- * Available options for select-type properties.- */- options: {- /**- * Display order.- */- displayOrder: number;- /**- * The display value of this option.- */- displayValue: string;- /**- * The option ID to use when setting select values.- */- id: string;- }[];- /**- * The property definition ID. Use this when calling SetEntityProperty.- */- propertyDefinitionId: string;- }[];+ properties: ToolPropertyItem[];/*** Human-readable summary.*/summary: string;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */--/**- * Retrieve an email thread and its messages. Returns the thread metadata and message contents including sender, recipients, subject, and body text. Use this to read the contents of a specific email conversation.+ * A single property in the tool response.*/-export interface GetThread {+export interface ToolPropertyItem {/**- * Maximum number of messages to return (default 10).+ * The current value, if set.*/- limit: number | null;+ currentValue?: {+ [k: string]: unknown;+ };/**- * The ID of the email thread to retrieve.+ * The data type (boolean, date, number, string, select_number, select_string, entity, link).*/- threadId: string;+ dataType: string;+ /**+ * Human-readable name of the property.+ */+ displayName: string;+ /**+ * Whether this property supports multiple values.+ */+ isMultiSelect: boolean;+ /**+ * Whether this is a system-defined property.+ */+ isSystem: boolean;+ /**+ * Available options for select-type properties.+ */+ options: ToolPropertyOption[];+ /**+ * The property definition ID. Use this when calling SetEntityProperty.+ */+ propertyDefinitionId: string;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * A property option in the tool response.*/-+export interface ToolPropertyOption {+ /**+ * Display order.+ */+ displayOrder: number;+ /**+ * The display value of this option.+ */+ displayValue: string;+ /**+ * The option ID to use when setting select values.+ */+ id: string;+}/*** Response from the GetThread tool.*/export interface GetThreadResponse {/**- * Whether the thread has been read.+ * Whether the thread has been read.+ */+ isRead: boolean;+ /**+ * The messages in the thread (most recent first).+ */+ messages: ToolMessage[];+ /**+ * A human-readable summary.+ */+ summary: string;+ /**+ * The thread's unique identifier.+ */+ threadId: string;+}+/**+ * A simplified message for tool output.+ */+export interface ToolMessage {+ /**+ * The parsed plaintext body (reply/forwarded content stripped, HTML converted).+ */+ bodyParsed?: string | null;+ /**+ * The Cc recipients.+ */+ cc: ToolContact[];+ /**+ * When the message was received/sent.*/- isRead: boolean;+ date?: string | null;/**- * The messages in the thread (most recent first).+ * The sender's email and name.*/- messages: {- /**- * The parsed plaintext body (reply/forwarded content stripped, HTML converted).- */- bodyParsed?: string | null;- /**- * The Cc recipients.- */- cc: {- /**- * The contact's email address.- */- email: string;- /**- * The contact's display name.- */- name?: string | null;- }[];- /**- * When the message was received/sent.- */- date?: string | null;- /**- * The sender's email and name.- */- from?: {- /**- * The contact's email address.- */- email: string;- /**- * The contact's display name.- */- name?: string | null;- } | null;- /**- * The message's unique identifier.- */- id: string;- /**- * The message subject.- */- subject?: string | null;- /**- * The To recipients.- */- to: {- /**- * The contact's email address.- */- email: string;- /**- * The contact's display name.- */- name?: string | null;- }[];- }[];+ from?: ToolContact | null;/**- * A human-readable summary.+ * The message's unique identifier.*/- summary: string;+ id: string;/**- * The thread's unique identifier.+ * The message subject.*/- threadId: string;+ subject?: string | null;+ /**+ * The To recipients.+ */+ to: ToolContact[];}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * A simplified contact for tool output.*/-+export interface ToolContact {+ /**+ * The contact's email address.+ */+ email: string;+ /**+ * The contact's display name.+ */+ name?: string | null;+}/*** List recent call records the user can access, ordered by start time descending. Results are scoped to channels the user is a member of. Transcripts are NOT included — call ReadCallRecord with a specific callId to fetch a transcript.*/@@ -901,20 +1042,12 @@ export interface ListCallRecords {/*** Optional filter on whether the caller joined the call. true = only calls the user attended; false = only calls the user did not attend; omit to include both.*/- attended: boolean | null;+ attended?: boolean | null;/*** Optional channel id. When provided, only calls from that channel are returned.*/- channelId: string | null;+ channelId?: string | null;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Response for [`ListCallRecords`].*/@@ -922,53 +1055,8 @@ export interface ListCallRecordsResponse {/*** Call records ordered by start time descending.*/- records: {- /**- * The call's unique identifier.- */- callId: string;- /**- * The channel the call belongs to.- */- channelId: string;- /**- * The channel's display name, if resolvable.- */- channelName?: string | null;- /**- * The user who created the call.- */- createdBy: string;- /**- * Call duration in milliseconds. Absent if the call is still active.- */- durationMs?: number | null;- /**- * When the call ended. Absent if the call is still active.- */- endedAt?: string | null;- /**- * True if the call is currently active.- */- isActive: boolean;- /**- * IDs of users who participated in the call.- */- participants: string[];- /**- * When the call started.- */- startedAt: string;- }[];+ records: CallRecordSummary[];}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Browse the user's workspace to see recent items they have access to. Returns documents, AI conversations, projects, emails, and chat channels. Use this to get an overview of what the user has been working on or to find items by type. For finding specific items by name or content, use the search tool instead.*/@@ -976,65 +1064,13 @@ export interface ListEntities {/*** Filter to specific item types. If not provided, returns all types. Example: ["document", "email"] returns only documents and emails.*/- includeTypes:- | ('document' | 'ai_chat' | 'project' | 'email' | 'channel' | 'call')[]- | null;- /**- * How to sort results: recently_viewed (default), recently_updated, or recently_created.- */- sortBy: 'recently_viewed' | 'recently_updated' | 'recently_created';+ includeTypes?: ItemType[] | null;+ sortBy?: SortBy;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-export interface ListEntitiesResponse {- items: (- | {- id: string;- name: string;- type: 'document';- }- | {- id: string;- name: string;- type: 'aiChat';- }- | {- id: string;- name: string;- type: 'project';- }- | {- id: string;- subject?: string | null;- type: 'email';- }- | {- id: string;- name?: string | null;- type: 'channel';- }- | {- createdBy: string;- id: string;- type: 'call';- }- )[];+ items: EntityItem[];summary: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Search for items by their name or title. For documents, this searches the document name. For emails, this searches the subject line. For chats, this searches the chat title. For projects (folders), this searches the project name. For call records, this searches the channel name the call took place in. This tool finds items based on what they're called, not their content.*/@@ -1042,27 +1078,51 @@ export interface NameSearch {/*** Which types of items to search. Leave empty to search all types. Examples: ['documents'], ['emails', 'documents'], ['channels'], ['call_records']*/- entityTypes: (- | 'documents'- | 'chats'- | 'emails'- | 'channels'- | 'projects'- | 'call_records'- )[];+ entityTypes?: UnifiedSearchIndex[];/*** The name or title to search for. For emails, this is the subject line. For channels, this can be the channel name or participant names. For call records, this is the channel name the call belongs to.*/name: string;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * Metadata for a project fetched from the database*/-+export interface ProjectMetadata {+ created_at: string;+ deleted_at?: string | null;+ parent_project_id?: string | null;+ updated_at: string;+ viewed_at?: string | null;+}+/**+ * ProjectSearchResponseItem object with project metadata we fetch from macrodb. we don't store these+ * timestamps in opensearch as they would require us to update the project record+ * every time the project updates (specifically for updated_at and viewed_at)+ */+export interface ProjectSearchResponseItemWithMetadata {+ created_at: string;+ /**+ * Standardized fields that all item types will share.+ * These field names are being aligned across all item types+ * for consistency in our data model.+ */+ id: string;+ /**+ * Metadata from the database. None if the project doesn't exist in the database.+ */+ metadata?: ProjectMetadata | null;+ name: string;+ owner_id: string;+ project_search_results: ProjectSearchResult[];+ updated_at: string;+}+export interface ProjectSearchResult {+ highlight: SearchHighlight;+ /**+ * The score of the result+ */+ score?: number | null;+}/*** Retrieve the transcript for a specific call record. Use ListCallRecords first to find the callId. Only the transcript is returned — other metadata (participants, duration, etc.) is already available from ListCallRecords.*/@@ -1072,14 +1132,6 @@ export interface ReadCallRecord {*/callId: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Response for [`ReadCallRecord`] — the transcript of the requested call.*/@@ -1091,38 +1143,34 @@ export interface ReadCallRecordResponse {/*** Transcript segments in chronological order.*/- transcript: {- /**- * The transcribed text.- */- content: string;- /**- * Stable per-speaker identifier produced by diarization, when available.- * Distinguishes multiple speakers sharing one audio track.- */- diarizedSpeakerId?: string | null;- /**- * When the speaker stopped (if known).- */- endedAt?: string | null;- /**- * The speaker's user id.- */- speakerId: string;- /**- * When the speaker started this segment.- */- startedAt: string;- }[];+ transcript: TranscriptSegment[];}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * A single transcript segment.*/-+export interface TranscriptSegment {+ /**+ * The transcribed text.+ */+ content: string;+ /**+ * Stable per-speaker identifier produced by diarization, when available.+ * Distinguishes multiple speakers sharing one audio track.+ */+ diarizedSpeakerId?: string | null;+ /**+ * When the speaker stopped (if known).+ */+ endedAt?: string | null;+ /**+ * The speaker's user id.+ */+ speakerId: string;+ /**+ * When the speaker started this segment.+ */+ startedAt: string;+}/*** Retrieve a documents content*/@@ -1132,142 +1180,97 @@ export interface ReadContent {*/documentId: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-export interface ReadContentResponse {/*** Any comments on the document*/- comments: {- /**- * The comments in the thread, ordered by `createdAt` ASC.- */- comments: {- /**- * The unique id of the comment.- */- commentId: number;- /**- * When the comment was created.- */- createdAt?: string | null;- /**- * When the comment was deleted, if ever.- */- deletedAt?: string | null;- /**- * Arbitrary comment metadata.- */- metadata?: {- [k: string]: unknown;- };- /**- * Ordering position within the thread.- */- order?: number | null;- /**- * The user id of the comment owner.- */- owner: string;- /**- * Sender display string.- */- sender?: string | null;- /**- * Comment body.- */- text: string;- /**- * The thread this comment belongs to.- */- threadId: number;- /**- * When the comment was last updated.- */- updatedAt?: string | null;- }[];- /**- * The thread metadata.- */- thread: {- /**- * When the thread was created.- */- createdAt?: string | null;- /**- * When the thread was deleted, if ever.- */- deletedAt?: string | null;- /**- * The document the thread is attached to.- */- documentId: string;- /**- * Arbitrary thread metadata.- */- metadata?: {- [k: string]: unknown;- };- /**- * The user id of the thread owner.- */- owner: string;- /**- * Whether the thread has been resolved.- */- resolved: boolean;- /**- * The unique id of the thread.- */- threadId: number;- /**- * When the thread was last updated.- */- updatedAt?: string | null;- };- }[];- /**- * The content of the document- */- content:- | {- text: string;- }- | {- markdown: {- /**- * Human readable content- */- content: string;- /**- * The node id- */- nodeId: string;- /**- * Json respresentation- */- rawContent: string;- /**- * The style on the node, H1, em, code, etc.- */- type: string;- }[];- };+ comments: CommentThread[];+ content: Content;+}+export interface ReadDocumentMetadata {+ /**+ * If the document is a "task" the branch name of the document will be provided.+ */+ branchName?: string | null;+ /**+ * The id of the document this document branched from+ */+ branchedFromId?: string | null;+ /**+ * The id of the version this document branched from+ * This could be either DocumentInstance or DocumentBom id depending on+ * the file type+ */+ branchedFromVersionId?: number | null;+ /**+ * The time the document was created+ */+ createdAt?: string | null;+ /**+ * The time the document was deleted+ */+ deletedAt?: string | null;+ /**+ * If the document is a DOCX document and unzipped, the document_bom will be present+ */+ documentBom?: {+ [k: string]: unknown;+ };+ /**+ * The id of the document family this document belongs to+ */+ documentFamilyId?: number | null;+ /**+ * The document id+ */+ documentId: string;+ /**+ * The name of the document+ */+ documentName: string;+ /**+ * The version of the document+ * This could be the document_instance_id or document_bom_id depending on+ * the file type+ */+ documentVersionId: number;+ /**+ * The file type of the document (file extension)+ */+ fileType?: string | null;+ /**+ * The modification data for the document instance.+ * This is only used for PDF documents.+ */+ modificationData?: {+ [k: string]: unknown;+ };+ /**+ * The owner of the document+ */+ owner: string;+ /**+ * The id of the project that this document belongs to+ */+ projectId?: string | null;+ /**+ * The name of the project that this document belongs to+ */+ projectName?: string | null;+ /**+ * If the document is a PDF, this is the SHA of the pdf+ * If the document is a DOCX, this will not be present+ */+ sha?: string | null;+ /**+ * The sub type of the document if present.+ */+ subType?: DocumentSubType | null;+ /**+ * The time the document instance / document BOM was updated+ */+ updatedAt?: string | null;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Retrieve a documents metadata*/@@ -1277,129 +1280,32 @@ export interface ReadMetadata {*/documentId: string;}--/* eslint-disable */+export interface ReadMetadataResponse {+ documentMetadata: ReadDocumentMetadata;+ userAccessLevel: AccessLevel;+}+export interface ReadResponse {+ content: ReadThreadReadContent;+}/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * Retrieve an email thread and its messages. Returns the thread metadata and message contents including sender, recipients, subject, and body text. Use this to read the contents of a specific email conversation.*/--export interface ReadMetadataResponse {+export interface GetThread {/**- * The metadata of the document- */- documentMetadata: {- /**- * If the document is a "task" the branch name of the document will be provided.- */- branchName?: string | null;- /**- * The id of the document this document branched from- */- branchedFromId?: string | null;- /**- * The id of the version this document branched from- * This could be either DocumentInstance or DocumentBom id depending on- * the file type- */- branchedFromVersionId?: number | null;- /**- * The time the document was created- */- createdAt?: string | null;- /**- * The time the document was deleted- */- deletedAt?: string | null;- /**- * If the document is a DOCX document and unzipped, the document_bom will be present- */- documentBom?: {- [k: string]: unknown;- };- /**- * The id of the document family this document belongs to- */- documentFamilyId?: number | null;- /**- * The document id- */- documentId: string;- /**- * The name of the document- */- documentName: string;- /**- * The version of the document- * This could be the document_instance_id or document_bom_id depending on- * the file type- */- documentVersionId: number;- /**- * The file type of the document (file extension)- */- fileType?: string | null;- /**- * The modification data for the document instance.- * This is only used for PDF documents.- */- modificationData?: {- [k: string]: unknown;- };- /**- * The owner of the document- */- owner: string;- /**- * The id of the project that this document belongs to- */- projectId?: string | null;- /**- * The name of the project that this document belongs to- */- projectName?: string | null;- /**- * If the document is a PDF, this is the SHA of the pdf- * If the document is a DOCX, this will not be present- */- sha?: string | null;- /**- * The sub type of the document if present.- */- subType?: 'task' | null;- /**- * The time the document instance / document BOM was updated- */- updatedAt?: string | null;- };+ * Maximum number of messages to return (default 10).+ */+ limit?: number | null;/**- * The users level of access to the document+ * The ID of the email thread to retrieve.*/- userAccessLevel: 'view' | 'comment' | 'edit' | 'owner';+ threadId: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Read threaded content by ID(s). Supports reading channels, chats, and projects by their respective IDs. Use this tool when you need to retrieve the full content of a specific item(s). For documents, use ReadContent or ReadMetadata instead.* Channel transcripts only include the latest 150 messages. Use 'messages_since' to see messages in a different time window.*/export interface ReadThread {- /**- * The type of content to read. Choose based on the type of content you want to retrieve.- */- contentType:- | 'channel'- | 'channel-message'- | 'chat-thread'- | 'chat-message'- | 'project';+ contentType: ContentType;/*** ID(s) of the content to read. IMPORTANT: channel-message, chat-message, and content types support MULTIPLE ids! For all other content types (channel, chat-thread) provide a single id.*/@@ -1407,49 +1313,11 @@ export interface ReadThread {/*** A local datetime of the earliest message to include in a channel transcript following ISO 8601 format, only applicable to channels*/- messagesSince: string | null;+ messagesSince?: string | null;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */--export interface ReadResponse {- content:- | {- channel_id: string;- channel_name?: string | null;- transcript: string;- type: 'channel';- }- | {- conversation: {- chat_id: string;- messages: {- attachmentIds: string[];- content: string;- date: string;- }[];- title: string;- }[];- type: 'chat';- }- | {- formatted_preview: string;- type: 'itemPreviews';- };+export interface SearchToolResponse {+ results: UnifiedSearchResponseItem[];}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Compose and send an email. Creates the message and immediately queues it for delivery. To reply to an existing message, provide the replying_to_id. Write the body in Markdown — use **bold**, *italics*, lists, links, and other standard Markdown formatting. The draft composer renders the Markdown for the user to review and edit; the composer produces HTML that is sent as the actual email body.*/@@ -1457,105 +1325,32 @@ export interface SendEmail {/*** Blind carbon copy recipients (optional).*/- bcc: {- /**- * The recipient's email address.- */- email: string;- /**- * The recipient's display name (optional).- */- name: string | null;- }[];- /**- * The body of the email. Written as Markdown by the AI and rendered in- * the draft composer. At send time the frontend replaces this with the- * base64url-encoded HTML produced by the composer, which is what gets- * sent to recipients.- */- body: string;- /**- * Carbon copy recipients (optional).- */- cc: {- /**- * The recipient's email address.- */- email: string;- /**- * The recipient's display name (optional).- */- name: string | null;- }[];- /**- * The ID of a message to reply to (optional). When set, the email is- * sent as a reply within the same thread.- */- replyingToId: string | null;- /**- * The subject line of the email.- */- subject: string;+ bcc?: EmailRecipient[];/**- * The primary recipients (To field).- */- to: {- /**- * The recipient's email address.- */- email: string;- /**- * The recipient's display name (optional).- */- name: string | null;- }[];-}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */--/**- * User tools are pending until a user executes them- */-export type UserToolResponse =- | 'PendingUserExecution'- | 'Rejected'- | {- /**- * Response from the SendEmail tool.- */- UserAction:- | 'userEdited'- | {- sent: {- /**- * The database ID of the sent message.- */- message_id: string;- /**- * The thread ID the message belongs to.- */- thread_id: string;- };- }- | {- convertedToDraft: {- draft_id: string;- };- };- };--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-+ * The body of the email. Written as Markdown by the AI and rendered in+ * the draft composer. At send time the frontend replaces this with the+ * base64url-encoded HTML produced by the composer, which is what gets+ * sent to recipients.+ */+ body: string;+ /**+ * Carbon copy recipients (optional).+ */+ cc?: EmailRecipient[];+ /**+ * The ID of a message to reply to (optional). When set, the email is+ * sent as a reply within the same thread.+ */+ replyingToId?: string | null;+ /**+ * The subject line of the email.+ */+ subject: string;+ /**+ * The primary recipients (To field).+ */+ to: EmailRecipient[];+}/*** Set or update a property value on an entity (document, task, project, etc.). Provide the property_definition_id and exactly one value field matching the property's data type.*@@ -1574,11 +1369,11 @@ export interface SetEntityProperty {/*** For boolean properties.*/- boolean_value: boolean | null;+ boolean_value?: boolean | null;/*** For date properties (ISO 8601 date-time).*/- date_value: string | null;+ date_value?: string | null;/*** The ID of the entity to update.*/@@ -1586,64 +1381,32 @@ export interface SetEntityProperty {/*** For single entity reference properties.*/- entity_ref: {- entityId: string;- entityType:- | 'document'- | 'task'- | 'project'- | 'chat'- | 'thread'- | 'channel'- | 'user';- } | null;+ entity_ref?: ToolEntityRef | null;/*** For multi entity reference properties.*/- entity_refs:- | {- entityId: string;- entityType:- | 'document'- | 'task'- | 'project'- | 'chat'- | 'thread'- | 'channel'- | 'user';- }[]- | null;- /**- * The type of entity.- */- entity_type:- | 'document'- | 'task'- | 'project'- | 'chat'- | 'thread'- | 'channel'- | 'user';+ entity_refs?: ToolEntityRef[] | null;+ entity_type: ToolEntityType;/*** For single link properties.*/- link_url: string | null;+ link_url?: string | null;/*** For multi link properties.*/- link_urls: string[] | null;+ link_urls?: string[] | null;/*** For number properties.*/- number_value: number | null;+ number_value?: number | null;/*** For single-select properties. The option UUID from available options.*/- option_id: string | null;+ option_id?: string | null;/*** For multi-select properties. The option UUIDs from available options.*/- option_ids: string[] | null;+ option_ids?: string[] | null;/*** The property definition ID. Get this from GetEntityProperties results.*/@@ -1651,16 +1414,12 @@ export interface SetEntityProperty {/*** For string properties.*/- string_value: string | null;+ string_value?: string | null;+}+export interface ToolEntityRef {+ entityId: string;+ entityType: ToolEntityType;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Response from the SetEntityProperty tool.*/@@ -1668,14 +1427,6 @@ export interface SetEntityPropertyResponse {message: string;success: boolean;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, and call tools. Use this for tasks that require multiple tool calls or independent research.*/@@ -1685,85 +1436,9 @@ export interface Subagent {*/task: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-export interface SubagentResponse {result: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */--/**- * The expected shape of the streamed JSON following a `server_tool_use` for text_editor_code_execution- */-export interface TextEditorCodeExecutionToolCall {- /**- * The command to execute: "view", "create", or "str_replace"- */- command: string;- /**- * File content for create operations- */- file_text?: string | null;- /**- * Replacement string for str_replace operations- */- new_str?: string | null;- /**- * String to find for str_replace operations- */- old_str?: string | null;- /**- * Path to the file- */- path: string;-}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */--/**- * Content of a text editor code execution response - either a result or an error- */-export type TextEditorCodeExecutionContent =- | (TextEditorCodeExecutionResult & {- type: 'text_editor_code_execution_view_result';- })- | (TextEditorCodeExecutionResult & {- type: 'text_editor_code_execution_create_result';- })- | (TextEditorCodeExecutionResult & {- type: 'text_editor_code_execution_str_replace_result';- })- | (TextEditorCodeExecutionToolError & {- type: 'text_editor_code_execution_tool_result_error';- });-/**- * Error codes for code execution failures- */--/**- * Response from text_editor_code_execution tool- */-export interface TextEditorCodeExecutionResponse {- content: TextEditorCodeExecutionContent;- tool_use_id: string;-}/*** Result from text editor operations (view, create, str_replace)* Fields are optional as different operations return different fields@@ -1820,14 +1495,38 @@ export interface TextEditorCodeExecutionResult {export interface TextEditorCodeExecutionToolError {error_code: CodeExecutionErrorCode;}--/* eslint-disable *//**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.+ * Response from text_editor_code_execution tool*/-+export interface TextEditorCodeExecutionResponse {+ content: TextEditorCodeExecutionContent;+ tool_use_id: string;+}+/**+ * The expected shape of the streamed JSON following a `server_tool_use` for text_editor_code_execution+ */+export interface TextEditorCodeExecutionToolCall {+ /**+ * The command to execute: "view", "create", or "str_replace"+ */+ command: string;+ /**+ * File content for create operations+ */+ file_text?: string | null;+ /**+ * Replacement string for str_replace operations+ */+ new_str?: string | null;+ /**+ * String to find for str_replace operations+ */+ old_str?: string | null;+ /**+ * Path to the file+ */+ path: string;+}/*** Add or remove a label from all messages in an email thread. Use ListLabels first to get valid label IDs. Set `add` to true to apply the label, or false to remove it.*/@@ -1845,14 +1544,6 @@ export interface UpdateThreadLabels {*/thread_id: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/*** Response from the UpdateThreadLabels tool.*/@@ -1870,58 +1561,6 @@ export interface UpdateThreadLabelsResponse {*/summary: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */--/**- * The expected shape of the streamed JSON following a `server_tool_use` in content_block_start event- */-export interface WebFetchToolCall {- url: string;-}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */--/**- * Content of a web fetch response - either a successful result or an error- */-export type WebFetchContent =- | (WebFetchResult & {- type: 'web_fetch_result';- })- | (WebFetchToolError & {- type: 'web_fetch_tool_result_error';- });-/**- * Possible error codes for web fetch failures- */-export type WebFetchErrorCode =- | 'invalid_input'- | 'url_too_long'- | 'url_not_allowed'- | 'url_not_accessible'- | 'too_many_requests'- | 'unsupported_content_type'- | 'max_uses_exceeded'- | 'unavailable';--/**- * Web fetch tool response content returned by Claude when using the web_fetch tool- */-export interface WebFetchResponse {- content: WebFetchContent;- tool_use_id: string;-}/*** Successful web fetch result containing the fetched content*/@@ -1937,75 +1576,38 @@ export interface WebFetchResult {url: string;}/**- * The fetched document content+ * Document content from a web fetch*/export interface WebFetchDocument {/*** Optional citations configuration*/citations?: CitationsConfig | null;- /**- * The source content (text or base64)- */- source:- | {- data: string;- media_type: string;- type: 'text';- }- | {- data: string;- media_type: string;- type: 'base64';- };+ source: WebFetchSource;/*** Optional title of the document*/title?: string | null;}-/**- * Citations configuration for web fetch- */-export interface CitationsConfig {- enabled: boolean;-}/*** Error returned when web fetch fails*/export interface WebFetchToolError {error_code: WebFetchErrorCode;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/**- * This is the expected shape of the streamed json following a `server_tool_use` in content_block_start event+ * Web fetch tool response content returned by Claude when using the web_fetch tool*/-export interface WebSearchToolCall {- query: string;+export interface WebFetchResponse {+ content: WebFetchContent;+ tool_use_id: string;}--/* eslint-disable */-/**- * This file was automatically generated by json-schema-to-typescript.- * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,- * and run json-schema-to-typescript to regenerate this file.- */-/**- * A single search result from web search+ * The expected shape of the streamed JSON following a `server_tool_use` in content_block_start event*/-export type SearchResult = {- title: string;- type: 'web_search_result';+export interface WebFetchToolCall {url: string;-};-+}/*** Web search response content returned by Claude when using the web_search tool*/@@ -2017,3 +1619,9 @@ export interface WebSearchResponse {content: SearchResult[];tool_use_id: string;}+/**+ * This is the expected shape of the streamed json following a `server_tool_use` in content_block_start event+ */+export interface WebSearchToolCall {+ query: string;+}diff --git a/js/app/scripts/generate-dcs-tools.ts b/js/app/scripts/generate-dcs-tools.tsindex e242c20ffd..deac55b1c6 100644--- a/js/app/scripts/generate-dcs-tools.ts+++ b/js/app/scripts/generate-dcs-tools.ts@@ -6,9 +6,8 @@import { mkdir, readFile } from 'node:fs/promises';import * as path from 'node:path';-import { join } from 'node:path';import { $ } from 'bun';-import { resolveRefs } from 'json-refs';+import $RefParser from '@apidevtools/json-schema-ref-parser';import { compile } from 'json-schema-to-typescript';import { jsonSchemaToZod } from 'json-schema-to-zod';import { z } from 'zod';@@ -21,92 +20,42 @@ const rustCloudStorageDir = path.resolve(const aiToolsDir = path.join(rustCloudStorageDir, 'ai_tools');const schemasJsonPath = path.join(aiToolsDir, 'schemas', 'tools.json');-/**- * Pre-process JSON Schema to convert $ref with sibling properties into allOf.- * json-refs doesn't properly merge $ref with sibling keywords (properties, required, etc.),- * so we need to restructure the schema to use allOf for proper composition.- */-function preprocessSchemaForRefs(schema: unknown): unknown {- if (schema === null || typeof schema !== 'object') {- return schema;- }-- if (Array.isArray(schema)) {- return schema.map(preprocessSchemaForRefs);- }-- const obj = schema as Record<string, unknown>;- const result: Record<string, unknown> = {};-- // Check if this object has $ref along with other schema keywords- if ('$ref' in obj) {- const siblingKeys = Object.keys(obj).filter(- (k) => k !== '$ref' && k !== '$schema' && k !== 'description'- );-- if (siblingKeys.length > 0) {- // Convert to allOf structure: merge $ref schema with sibling properties- const refPart = { $ref: obj.$ref };- const siblingPart: Record<string, unknown> = {};-- for (const key of siblingKeys) {- siblingPart[key] = preprocessSchemaForRefs(obj[key]);- }-- // Keep description at top level if present- if ('description' in obj) {- result.description = obj.description;- }-- result.allOf = [refPart, siblingPart];- return result;- }- }-- // Recursively process all properties- for (const [key, value] of Object.entries(obj)) {- result[key] = preprocessSchemaForRefs(value);- }-- return result;-}-const serviceDir = path.resolve(import.meta.dirname,documentCognitionBase.output);-const outputDir = join(serviceDir, 'generated', 'tools');-const schemasFile = join(outputDir, 'schemas.ts');-const typesFile = join(outputDir, 'types.ts');-const toolFile = join(outputDir, 'tool.ts');+const outputDir = path.join(serviceDir, 'generated', 'tools');+const schemasFile = path.join(outputDir, 'schemas.ts');+const typesFile = path.join(outputDir, 'types.ts');+const toolFile = path.join(outputDir, 'tool.ts');await $`rm ${schemasFile} ${toolFile} ${typesFile}|| true`;const warning = `/* Generated by scripts/generate-dcs-tools.ts- * *DO NOT EDIT MANUALLY*- *-*/`;+ * *DO NOT EDIT MANUALLY*+ */`;await mkdir(outputDir, { recursive: true });-const AiToolsResponseSchema = z.object({- schemas: z.array(+// The combined schema has shared $defs and a tools array+const CombinedSchemaValidator = z.object({+ $defs: z.record(z.any()),+ tools: z.array(z.object({name: z.string(),- inputSchema: z.any(),- outputSchema: z.any(),+ input: z.string(),+ output: z.string(),})),});-type AiToolsResponse = z.infer<typeof AiToolsResponseSchema>['schemas'];+type CombinedSchema = z.infer<typeof CombinedSchemaValidator>;async function buildAndRunSchemaGenerator(): Promise<void> {console.log('Building gen_tool_schemas binary...');await $`cd ${rustCloudStorageDir} && SQLX_OFFLINE=true cargo build --bin gen_tool_schemas`;console.log('Build complete.');- // Remove existing schemas dir if it exists (the binary expects to create it)await $`rm -rf ${path.join(aiToolsDir, 'schemas')}`.quiet();console.log('Running gen_tool_schemas...');@@ -120,201 +69,87 @@ async function buildAndRunSchemaGenerator(): Promise<void> {console.log('Schema generation complete.');}-async function fetchAIToolsSchemas(): Promise<AiToolsResponse> {- try {- // Build and run the Rust binary to generate schemas- await buildAndRunSchemaGenerator();-- const data = await readFile(schemasJsonPath, 'utf-8');- const parsed = AiToolsResponseSchema.parse(JSON.parse(data));- console.log(`Successfully loaded ${parsed.schemas.length} AI tool schemas`);- return parsed.schemas;- } catch (error) {- console.error('Failed to load AI tools schemas:', error);- throw error;- }+async function loadCombinedSchema(): Promise<CombinedSchema> {+ await buildAndRunSchemaGenerator();+ const data = await readFile(schemasJsonPath, 'utf-8');+ const parsed = CombinedSchemaValidator.parse(JSON.parse(data));+ console.log(+ `Loaded ${parsed.tools.length} tools, ${Object.keys(parsed.$defs).length} definitions`+ );+ return parsed;}-async function generateSchemasFile(tools: AiToolsResponse) {- // Generate all schemas, deduplicating by title- const generatedSchemas = new Set<string>();- const content: Array<string> = [];-- for (const tool of tools) {- // jsonSchemaToZod with name option generates a proper export- // Preprocess to handle $ref with sibling properties- const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);- const { resolved: inputSchema } = await resolveRefs(preprocessedInput);- if (!generatedSchemas.has(inputSchema.title)) {- const inputCode = jsonSchemaToZod(inputSchema, {- module: 'esm',- name: inputSchema.title,- withoutDescribes: true,- noImport: true,- });- content.push(inputCode);- generatedSchemas.add(inputSchema.title);- }-- const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);- const { resolved: outputSchema } = await resolveRefs(preprocessedOutput);- if (!generatedSchemas.has(outputSchema.title)) {- const outputCode = jsonSchemaToZod(outputSchema, {- module: 'esm',- name: outputSchema.title,- withoutDescribes: true,- noImport: true,- });- content.push(outputCode);- generatedSchemas.add(outputSchema.title);+async function generateSchemasFile(schema: CombinedSchema) {+ const resolved = await $RefParser.dereference(structuredClone(schema));+ const defs = (resolved as Record<string, unknown>).$defs as Record<+ string,+ unknown+ >;+ const seen = new Set<string>();+ const content: string[] = [];++ for (const tool of schema.tools) {+ for (const defName of [tool.input, tool.output]) {+ if (seen.has(defName)) continue;+ seen.add(defName);++ const resolvedDef = defs[defName];+ const schemaWithTitle = { ...resolvedDef, title: defName };++ content.push(+ jsonSchemaToZod(schemaWithTitle, {+ module: 'esm',+ name: defName,+ withoutDescribes: true,+ noImport: true,+ })+ );}}- const contents = `${warning}-import { z } from 'zod';--${content.join('\n\n')}-`;-- await Bun.write(schemasFile, contents);+ await Bun.write(+ schemasFile,+ `${warning}\nimport { z } from 'zod';\n\n${content.join('\n\n')}\n`+ );}-/**- * Remove duplicate type/interface declarations from generated TypeScript code.- * json-schema-to-typescript generates nested types inline, which can cause duplicates- * when multiple schemas reference the same type.- */-function deduplicateTypes(code: string): string {- const seenTypes = new Set<string>();- const lines = code.split('\n');- const result: string[] = [];- let skipUntilNextExport = false;- let braceCount = 0;-- for (let i = 0; i < lines.length; i++) {- const line = lines[i];-- // Check if we're starting a new export type or interface- const typeMatch = line.match(- /^export\s+(type|interface)\s+(\w+)(?:\s*=|\s*\{|\s*$)/- );-- if (typeMatch && !skipUntilNextExport) {- const typeName = typeMatch[2];-- if (seenTypes.has(typeName)) {- // Skip this duplicate type definition- skipUntilNextExport = true;- braceCount = 0;- // Count opening braces on this line- braceCount += (line.match(/\{/g) || []).length;- braceCount -= (line.match(/\}/g) || []).length;- // If it's a type alias (ends with ;), skip just this line- if (line.includes(';') && braceCount === 0) {- skipUntilNextExport = false;- }- continue;- }- seenTypes.add(typeName);- }-- if (skipUntilNextExport) {- // Count braces to know when the type/interface ends- braceCount += (line.match(/\{/g) || []).length;- braceCount -= (line.match(/\}/g) || []).length;-- // For type aliases, check if line ends with semicolon at brace level 0- if (braceCount <= 0 && (line.includes(';') || line.trim() === '}')) {- skipUntilNextExport = false;- }- continue;- }-- result.push(line);+async function generateToolTypesFile(schema: CombinedSchema) {+ const properties: Record<string, unknown> = {};+ for (const key of Object.keys(schema.$defs)) {+ properties[key] = { $ref: `#/$defs/${key}` };}- return result.join('\n');-}--async function generateToolTypesFile(tools: AiToolsResponse) {- // Generate all schemas, deduplicating by title- const generatedTypes = new Set<string>();- const content: Array<string> = [];-- for (const tool of tools) {- // Preprocess to handle $ref with sibling properties- const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);- if (!generatedTypes.has(tool.inputSchema.title)) {- const inputCode = await compile(- preprocessedInput,- tool.inputSchema.title,- {- // override top level name for export- customName: (schema) => {- if (schema.title) {- console.log(`Using schema title: ${schema.title}`);- return schema.title;- }- },- additionalProperties: false,- style: {- singleQuote: true,- },- }- );- content.push(inputCode);- generatedTypes.add(tool.inputSchema.title);- }-- const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);- if (!generatedTypes.has(tool.outputSchema.title)) {- const outputCode = await compile(- preprocessedOutput,- tool.outputSchema.title,- {- // override top level name for export- customName: (schema) => {- if (schema.title) {- console.log(`Using schema title: ${schema.title}`);- return schema.title;- }- return undefined;- },- additionalProperties: false,- style: {- singleQuote: true,- },- }- );- content.push(outputCode);- generatedTypes.add(tool.outputSchema.title);+ const code = await compile(+ {+ $defs: schema.$defs,+ type: 'object',+ properties,+ additionalProperties: false,+ },+ 'AllToolTypes',+ {+ additionalProperties: false,+ style: { singleQuote: true },}- }+ );- // Deduplicate nested types that may have been generated multiple times- const rawContents = `${warning}-${content.join('\n\n')}-`;- const deduplicatedContents = deduplicateTypes(rawContents);+ // Strip the root wrapper interface — we only want the definition types+ const cleaned = code.replace(+ /export interface AllToolTypes\s*\{[\s\S]*?\n\}\n*/,+ ''+ );- await Bun.write(typesFile, deduplicatedContents);+ await Bun.write(typesFile, `${warning}\n${cleaned}`);}-async function generateToolsFile(tools: AiToolsResponse) {- // Resolve schemas to get titles- const toolsWithTitles = await Promise.all(- tools.map(async (tool) => {- const preprocessedInput = preprocessSchemaForRefs(tool.inputSchema);- const preprocessedOutput = preprocessSchemaForRefs(tool.outputSchema);- const { resolved: inputSchema } = await resolveRefs(preprocessedInput);- const { resolved: outputSchema } = await resolveRefs(preprocessedOutput);- return {- name: tool.name,- inputTitle: inputSchema.title,- outputTitle: outputSchema.title,- };- })- );+async function generateToolsFile(schema: CombinedSchema) {+ const entries = schema.tools+ .map((t) => ({+ name: t.name,+ inputTitle: t.input,+ outputTitle: t.output,+ }))+ .sort((a, b) => a.name.localeCompare(b.name));const contents = `${warning}@@ -323,19 +158,19 @@ import * as schemas from './schemas';import type * as types from './types';type ToolParserMap = {-${toolsWithTitles+${entries.map(- (tool) =>- `${tool.name}: { call: types.${tool.inputTitle}, response: types.${tool.outputTitle} }`+ (t) =>+ `${t.name}: { call: types.${t.inputTitle}, response: types.${t.outputTitle} }`).join('\n')}};const toolParserMap = {-${toolsWithTitles+${entries.map(- (tool) =>- `${tool.name}: { call: schemas.${tool.inputTitle}, response: schemas.${tool.outputTitle} }`+ (t) =>+ `${t.name}: { call: schemas.${t.inputTitle}, response: schemas.${t.outputTitle} }`).join(',\n')}};@@ -349,10 +184,10 @@ type NamedRawTool = {};type ToolDataMap = {-${toolsWithTitles+${entries.map(- (tool) =>- `${tool.name}: { call: types.${tool.inputTitle}, response: types.${tool.outputTitle} }`+ (t) =>+ `${t.name}: { call: types.${t.inputTitle}, response: types.${t.outputTitle} }`).join(';\n')};};@@ -400,16 +235,13 @@ export function deserializeToolResponse(await Bun.write(toolFile, contents);}-// Fetch AI tools schemas-const tools = await fetchAIToolsSchemas();-// Sort tools by name to maintain consistent order-tools.sort((a, b) => a.name.localeCompare(b.name));-// write types-await generateSchemasFile(tools);-await generateToolsFile(tools);-await generateToolTypesFile(tools);+const schema = await loadCombinedSchema();++await generateSchemasFile(schema);+await generateToolsFile(schema);+await generateToolTypesFile(schema);+// On NixOS, the npm-installed biome binary doesn't work due to dynamic linking issues.-// We detect NixOS and use the system biome instead.const isNixOS =process.env.NIX_PATH !== undefined ||((await Bun.file('/etc/os-release').exists()) &&@@ -422,8 +254,5 @@ if (isNixOS) {await $`biome format --write --no-errors-on-unmatched ${toolFile} ${schemasFile} ${typesFile}`;}-console.log(- `Generated AI tools types at: ${serviceDir}/generated/tools/tools.ts`-);-+console.log(`Generated AI tools types at: ${outputDir}`);console.log('✅ AI tools types generation completed successfully');diff --git a/js/bun.lock b/js/bun.lockindex 5a688912fb..d6f6a583b9 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -108,6 +108,7 @@"zod": "^3.23.8",},"devDependencies": {+ "@apidevtools/json-schema-ref-parser": "^15.3.5","@biomejs/biome": "2.4.12","@playwright/test": "^1.55.1","@solidjs/meta": "^0.29.4",@@ -371,7 +372,7 @@"@antfu/install-pkg": ["@antfu/[email protected]", "", { "dependencies": { "package-manager-detector": "^1.3.0", "tinyexec": "^1.0.1" } }, "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ=="],- "@apidevtools/json-schema-ref-parser": ["@apidevtools/[email protected]", "", { "dependencies": { "@jsdevtools/ono": "^7.1.3", "@types/json-schema": "^7.0.15", "js-yaml": "^4.1.0" } }, "sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ=="],+ "@apidevtools/json-schema-ref-parser": ["@apidevtools/[email protected]", "", { "dependencies": { "js-yaml": "^4.1.1" }, "peerDependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-orNOYXw3hYXxxisXMldjzjBzqqTLBPbwOtHg7ovBPvfBHDue1qM9YJENZ3W2BQuS+7z4ThogMbEzEsov57Itkg=="],"@apidevtools/openapi-schemas": ["@apidevtools/[email protected]", "", {}, "sha512-Zc1AlqrJlX3SlpupFGpiLi2EbteyP7fXmUOGup6/DnkRgjP9bgMM/ag+n91rsv0U1Gpz0H3VILA/o3bW7Ua6BQ=="],@@ -1589,7 +1590,7 @@"app": ["app@workspace:app/packages/app"],- "argparse": ["[email protected]", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],+ "argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],"aria-query": ["[email protected]", "", {}, "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw=="],@@ -2279,7 +2280,7 @@"js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],- "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg=="],+ "js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],"jsbn": ["[email protected]", "", {}, "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg=="],@@ -3175,8 +3176,6 @@"@antfu/install-pkg/tinyexec": ["[email protected]", "", {}, "sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg=="],- "@apidevtools/json-schema-ref-parser/js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],-"@apidevtools/swagger-parser/@apidevtools/json-schema-ref-parser": ["@apidevtools/[email protected]", "", { "dependencies": { "@types/json-schema": "^7.0.15", "js-yaml": "^4.1.0" } }, "sha512-Oc96zvmxx1fqoSEdUmfmvvb59/KDOnUoJ7s2t7bISyAn0XEz57LCCw8k2Y4Pf3mwKaZLMciESALORLgfe2frCw=="],"@asamuzakjp/css-color/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],@@ -3293,8 +3292,6 @@"@eslint-community/eslint-utils/eslint-visitor-keys": ["[email protected]", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],- "@eslint/eslintrc/js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],-"@eslint/eslintrc/strip-json-comments": ["[email protected]", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],"@google-cloud/common/google-auth-library": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^6.1.1", "gcp-metadata": "^6.1.0", "gtoken": "^7.0.0", "jws": "^4.0.0" } }, "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng=="],@@ -3427,8 +3424,6 @@"chalk/supports-color": ["[email protected]", "", {}, "sha512-KKNVtd6pCYgPIKU4cp2733HWYCpplQhddZLBUryaAHou723x+FRzQ5Df824Fj+IyyuiQTRoub4SnIFfIcrp70g=="],- "chanfana/js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],-"cliui/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],"concurrently/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],@@ -3495,7 +3490,9 @@"json-refs/commander": ["[email protected]", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="],- "json-schema-to-typescript/js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],+ "json-refs/js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg=="],++ "json-schema-to-typescript/@apidevtools/json-schema-ref-parser": ["@apidevtools/[email protected]", "", { "dependencies": { "@jsdevtools/ono": "^7.1.3", "@types/json-schema": "^7.0.15", "js-yaml": "^4.1.0" } }, "sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ=="],"katex/commander": ["[email protected]", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="],@@ -3513,8 +3510,6 @@"make-dir/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],- "markdown-it/argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],-"markdown-it/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],"micromatch/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],@@ -3541,8 +3536,6 @@"orval/commander": ["[email protected]", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="],- "orval/js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],-"orval/typedoc": ["[email protected]", "", { "dependencies": { "@gerrit0/mini-shiki": "^3.23.0", "lunr": "^2.3.9", "markdown-it": "^14.1.1", "minimatch": "^10.2.5", "yaml": "^2.8.3" }, "peerDependencies": { "typescript": "5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x" }, "bin": { "typedoc": "bin/typedoc" } }, "sha512-wKh+lhdmMFivMlc6vRRcMGXeGEHGU2g8a2CkPTJjJlwRf1iXbimWIPcFolCqe4E0d/FRtGszpIrsp3WLpDB8Pw=="],"path-scurry/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],@@ -3641,10 +3634,6 @@"yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],- "@apidevtools/json-schema-ref-parser/js-yaml/argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],-- "@apidevtools/swagger-parser/@apidevtools/json-schema-ref-parser/js-yaml": ["[email protected]", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],-"@aws-sdk/client-cloudwatch-logs/@smithy/util-retry/@smithy/service-error-classification": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/types": "^4.14.1" } }, "sha512-9jKsBYQRPR0xBLgc2415RsA5PIcP2sis4oBdN9s0D13cg1B1284mNTjx9Yc+BEERXzuPm5ObktI96OxsKh8E9A=="],"@aws-sdk/client-cloudwatch-logs/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/is-array-buffer": "^4.2.2", "tslib": "^2.6.2" } }, "sha512-FDXD7cvUoFWwN6vtQfEta540Y/YBe5JneK3SoZg9bThSoOAC/eGeYEua6RkBgKjGa/sz6Y+DuBZj3+YEY21y4Q=="],@@ -3771,7 +3760,7 @@"@datadog/datadog-ci/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],- "@eslint/eslintrc/js-yaml/argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],+ "@datadog/datadog-ci/js-yaml/argparse": ["[email protected]", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],"@google-cloud/common/google-auth-library/gaxios": ["[email protected]", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "is-stream": "^2.0.0", "node-fetch": "^2.6.9", "uuid": "^9.0.1" } }, "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ=="],@@ -3823,8 +3812,6 @@"@vitest/ui/@vitest/utils/@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-7I3q6l5qr03dVfMX2wCo9FxwSJbPdwKjy2uu/YPpU3wfHvIL4QHwVRp57OfGrDFeUJ8/8QdfBKIV12FTtLn00g=="],- "chanfana/js-yaml/argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],-"concurrently/chalk/ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],"concurrently/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],@@ -3867,7 +3854,7 @@"jest-diff/pretty-format/react-is": ["[email protected]", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],- "json-schema-to-typescript/js-yaml/argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],+ "json-refs/js-yaml/argparse": ["[email protected]", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="],"lexical-service/@types/node/undici-types": ["[email protected]", "", {}, "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg=="],@@ -3891,8 +3878,6 @@"orval/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],- "orval/js-yaml/argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],-"pkg-dir/find-up/locate-path": ["[email protected]", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="],"rollup-plugin-typescript2/@rollup/pluginutils/picomatch": ["[email protected]", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],@@ -4005,8 +3990,6 @@"wrangler/esbuild/@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA=="],- "@apidevtools/swagger-parser/@apidevtools/json-schema-ref-parser/js-yaml/argparse": ["[email protected]", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],-"@aws-sdk/client-cloudwatch-logs/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-n6rQ4N8Jj4YTQO3YFrlgZuwKodf4zUFs7EJIWH86pSCWBaAtAGBFfCM7Wx6D2bBJ2xqFNxGBSrUWswT3M0VJow=="],"@aws-sdk/client-cognito-identity/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-n6rQ4N8Jj4YTQO3YFrlgZuwKodf4zUFs7EJIWH86pSCWBaAtAGBFfCM7Wx6D2bBJ2xqFNxGBSrUWswT3M0VJow=="],diff --git a/package.json b/package.jsonnew file mode 100644index 0000000000..434a43d751--- /dev/null+++ b/package.json@@ -0,0 +1,6 @@+{+ "dependencies": {},+ "devDependencies": {+ "@apidevtools/json-schema-ref-parser": "^15.3.5"+ }+}\ No newline at end of filediff --git a/rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rs b/rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rsindex 0d790224bd..b7b5f32928 100644--- a/rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rs+++ b/rust/cloud-storage/ai_tools/src/bin/gen_tool_schemas.rs@@ -1,8 +1,9 @@-//! Binary to generate tool schemas JSON file.+//! Binary to generate combined tool schemas JSON file.fn main() {- let schemas = ai_tools::all_tool_schemas();- let json = serde_json::to_string_pretty(&schemas).expect("serialize schemas");+ let mut combined = ai_tools::all_tool_combined_schema();+ combined.mangle_collisions();+ let json = serde_json::to_string_pretty(&combined).expect("serialize schemas");std::fs::create_dir("schemas").expect("create schemas dir");std::fs::write("schemas/tools.json", &json).expect("write tools.json");println!("Generated ai_tools/schemas/tools.json");diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rsindex 5878e23730..3c85bf5eb9 100644--- a/rust/cloud-storage/ai_tools/src/lib.rs+++ b/rust/cloud-storage/ai_tools/src/lib.rs@@ -1,7 +1,7 @@#![recursion_limit = "256"]use ai_toolset::AsyncToolSet;-use ai_toolset::schema::{ToolSchemaGenerator, ToolSchemas};+use ai_toolset::schema::{CombinedToolSchemas, ToolSchemaGenerator};mod build_context;pub mod code_execution;pub mod prompts;@@ -41,6 +41,13 @@ impl ToolSchemaGenerator for ToolSetWithPrompt {fn generate_schemas(&self) -> ai_toolset::schema::ToolSchemas {self.toolset.generate_schemas()}++ fn register_schemas(+ &self,+ generator: &mut schemars::SchemaGenerator,+ ) -> Vec<ai_toolset::schema::CombinedToolEntry> {+ self.toolset.register_schemas(generator)+ }}/// Toolset available to subagents — everything except email and the Subagent@@ -65,15 +72,28 @@ pub fn all_tools() -> ToolSetWithPrompt {ToolSetWithPrompt { toolset, prompt }}-/// These are used to generate schemas for the frontend-/// See [ai_toolset::schema::PhantomTool]-pub fn all_tool_schemas() -> ToolSchemas {- all_tools()- .merge(&*anthropic_web_search_tool)- .merge(&*anthropic_web_fetch_tool)- .merge(&*anthropic_bash_code_execution_tool)- .merge(&*anthropic_text_editor_code_execution_tool)- .generate_schemas()+/// Combined schema with shared, deduplicated `$defs`.+///+/// Uses a single [`schemars::SchemaGenerator`] so types referenced by+/// multiple tools (e.g. `CodeExecutionErrorCode`) appear exactly once.+pub fn all_tool_combined_schema() -> CombinedToolSchemas {+ use ai_toolset::schema::NormaliseRefSiblings;+ use schemars::transform::RecursiveTransform;++ let mut generator = schemars::generate::SchemaSettings::draft2020_12()+ .with(|s| s.meta_schema = None)+ .with_transform(RecursiveTransform(NormaliseRefSiblings))+ .into_generator();++ let mut tools = Vec::new();+ tools.extend(all_tools().register_schemas(&mut generator));+ tools.extend(anthropic_web_search_tool.register_schemas(&mut generator));+ tools.extend(anthropic_web_fetch_tool.register_schemas(&mut generator));+ tools.extend(anthropic_bash_code_execution_tool.register_schemas(&mut generator));+ tools.extend(anthropic_text_editor_code_execution_tool.register_schemas(&mut generator));++ let defs = generator.take_definitions(true);+ CombinedToolSchemas { defs, tools }}pub fn no_tools() -> ToolSetWithPrompt {diff --git a/rust/cloud-storage/ai_toolset/src/schema/generate.rs b/rust/cloud-storage/ai_toolset/src/schema/generate.rsindex 0fecb16a9e..d019de77d8 100644--- a/rust/cloud-storage/ai_toolset/src/schema/generate.rs+++ b/rust/cloud-storage/ai_toolset/src/schema/generate.rs@@ -1,7 +1,71 @@use crate::AsyncToolSet;+use schemars::Schema;+use schemars::transform::Transform;use serde::{Deserialize, Serialize};use utoipa::ToSchema;+/// Normalises `$ref` nodes that carry sibling keywords.+///+/// Downstream TS tooling (`json-schema-to-typescript`) predates Draft 2020-12+/// and doesn't merge `$ref` with sibling keywords. This [`schemars::Transform`]+/// rewrites those nodes so the output is consumable:+///+/// * `$ref` + `description` only → drops the description (the referenced type+/// already carries its own).+/// * `$ref` + structural siblings (`properties`, `required`, …) → rewrites to+/// `allOf` so the intersection is explicit.+#[derive(Debug, Clone)]+pub struct NormaliseRefSiblings;++impl Transform for NormaliseRefSiblings {+ fn transform(&mut self, schema: &mut Schema) {+ let Some(obj) = schema.as_object_mut() else {+ return;+ };+ if !obj.contains_key("$ref") {+ return;+ }++ let sibling_keys: Vec<String> = obj+ .keys()+ .filter(|k| *k != "$ref" && *k != "$schema")+ .cloned()+ .collect();++ if sibling_keys.is_empty() {+ return;+ }++ if sibling_keys == ["description"] {+ obj.remove("description");+ return;+ }++ let ref_val = obj.remove("$ref").unwrap();+ let mut ref_part = serde_json::Map::new();+ ref_part.insert("$ref".to_string(), ref_val);++ let mut sibling_part = serde_json::Map::new();+ for key in &sibling_keys {+ if key == "description" {+ continue;+ }+ if let Some(val) = obj.remove(key) {+ sibling_part.insert(key.clone(), val);+ }+ }+ obj.remove("description");++ obj.insert(+ "allOf".to_string(),+ serde_json::json!([+ serde_json::Value::Object(ref_part),+ serde_json::Value::Object(sibling_part),+ ]),+ );+ }+}+/// Schema information for a single tool, serializable for API responses.#[derive(Serialize, Deserialize, Clone, ToSchema)]#[serde(rename_all = "camelCase")]@@ -22,6 +86,142 @@ pub struct ToolSchemas {pub schemas: Vec<ToolSchema>,}+/// Entry in a combined schema mapping a tool name to its input/output definition names.+#[derive(Serialize, Deserialize, Clone)]+pub struct CombinedToolEntry {+ /// The tool name.+ pub name: String,+ /// The schema definition name for the tool's input.+ pub input: String,+ /// The schema definition name for the tool's output.+ pub output: String,+}++/// Combined schema with shared `$defs` and a tool→type mapping.+///+/// All tool input/output types and their transitive dependencies live in a+/// single `$defs` map, deduplicated by schemars' [`SchemaGenerator`].+#[derive(Serialize, Deserialize, Clone)]+pub struct CombinedToolSchemas {+ /// Shared JSON Schema definitions (keyed by type name).+ #[serde(rename = "$defs")]+ pub defs: serde_json::Map<String, serde_json::Value>,+ /// Tool entries referencing definitions by name.+ pub tools: Vec<CombinedToolEntry>,+}++impl CombinedToolSchemas {+ /// Replaces schemars' numeric collision suffixes (e.g. `ReadContent2`)+ /// with tool-name-prefixed names (e.g. `ReadThreadReadContent`).+ ///+ /// When two different Rust types share a `schema_name()`, schemars+ /// disambiguates with a numeric suffix. This method finds those,+ /// determines which tool references them, and renames to+ /// `{ToolName}{BaseName}` across `$defs`, `tools`, and all `$ref`s.+ pub fn mangle_collisions(&mut self) {+ let suffixed: Vec<(String, String)> = self+ .defs+ .keys()+ .filter_map(|name| {+ let base = name.trim_end_matches(|c: char| c.is_ascii_digit());+ if base.len() < name.len() && self.defs.contains_key(base) {+ Some((name.clone(), base.to_owned()))+ } else {+ None+ }+ })+ .collect();++ for (suffixed_name, base_name) in suffixed {+ let tool_name = self.find_owning_tool(&suffixed_name);+ let new_name = format!("{tool_name}{base_name}");+ let old_ref = format!("#/$defs/{suffixed_name}");+ let new_ref = format!("#/$defs/{new_name}");++ if let Some(def) = self.defs.remove(&suffixed_name) {+ self.defs.insert(new_name.clone(), def);+ }++ for tool in &mut self.tools {+ if tool.input == suffixed_name {+ tool.input = new_name.clone();+ }+ if tool.output == suffixed_name {+ tool.output = new_name.clone();+ }+ }++ Self::rename_refs(&mut self.defs, &old_ref, &new_ref);+ }+ }++ fn find_owning_tool(&self, def_name: &str) -> String {+ let ref_str = format!("#/$defs/{def_name}");++ // Check if a tool directly uses this def as input or output.+ for tool in &self.tools {+ if tool.input == def_name || tool.output == def_name {+ return tool.name.clone();+ }+ }++ // Walk each tool's input/output def tree looking for a transitive $ref.+ for tool in &self.tools {+ for root in [&tool.input, &tool.output] {+ if let Some(def) = self.defs.get(root.as_str())+ && Self::value_contains_ref(def, &ref_str)+ {+ return tool.name.clone();+ }+ }+ }++ def_name.to_owned()+ }++ fn value_contains_ref(value: &serde_json::Value, target: &str) -> bool {+ match value {+ serde_json::Value::String(s) => s == target,+ serde_json::Value::Array(arr) => {+ arr.iter().any(|v| Self::value_contains_ref(v, target))+ }+ serde_json::Value::Object(map) => {+ map.values().any(|v| Self::value_contains_ref(v, target))+ }+ _ => false,+ }+ }++ fn rename_refs(+ defs: &mut serde_json::Map<String, serde_json::Value>,+ old_ref: &str,+ new_ref: &str,+ ) {+ for value in defs.values_mut() {+ Self::rename_refs_in_value(value, old_ref, new_ref);+ }+ }++ fn rename_refs_in_value(value: &mut serde_json::Value, old_ref: &str, new_ref: &str) {+ match value {+ serde_json::Value::String(s) if s == old_ref => {+ *s = new_ref.to_owned();+ }+ serde_json::Value::Array(arr) => {+ for v in arr {+ Self::rename_refs_in_value(v, old_ref, new_ref);+ }+ }+ serde_json::Value::Object(map) => {+ for v in map.values_mut() {+ Self::rename_refs_in_value(v, old_ref, new_ref);+ }+ }+ _ => {}+ }+ }+}+/// Trait for types that can generate tool schemas.////// Implement this trait to provide schema information about available tools.@@ -29,20 +229,13 @@ pub trait ToolSchemaGenerator {/// Generates the schemas for all tools in this generator.fn generate_schemas(&self) -> ToolSchemas;- /// Merges this generator's schemas with another generator's schemas.- fn merge(&self, generator: &dyn ToolSchemaGenerator) -> ToolSchemas {- let mut schemas = self.generate_schemas();- schemas- .schemas- .append(&mut generator.generate_schemas().schemas);- schemas- }-}--impl ToolSchemaGenerator for ToolSchemas {- fn generate_schemas(&self) -> ToolSchemas {- self.clone()- }+ /// Registers this generator's tool types with a shared+ /// [`schemars::SchemaGenerator`], returning an entry per tool.+ ///+ /// The generator accumulates shared definitions so that types used by+ /// multiple tools (e.g. `CodeExecutionErrorCode`) appear only once.+ fn register_schemas(&self, generator: &mut schemars::SchemaGenerator)+ -> Vec<CombinedToolEntry>;}impl<Context> ToolSchemaGenerator for AsyncToolSet<Context> {@@ -58,4 +251,21 @@ impl<Context> ToolSchemaGenerator for AsyncToolSet<Context> {.collect();ToolSchemas { schemas }}++ fn register_schemas(+ &self,+ generator: &mut schemars::SchemaGenerator,+ ) -> Vec<CombinedToolEntry> {+ self.tools+ .iter()+ .map(|(name, tool_object)| {+ let (input, output) = (tool_object.schema_registrar)(generator);+ CombinedToolEntry {+ name: name.clone(),+ input,+ output,+ }+ })+ .collect()+ }}diff --git a/rust/cloud-storage/ai_toolset/src/schema/phantom_tool.rs b/rust/cloud-storage/ai_toolset/src/schema/phantom_tool.rsindex c11d444c29..f9e7218ff9 100644--- a/rust/cloud-storage/ai_toolset/src/schema/phantom_tool.rs+++ b/rust/cloud-storage/ai_toolset/src/schema/phantom_tool.rs@@ -1,4 +1,4 @@-use super::generate::{ToolSchema, ToolSchemaGenerator, ToolSchemas};+use super::generate::{CombinedToolEntry, ToolSchema, ToolSchemaGenerator, ToolSchemas};use schemars::{JsonSchema, schema_for};use std::fmt::Debug;use std::marker::PhantomData;@@ -45,4 +45,17 @@ where}],}}++ fn register_schemas(+ &self,+ generator: &mut schemars::SchemaGenerator,+ ) -> Vec<CombinedToolEntry> {+ generator.subschema_for::<I>();+ generator.subschema_for::<O>();+ vec![CombinedToolEntry {+ name: self.name.to_owned(),+ input: I::schema_name().into_owned(),+ output: O::schema_name().into_owned(),+ }]+ }}diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rsindex 0de32b3e25..ca82854d37 100644--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/object.rs@@ -1,8 +1,13 @@+use schemars::SchemaGenerator;use serde_json::Error as JsonError;use serde_json::Map;use serde_json::Value;use thiserror::Error;+/// Closure that registers a tool's input/output types with a shared+/// [`SchemaGenerator`], returning `(input_name, output_name)`.+pub type SchemaRegistrar = Box<dyn Fn(&mut SchemaGenerator) -> (String, String) + Send + Sync>;+/// A compiled tool object containing schema and deserialization logic.////// `ToolObject` holds the metadata and deserializer for a tool, allowing@@ -18,6 +23,9 @@ pub struct ToolObject<T> {pub name: String,/// The deserializer function for converting JSON to the tool type.pub deserializer: T,+ /// Registers this tool's input/output types with a shared generator+ /// for combined schema generation.+ pub schema_registrar: SchemaRegistrar,}/// Errors that can occur when validating a tool's schema.diff --git a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rsindex 00400f36e3..bb910dd884 100644--- a/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs+++ b/rust/cloud-storage/ai_toolset/src/toolset/tool_object/tool_async.rs@@ -1,4 +1,4 @@-use super::object::{ToolObject, ValidationError};+use super::object::{SchemaRegistrar, ToolObject, ValidationError};use super::util::validate_tool_schema;use crate::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;@@ -173,12 +173,20 @@ wherelet output_schema_json =serde_json::to_value(&output_schema).map_err(ValidationError::JsonSerialization)?;+ let schema_registrar: SchemaRegistrar =+ Box::new(|generator: &mut schemars::SchemaGenerator| {+ generator.subschema_for::<T>();+ generator.subschema_for::<O>();+ (T::schema_name().into_owned(), O::schema_name().into_owned())+ });+Ok(Self {name,input_schema: input_schema_json,output_schema: output_schema_json,description,deserializer,+ schema_registrar,})}@@ -260,6 +268,7 @@ whereoutput_schema: self.output_schema,description: self.description,deserializer: new_deserializer,+ schema_registrar: self.schema_registrar,}}}diff --git a/rust/cloud-storage/ai_toolset/src/toolset/types.rs b/rust/cloud-storage/ai_toolset/src/toolset/types.rsindex 020bcdc59d..ce8f06f730 100644--- a/rust/cloud-storage/ai_toolset/src/toolset/types.rs+++ b/rust/cloud-storage/ai_toolset/src/toolset/types.rs@@ -6,7 +6,7 @@ use axum::extract::FromRef;use schemars::{JsonSchema, Schema};use serde::Serialize;use serde::de::Deserialize;-use std::collections::hash_map::HashMap;+use std::collections::BTreeMap;use thiserror::Error;/// Error type for failures when creating or adding tools to a toolset.@@ -63,17 +63,17 @@ impl ToolSchema {pub struct ToolSet<T> {/// The tools in this toolset, keyed by name./// This includes type-erased user tools- pub tools: HashMap<String, T>,+ pub tools: BTreeMap<String, T>,/// Non type-erased user tools- pub user_tools: HashMap<String, T>,+ pub user_tools: BTreeMap<String, T>,}impl<T> ToolSet<T> {/// Creates a new empty toolset.pub fn new() -> Self {Self {- tools: HashMap::new(),- user_tools: HashMap::new(),+ tools: BTreeMap::new(),+ user_tools: BTreeMap::new(),}}}