import { AIWS_MANIFEST_FILE, AIWS_MANIFEST_VERSION, AiwsFailure, AiwsSourceError, aiwsTarget, buildControl, commitOps, exportBundle, fieldAdd, isSourcePath, move, NfspClient, optionAdd, packBuildFiles, pullControl, rename, setProps, tableDelete, tableInsert, tableSet, templateDir, textAppend, textDeleteBlocks, textReplaceBlock, watchControl, } from 'buckyos/node' import { AiccLlmClient, LLMComputeException, providerErrorFromRpc } from 'buckyos/xllm' import type { CommandDefinition, CommandModule, JsonSchema, OptionDefinition, PositionalDefinition } from '../core/command.ts' import type { CommandContext } from '../core/context.ts' import { EXIT_AUTH, ToolError, UsageError } from '../core/errors.ts' import { callService, expectObject, inputString, requiredInputString, rpcOptions } from '../core/service.ts' import { getHost } from '../runtime/host.ts' import { createPikgModule } from './pikg.ts' import { placeCommand } from './aiws_place.ts' import { gatewayOrigin } from './share.ts' // AI Workspace (`/kapi/aiworkspace`): finding, reading, querying and writing a workspace (ls, find, grep, stat, cat, // resolve, sql; table, text, mv, rename, set-prop: buckyos notepads/aiws-core-api-design.md §9), and the executor // protocol of a wish run (内核架构改进 M3): claim → heartbeat → report. Source of truth for the methods: // buckyos/src/frame/aiworkspace/README.md (Protocol). const SERVICE = 'aiworkspace' const OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true } const WORKSPACE_OPTION: OptionDefinition = { name: 'workspace', property: 'workspace_id', description: 'Workspace id (ws_…)', type: 'string', required: true } const RUN_OPTION: OptionDefinition = { name: 'run', property: 'run_id', description: 'Run id (run_…)', type: 'string', required: true } const ATTEMPT_OPTION: OptionDefinition = { name: 'attempt', property: 'attempt', description: 'The attempt number `run-claim` answered', type: 'integer', required: true } function workspaceInput(extra: Record, required: string[] = []): JsonSchema { return { type: 'object', properties: { workspace_id: { type: 'string', minLength: 1 }, ...extra }, required: ['workspace_id', ...required], additionalProperties: false } } async function aiws(ctx: CommandContext, method: string, params: Record): Promise> { const result = expectObject(await callService(ctx, SERVICE, method, params), method) if (result.ok === false) { const error = expectObject(result.error, `${method}.error`) const code = typeof error.code === 'string' ? error.code : 'AIWS_ERROR' const detail = typeof error.detail === 'string' ? error.detail : code // the structured part (a build's diagnostics, a conflict's revisions) travels in the error's details const details: Record = {} if (typeof error.sub_code === 'string') details.sub_code = error.sub_code if (error.data !== undefined) details.data = error.data throw new ToolError(code, `${code}${typeof error.sub_code === 'string' ? `/${error.sub_code}` : ''}: ${detail}`, undefined, false, details) } return result } async function jsonInput(input: Record, textKey: string, fileKey: string, label: string): Promise { const text = inputString(input, textKey) const file = inputString(input, fileKey) if (text && file) throw new UsageError('AIWS_USAGE', `${textKey} and ${fileKey} are exclusive`) if (file) return JSON.parse(await getHost().readTextFile(file)) as unknown if (text) return JSON.parse(text) as unknown throw new UsageError('AIWS_USAGE', `${label}: pass --${textKey.replace(/_/g, '-')} or --${fileKey.replace(/_/g, '-')}`) } // ---- finding and reading. An entity argument is a path (`/data/销售`, `~/…`) or an entity id. const PATH_HELP = 'Path (/data/销售, ~/…) or entity id' const TYPE_OPTIONS: OptionDefinition[] = [ { name: 'type', property: 'type', description: 'Only these types, comma-separated: table, richtext, record, annotation, block, container (container:), asset, dir, wish, def, …', type: 'string' }, { name: 'not-type', property: 'not_type', description: 'Leave these types out, comma-separated', type: 'string' }, ] const CURSOR_OPTION: OptionDefinition = { name: 'cursor', property: 'cursor', description: 'Continue from the next_cursor of a previous page', type: 'string' } const READ_ACCESS = { mode: 'fixed', level: 'read' } as const const WRITE_ACCESS = { mode: 'fixed', level: 'write' } as const /** The keys of `input` that are given, renamed by `names` ({ input key: param }). */ function given(input: Record, names: Record): Record { const out: Record = {} for (const [key, param] of Object.entries(names)) { const v = input[key] if (typeof v === 'string' ? v.trim() !== '' : v !== undefined && v !== false) out[param] = typeof v === 'string' ? v.trim() : v } return out } function jsonArg(text: string, label: string): unknown { try { return JSON.parse(text) as unknown } catch (error) { throw new UsageError('AIWS_USAGE', `${label}: ${error instanceof Error ? error.message : String(error)}`) } } const readCommand: CommandDefinition = { verb: 'read', summary: 'Read one entity of a workspace: envelope and native content', positionals: [{ name: 'entity_id', description: PATH_HELP, required: true } satisfies PositionalDefinition], options: [WORKSPACE_OPTION, { name: 'selector', property: 'selector', description: 'Selector JSON, e.g. {"kind":"table_record","record_id":"r1"}', type: 'string' }], inputSchema: workspaceInput({ entity_id: { type: 'string', minLength: 1 }, selector: { type: 'string' } }, ['entity_id']), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: ['buckyos aiws read orders --workspace ws_abc', 'buckyos aiws read /data/订单 --workspace ws_abc --selector \'{"kind":"table_record","record_id":"r1"}\''], handler: (ctx, input) => { const selector = inputString(input, 'selector') return aiws(ctx, 'doc.read', { workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'entity_id')), ...(selector ? { selector: jsonArg(selector, '--selector') } : {}) }) }, } const lsCommand: CommandDefinition = { verb: 'ls', summary: 'The direct children of a path (default /), in tree order: name, path, type, title, children, body state', positionals: [{ name: 'path', description: `${PATH_HELP} (default /)`, required: false }], options: [WORKSPACE_OPTION, ...TYPE_OPTIONS, { name: 'schema', property: 'schema', description: 'Only entities of this schema id, e.g. buckyos.todo@1', type: 'string' }, { name: 'limit', property: 'limit', description: 'Items per page (≤ 1000, default 100)', type: 'integer' }, CURSOR_OPTION], inputSchema: workspaceInput({ path: { type: 'string' }, type: { type: 'string' }, not_type: { type: 'string' }, schema: { type: 'string' }, limit: { type: 'integer', minimum: 1 }, cursor: { type: 'string' } }), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: ['buckyos aiws ls --workspace ws_abc', 'buckyos aiws ls /data --workspace ws_abc --type table'], handler: (ctx, input) => aiws(ctx, 'doc.list', { workspace_id: requiredInputString(input, 'workspace_id'), ...given(input, { path: 'at', type: 'type', not_type: 'not_type', schema: 'schema', limit: 'limit', cursor: 'cursor' }) }), } const findCommand: CommandDefinition = { verb: 'find', summary: 'Entities whose name or title holds a literal (case-insensitive), by type and schema, walking down from a path', description: 'A pre-order walk of at most 20 000 entities per call: when `complete` is false, continue with --cursor. Without text it finds by --type / --schema only.', positionals: [{ name: 'text', description: 'Literal looked for in names and titles', required: false }], options: [WORKSPACE_OPTION, { name: 'at', property: 'at', description: `Where to start: ${PATH_HELP} (default /)`, type: 'string' }, { name: 'depth', property: 'depth', description: 'Levels below --at (≤ 16)', type: 'integer' }, ...TYPE_OPTIONS, { name: 'schema', property: 'schema', description: 'Only entities of this schema id', type: 'string' }, { name: 'limit', property: 'limit', description: 'Items per page (≤ 200, default 50)', type: 'integer' }, CURSOR_OPTION], inputSchema: workspaceInput({ text: { type: 'string' }, at: { type: 'string' }, depth: { type: 'integer', minimum: 1 }, type: { type: 'string' }, not_type: { type: 'string' }, schema: { type: 'string' }, limit: { type: 'integer', minimum: 1 }, cursor: { type: 'string' } }), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: ['buckyos aiws find 销售 --workspace ws_abc', 'buckyos aiws find --workspace ws_abc --type table --at /data'], handler: (ctx, input) => aiws(ctx, 'doc.find', { workspace_id: requiredInputString(input, 'workspace_id'), ...given(input, { text: 'name', at: 'at', depth: 'depth', type: 'type', not_type: 'not_type', schema: 'schema', limit: 'limit', cursor: 'cursor' }) }), } const grepCommand: CommandDefinition = { verb: 'grep', summary: 'A literal (1–256 characters) in names, titles and bodies (the plain-text rendering of each entity): hits with a snippet and the selector of the part', description: 'Literal match, case-insensitive unless --case; no regex. An empty result means “none” only when coverage.complete is true; otherwise continue with --cursor. Annotations, viewports, paths, tasks, responses and results are searched only when named in --type.', positionals: [{ name: 'text', description: 'Literal to look for', required: true }], options: [WORKSPACE_OPTION, { name: 'at', property: 'at', description: `Where to search: ${PATH_HELP} (default /)`, type: 'string' }, { name: 'depth', property: 'depth', description: 'Levels below --at', type: 'integer' }, { name: 'case', property: 'case', description: 'Compare case-sensitively', type: 'boolean' }, ...TYPE_OPTIONS, { name: 'limit', property: 'limit', description: 'Hits per page (≤ 100, default 20)', type: 'integer' }, CURSOR_OPTION], inputSchema: workspaceInput({ text: { type: 'string', minLength: 1 }, at: { type: 'string' }, depth: { type: 'integer', minimum: 1 }, case: { type: 'boolean' }, type: { type: 'string' }, not_type: { type: 'string' }, limit: { type: 'integer', minimum: 1 }, cursor: { type: 'string' } }, ['text']), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: ['buckyos aiws grep 华东 --workspace ws_abc', 'buckyos aiws grep "Q4 plan" --workspace ws_abc --at /docs --type richtext'], handler: (ctx, input) => aiws(ctx, 'doc.query', { workspace_id: requiredInputString(input, 'workspace_id'), text: requiredInputString(input, 'text'), ...given(input, { at: 'at', depth: 'depth', case: 'case', type: 'type', not_type: 'not_type', limit: 'limit', cursor: 'cursor' }) }), } // ---- permissions (buckyos notepads/aiws-permission-system-prd.md §4; README “Permissions”): entries `subject × resource // → allow, deny` addressed by path, logical groups, anonymous access, inner-path publications, the operation record. const SUBJECT_HELP = 'A principal (user id, DID), @, @all, @guest or @creator' const caps = (text: string | undefined): string[] => (text ? ids(text) : []) const aclCommand: CommandDefinition = { verb: 'acl', summary: 'Read permissions: `ls` (every entry, or your own), `show ` (who holds what on it and from where), `who [subject]` (a subject\'s entries; a principal\'s groups), `explain [--principal]` (why each capability is allowed or refused), `groups`, `entries` (share links), `audit` (the operation record)', description: 'Entries are decided by the nearest layer (the entity, its ancestors, then /) that mentions a capability, then by the most specific tier (a single caller, then groups and @creator, then @guest and @all); a deny wins within a tier. Anyone may ask about themselves (who, explain); the rest needs manage.', positionals: [ { name: 'action', description: 'ls | show | who | explain | groups | entries | audit', required: true }, { name: 'target', description: `show / explain: ${PATH_HELP} (default /); who: ${SUBJECT_HELP}`, required: false }, ], options: [ WORKSPACE_OPTION, { name: 'principal', property: 'principal', description: 'explain: whose permissions (default: yours; another\'s needs manage)', type: 'string' }, { name: 'expand', property: 'expand', description: 'show: list the members of each group', type: 'boolean' }, { name: 'after', property: 'after', description: 'audit: records after this sequence number', type: 'integer' }, { name: 'limit', property: 'limit', description: 'audit: at most this many records (≤ 1000)', type: 'integer' }, ], inputSchema: workspaceInput({ action: { type: 'string', enum: ['ls', 'show', 'who', 'explain', 'groups', 'entries', 'audit'] }, target: { type: 'string' }, principal: { type: 'string' }, expand: { type: 'boolean' }, after: { type: 'integer' }, limit: { type: 'integer', minimum: 1 }, }, ['action']), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: [ 'buckyos aiws acl show /data/成绩 --workspace ws_abc', 'buckyos aiws acl explain /data/成绩 --principal bob --workspace ws_abc', 'buckyos aiws acl who @teachers --workspace ws_abc', 'buckyos aiws acl groups --workspace ws_abc', ], handler: (ctx, input) => { const workspace_id = requiredInputString(input, 'workspace_id') const target = inputString(input, 'target') switch (requiredInputString(input, 'action')) { case 'ls': return aiws(ctx, 'acl.query', { workspace_id, by: 'all' }) case 'show': return aiws(ctx, 'acl.query', { workspace_id, by: 'entity', resource: target ?? '/', ...given(input, { expand: 'expand' }) }) case 'who': return aiws(ctx, 'acl.query', { workspace_id, by: 'subject', ...(target ? { subject: target } : {}) }) case 'explain': return aiws(ctx, 'acl.query', { workspace_id, by: 'explain', resource: target ?? '/', ...given(input, { principal: 'principal' }) }) case 'groups': return aiws(ctx, 'acl.groups', { workspace_id }) case 'entries': return aiws(ctx, 'ws.list_entries', { workspace_id }) case 'audit': return aiws(ctx, 'acl.audit', { workspace_id, ...given(input, { after: 'after', limit: 'limit' }) }) default: throw new UsageError('AIWS_USAGE', 'acl: ls, show, who, explain, groups, entries or audit') } }, } const aclEditCommand: CommandDefinition = { verb: 'acl-edit', summary: 'Change permissions: `set --allow … --deny …` (replaces that entry; both empty removes it), `rm `, `group-add [--title]`, `group-rm `, `member-add `, `member-rm `, `anonymous on|off`, `bind [--mode]`, `entry-add --methods …`, `entry-close [--remove-members]`, `publish [--name]`, `unpublish `', description: 'Needs manage (giving or taking manage, or changing the members of a group holding it, is the owner\'s). Members: a principal, group:, contact:#, * (every unrestricted account of the Zone); a group is never a member of a group. @all and @guest never get manage or run; @guest exists only while anonymous access is on. A share entry leads into a group holding neither manage nor run.', positionals: [ { name: 'action', description: 'set | rm | group-add | group-rm | member-add | member-rm | anonymous | bind | entry-add | entry-close | publish | unpublish', required: true }, { name: 'target', description: `set / rm: ${SUBJECT_HELP}; group-*, member-*, entry-add: group id; anonymous: on | off; bind, publish, unpublish: ${PATH_HELP}; entry-close: entry id`, required: false }, { name: 'arg', description: `set / rm: ${PATH_HELP} (default /); member-*: members, comma-separated; bind: group id or none`, required: false }, ], options: [ WORKSPACE_OPTION, { name: 'allow', property: 'allow', description: 'set: capabilities, comma-separated (read, append, update, delete, structure, comment, export, manage, run)', type: 'string' }, { name: 'deny', property: 'deny', description: 'set: capabilities refused, comma-separated', type: 'string' }, { name: 'title', property: 'title', description: 'group-add: the group\'s title', type: 'string' }, { name: 'description', property: 'description', description: 'group-add: what the group is for', type: 'string' }, { name: 'mode', property: 'mode', description: 'bind: union (default) or intersection with the triggerer\'s permissions', type: 'string', enum: ['union', 'intersection'] }, { name: 'methods', property: 'methods', description: 'entry-add: ways in, comma-separated: guest, password, self_register, did_login', type: 'string' }, { name: 'expires-at', property: 'expires_at', description: 'entry-add: unix seconds', type: 'integer' }, { name: 'max-joins', property: 'max_joins', description: 'entry-add: how many may join at most', type: 'integer' }, { name: 'remove-members', property: 'remove_members', description: 'entry-close: those who joined through it leave the group too', type: 'boolean' }, { name: 'name', property: 'name', description: 'publish: the last segment of the link', type: 'string' }, ], inputSchema: workspaceInput({ action: { type: 'string', enum: ['set', 'rm', 'group-add', 'group-rm', 'member-add', 'member-rm', 'anonymous', 'bind', 'entry-add', 'entry-close', 'publish', 'unpublish'] }, target: { type: 'string' }, arg: { type: 'string' }, allow: { type: 'string' }, deny: { type: 'string' }, title: { type: 'string' }, description: { type: 'string' }, mode: { type: 'string', enum: ['union', 'intersection'] }, methods: { type: 'string' }, expires_at: { type: 'integer' }, max_joins: { type: 'integer', minimum: 1 }, remove_members: { type: 'boolean' }, name: { type: 'string' }, }, ['action']), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: WRITE_ACCESS, asyncMode: 'sync', requiresSession: true, examples: [ 'buckyos aiws acl-edit group-add teachers --title 老师 --workspace ws_abc', 'buckyos aiws acl-edit member-add teachers group:staff,bob --workspace ws_abc', 'buckyos aiws acl-edit set @teachers /data/成绩 --allow read,update --workspace ws_abc', 'buckyos aiws acl-edit set @all /data/工资 --deny read --workspace ws_abc', 'buckyos aiws acl-edit anonymous on --workspace ws_abc', 'buckyos aiws acl-edit entry-add visitors --methods guest,password --workspace ws_abc', ], handler: async (ctx, input) => { const workspace_id = requiredInputString(input, 'workspace_id') const target = () => requiredInputString(input, 'target') const arg = inputString(input, 'arg') const entityId = async (path: string) => String((await aiws(ctx, 'doc.resolve', { workspace_id, ...( path.startsWith('/') || path.startsWith('~') ? { path } : { reference: { entity_id: path, mode: 'live' } }) })).entity_id) switch (requiredInputString(input, 'action')) { case 'set': return aiws(ctx, 'acl.set', { workspace_id, changes: [{ subject: target(), resource: arg ?? '/', allow: caps(inputString(input, 'allow')), deny: caps(inputString(input, 'deny')) }] }) case 'rm': return aiws(ctx, 'acl.set', { workspace_id, changes: [{ subject: target(), resource: arg ?? '/' }] }) case 'group-add': return aiws(ctx, 'acl.set_group', { workspace_id, group_id: target(), ...given(input, { title: 'title', description: 'description' }) }) case 'group-rm': return aiws(ctx, 'acl.delete_group', { workspace_id, group_id: target() }) case 'member-add': return aiws(ctx, 'acl.members', { workspace_id, group_id: target(), add: ids(arg ?? '') }) case 'member-rm': return aiws(ctx, 'acl.members', { workspace_id, group_id: target(), remove: ids(arg ?? '') }) case 'anonymous': { const on = target() if (on !== 'on' && on !== 'off') throw new UsageError('AIWS_USAGE', 'anonymous on | off') return aiws(ctx, 'acl.set_anonymous', { workspace_id, enabled: on === 'on' }) } case 'bind': return aiws(ctx, 'acl.bind_macro', { workspace_id, wish: target(), group_id: !arg || arg === 'none' ? null : arg, ...given(input, { mode: 'mode' }) }) case 'entry-add': { const methods = Object.fromEntries(ids(requiredInputString(input, 'methods')).map((m) => [m, true])) return aiws(ctx, 'ws.create_entry', { workspace_id, group_id: target(), methods, ...given(input, { expires_at: 'expires_at', max_joins: 'max_joins' }) }) } case 'entry-close': return aiws(ctx, 'ws.close_entry', { workspace_id, entry_id: target(), ...given(input, { remove_members: 'remove_members' }) }) case 'publish': return aiws(ctx, 'ws.publish', { workspace_id, entity_id: await entityId(target()), ...given(input, { name: 'name' }) }) case 'unpublish': return aiws(ctx, 'ws.unpublish', { workspace_id, entity_id: await entityId(target()) }) default: throw new UsageError('AIWS_USAGE', 'acl-edit: set, rm, group-add, group-rm, member-add, member-rm, anonymous, bind, entry-add, entry-close, publish or unpublish') } }, } const statCommand: CommandDefinition = { verb: 'stat', summary: 'What an entity is: path, name, title, type, schema, parent, versions, body state and size, children, your capabilities and the Commit operations its type takes', positionals: [{ name: 'path', description: PATH_HELP, required: true }], options: [WORKSPACE_OPTION], inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 } }, ['path']), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: ['buckyos aiws stat /data/销售 --workspace ws_abc'], handler: (ctx, input) => aiws(ctx, 'doc.read', { workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'path')), as: 'meta' }), } /** Pages of a body followed at most this far (32 KiB each by default). */ const CAT_MAX_PAGES = 512 const catCommand: CommandDefinition = { verb: 'cat', summary: 'The plain-text body of an entity (rich text as Markdown, a table as CSV, …), whole: the pages are followed unless --max-bytes or --cursor asks for one page', description: 'With --output text only the text is printed. A table body is CSV of display values (select labels, reference paths); one part (a record, a block) is read with --selector.', positionals: [{ name: 'path', description: PATH_HELP, required: true }], options: [ WORKSPACE_OPTION, { name: 'selector', property: 'selector', description: 'Only this part, selector JSON, e.g. {"kind":"richtext_block","block_id":"b3"}', type: 'string' }, { name: 'max-bytes', property: 'max_bytes', description: 'One page of at most this many bytes (64…262144)', type: 'integer' }, CURSOR_OPTION, ], inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, selector: { type: 'string' }, max_bytes: { type: 'integer', minimum: 64 }, cursor: { type: 'string' } }, ['path']), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: ['buckyos aiws cat /docs/周报 --workspace ws_abc --output text', 'buckyos aiws cat /data/销售 --workspace ws_abc --max-bytes 4096'], handler: async (ctx, input) => { const selector = inputString(input, 'selector') const request = { workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'path')), as: 'body', ...(selector ? { selector: jsonArg(selector, '--selector') } : {}), ...given(input, { max_bytes: 'max_bytes' }), } let page = await aiws(ctx, 'doc.read', { ...request, ...given(input, { cursor: 'cursor' }) }) if (input.max_bytes !== undefined || inputString(input, 'cursor')) return page let text = String(page.text ?? '') for (let n = 1; page.complete === false && typeof page.next_cursor === 'string' && n < CAT_MAX_PAGES; n++) { page = await aiws(ctx, 'doc.read', { ...request, cursor: page.next_cursor }) text += String(page.text ?? '') } const { parts: _parts, ...last } = page return { ...last, text } }, } const resolveCommand: CommandDefinition = { verb: 'resolve', summary: 'A path (or entity id) as a reference: entity id, canonical reference, path and name', positionals: [{ name: 'path', description: PATH_HELP, required: true }], options: [WORKSPACE_OPTION], inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 } }, ['path']), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: ['buckyos aiws resolve /data/销售 --workspace ws_abc'], handler: (ctx, input) => { const target = aiwsTarget(requiredInputString(input, 'path')) return aiws(ctx, 'doc.resolve', { workspace_id: requiredInputString(input, 'workspace_id'), ...('path' in target ? target : { reference: { entity_id: target.entity_id, mode: 'live' } }) }) }, } /** `--table a=/data/销售,b=orders`: aliases of the tables a query reads (a path may hold commas; a pair starts at * `=`). */ function tableAliases(text: string): Record { const out: Record = {} for (const pair of text.split(/,(?=\s*[A-Za-z_][A-Za-z0-9_]*=)/)) { const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)=(.+?)\s*$/.exec(pair) if (!m) throw new UsageError('AIWS_USAGE', `--table ${pair}: =`) out[m[1]] = m[2] } return out } const sqlCommand: CommandDefinition = { verb: 'sql', summary: 'One SQL SELECT over the tables of a workspace: a table is named by its path in double quotes (FROM "/data/销售"), "~", or an alias of --table', description: 'Columns: _id (record id), _rev, _body (path of the record body), _record (the record as doc.read gives it, JSON), and per field "" (display value: select label, multi-select JSON array of labels, reference path, decimal / currency amount as a number, boolean 1/0) and "#raw" (stored value: option ids, exact decimal, reference / currency JSON); currency also "#currency". SELECT only (WITH, subqueries and window functions included); at most --max-rows rows (truncated tells), 4 MiB and 2 s. URL tables have no local rows (NOT_MATERIALIZED).', positionals: [{ name: 'sql', description: 'The SELECT statement', required: true }], options: [ WORKSPACE_OPTION, { name: 'table', property: 'table', description: 'Aliases: alias=[,alias=…]; only these tables are visible then', type: 'string' }, { name: 'params', property: 'params', description: 'Positional parameters (?) as a JSON array', type: 'string' }, { name: 'max-rows', property: 'max_rows', description: 'Rows at most (≤ 5000, default 1000)', type: 'integer' }, ], inputSchema: workspaceInput({ sql: { type: 'string', minLength: 1 }, table: { type: 'string' }, params: { type: 'string' }, max_rows: { type: 'integer', minimum: 1 } }, ['sql']), outputSchema: OBJECT_OUTPUT, resultSchemaVersion: 1, access: READ_ACCESS, asyncMode: 'sync', requiresSession: true, examples: [ 'buckyos aiws sql \'SELECT "客户", SUM("金额") AS total FROM "/data/销售" GROUP BY "客户" ORDER BY total DESC LIMIT 10\' --workspace ws_abc', 'buckyos aiws sql \'SELECT "_id", "客户", "金额" FROM t WHERE "状态" = ? LIMIT 20\' --table t=/data/销售 --params \'["已完成"]\' --workspace ws_abc', ], handler: (ctx, input) => { const table = inputString(input, 'table') const params = inputString(input, 'params') const values = params ? jsonArg(params, '--params') : undefined if (values !== undefined && !Array.isArray(values)) throw new UsageError('AIWS_USAGE', '--params is a JSON array') return aiws(ctx, 'doc.query', { workspace_id: requiredInputString(input, 'workspace_id'), sql: requiredInputString(input, 'sql'), ...(table ? { tables: tableAliases(table) } : {}), ...(values ? { params: values } : {}), ...given(input, { max_rows: 'max_rows' }), }) }, } // ---- writing: the operations of buckyos-websdk src/aiws_write.ts, committed as one Commit each (an idempotency key, and // on an unknown result doc.get_submission, then the same key again). Field names, option labels and `expect` come from // what is read just before. type TableRead = Parameters[0] type RichTextRead = Parameters[0] type EntityRead = Parameters[0] /** The service as the SDK's write helpers take it: a business failure is an `AiwsFailure`, never an unknown result. */ function writeTransport(ctx: CommandContext) { return { call: async (method: string, params: Record): Promise => { const result = expectObject(await callService(ctx, SERVICE, method, params), method) if (result.ok === false) { const error = expectObject(result.error, `${method}.error`) throw new AiwsFailure({ code: String(error.code ?? 'AIWS_ERROR'), retryable: Boolean(error.retryable), detail: String(error.detail ?? error.code ?? ''), sub_code: typeof error.sub_code === 'string' ? error.sub_code : undefined, data: error.data }) } return result as T }, } } /** A refusal (of the service, or of a helper: an unknown field, a block not read) as the CLI's error, its code first. */ async function writing(work: () => Promise): Promise { try { return await work() } catch (error) { if (error instanceof AiwsFailure) throw new ToolError(error.code, error.message, undefined, false, { ...(error.subCode ? { sub_code: error.subCode } : {}), ...(error.data !== undefined ? { data: error.data } : {}) }) throw error } } async function commit(ctx: CommandContext, ws: string, ops: Record[], message: string): Promise> { const result = await commitOps(writeTransport(ctx), ws, ops as never, { message, ...(ctx.idempotencyKey ? { idempotencyKey: ctx.idempotencyKey } : {}) }) return { ok: true, status: result.status, commit_id: result.commit_id, seq: result.seq } } /** The envelope of an entity (ids and revs) without its content. */ function envelopeOf(ctx: CommandContext, ws: string, target: string): Promise> { return aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target), selector: { kind: 'doc_key', key: 'title' } }) } const ids = (text: string) => text.split(',').map((s) => s.trim()).filter(Boolean) async function markdownInput(input: Record): Promise { const text = typeof input.text === 'string' ? input.text : undefined const file = inputString(input, 'file') if ((text !== undefined) === (file !== undefined)) throw new UsageError('AIWS_USAGE', 'pass --file or --text ') return file ? await getHost().readTextFile(file) : text! } const tableCommand: CommandDefinition = { verb: 'table', summary: 'Write a table: `add --values` (records), `set
--values` (cells), `rm
[,…]`, `field-add
--name --type`, `option-add