buckyos 0.7.180 → 0.7.183

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +35 -0
  3. package/README.md +4 -0
  4. package/cli/deno.json +3 -2
  5. package/cli/dist/cli.mjs +1534 -216
  6. package/cli/dist/cli.mjs.map +1 -1
  7. package/cli/modules/aiws.ts +761 -58
  8. package/cli/modules/aiws_place.ts +383 -0
  9. package/cli/modules/aiws_schedule.ts +256 -0
  10. package/cli/runtime/host.ts +18 -0
  11. package/cli/runtime/host_deno.ts +34 -0
  12. package/cli/runtime/host_node.ts +32 -1
  13. package/cli/runtime/node_entry.ts +1 -0
  14. package/cli/system_bootstrap.ts +1 -0
  15. package/cli/system_launcher.ts +1 -0
  16. package/cli/version.ts +1 -1
  17. package/dist/aicc_client.d.ts +1 -1
  18. package/dist/aicc_client.d.ts.map +1 -1
  19. package/dist/aiworkspace_client.d.ts +253 -2
  20. package/dist/aiworkspace_client.d.ts.map +1 -1
  21. package/dist/aiws_bind-3b874f77.mjs +2235 -0
  22. package/dist/aiws_bind-3b874f77.mjs.map +1 -0
  23. package/dist/aiws_bind-82bace11.js +2 -0
  24. package/dist/aiws_bind-82bace11.js.map +1 -0
  25. package/dist/aiws_bind.d.ts +233 -0
  26. package/dist/aiws_bind.d.ts.map +1 -0
  27. package/dist/aiws_ext.cjs +1 -1
  28. package/dist/aiws_ext.cjs.map +1 -1
  29. package/dist/aiws_ext.d.ts +9 -5
  30. package/dist/aiws_ext.d.ts.map +1 -1
  31. package/dist/aiws_ext.mjs +146 -11
  32. package/dist/aiws_ext.mjs.map +1 -1
  33. package/dist/aiws_rrule.d.ts +121 -0
  34. package/dist/aiws_rrule.d.ts.map +1 -0
  35. package/dist/aiws_schedule.d.ts +324 -0
  36. package/dist/aiws_schedule.d.ts.map +1 -0
  37. package/dist/aiws_write-89b5cc2a.js +13 -0
  38. package/dist/aiws_write-89b5cc2a.js.map +1 -0
  39. package/dist/{executor_client-bfc8a1e1.mjs → aiws_write-c2de498e.mjs} +724 -285
  40. package/dist/aiws_write-c2de498e.mjs.map +1 -0
  41. package/dist/aiws_write.d.ts +178 -0
  42. package/dist/aiws_write.d.ts.map +1 -0
  43. package/dist/browser.cjs +1 -1
  44. package/dist/browser.cjs.map +1 -1
  45. package/dist/browser.d.ts +4 -0
  46. package/dist/browser.d.ts.map +1 -1
  47. package/dist/browser.mjs +112 -21
  48. package/dist/browser.mjs.map +1 -1
  49. package/dist/{content_objid-9232bcaf.mjs → content_objid-a2cafba9.mjs} +2 -2
  50. package/dist/{content_objid-9232bcaf.mjs.map → content_objid-a2cafba9.mjs.map} +1 -1
  51. package/dist/content_objid-dff803ff.js +2 -0
  52. package/dist/{content_objid-1aff74b6.js.map → content_objid-dff803ff.js.map} +1 -1
  53. package/dist/{did_object_client-7fa36f90.mjs → did_object_client-cb2f9aba.mjs} +2 -2
  54. package/dist/{did_object_client-7fa36f90.mjs.map → did_object_client-cb2f9aba.mjs.map} +1 -1
  55. package/dist/index.cjs +1 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.ts +4 -0
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.mjs +113 -22
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/node.cjs +1 -1
  62. package/dist/node.cjs.map +1 -1
  63. package/dist/node.d.ts +5 -0
  64. package/dist/node.d.ts.map +1 -1
  65. package/dist/node.mjs +99 -6
  66. package/dist/node.mjs.map +1 -1
  67. package/dist/{object_url-f72c1704.mjs → object_url-376c5222.mjs} +4 -4
  68. package/dist/{object_url-f72c1704.mjs.map → object_url-376c5222.mjs.map} +1 -1
  69. package/dist/xllm.mjs +2 -2
  70. package/package.json +5 -4
  71. package/dist/content_objid-1aff74b6.js +0 -2
  72. package/dist/executor_client-7ce0ddc7.js +0 -13
  73. package/dist/executor_client-7ce0ddc7.js.map +0 -1
  74. package/dist/executor_client-bfc8a1e1.mjs.map +0 -1
@@ -1,26 +1,44 @@
1
1
  import {
2
2
  AIWS_MANIFEST_FILE,
3
3
  AIWS_MANIFEST_VERSION,
4
+ AiwsFailure,
4
5
  AiwsSourceError,
6
+ aiwsTarget,
5
7
  buildControl,
8
+ commitOps,
6
9
  exportBundle,
10
+ fieldAdd,
7
11
  isSourcePath,
12
+ move,
8
13
  NfspClient,
14
+ optionAdd,
9
15
  packBuildFiles,
10
16
  pullControl,
17
+ rename,
18
+ setProps,
19
+ tableDelete,
20
+ tableInsert,
21
+ tableSet,
11
22
  templateDir,
23
+ textAppend,
24
+ textDeleteBlocks,
25
+ textReplaceBlock,
12
26
  watchControl,
13
27
  } from 'buckyos/node'
28
+ import { AiccLlmClient, LLMComputeException, providerErrorFromRpc } from 'buckyos/xllm'
14
29
  import type { CommandDefinition, CommandModule, JsonSchema, OptionDefinition, PositionalDefinition } from '../core/command.ts'
15
30
  import type { CommandContext } from '../core/context.ts'
16
31
  import { EXIT_AUTH, ToolError, UsageError } from '../core/errors.ts'
17
- import { callService, expectObject, inputString, requiredInputString } from '../core/service.ts'
32
+ import { callService, expectObject, inputString, requiredInputString, rpcOptions } from '../core/service.ts'
18
33
  import { getHost } from '../runtime/host.ts'
19
34
  import { createPikgModule } from './pikg.ts'
35
+ import { calCommand, todoCommand } from './aiws_schedule.ts'
36
+ import { placeCommand } from './aiws_place.ts'
20
37
  import { gatewayOrigin } from './share.ts'
21
38
 
22
- // AI Workspace (`/kapi/aiworkspace`): reading a workspace, and the executor protocol of a wish run
23
- // (内核架构改进 M3): claim → heartbeat → report. Source of truth for the methods:
39
+ // AI Workspace (`/kapi/aiworkspace`): finding, reading, querying and writing a workspace (ls, find, grep, stat, cat,
40
+ // resolve, sql; table, text, mv, rename, set-prop: buckyos notepads/aiws-core-api-design.md §9), and the executor
41
+ // protocol of a wish run (内核架构改进 M3): claim → heartbeat → report. Source of truth for the methods:
24
42
  // buckyos/src/frame/aiworkspace/README.md (Protocol).
25
43
  const SERVICE = 'aiworkspace'
26
44
  const OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }
@@ -56,53 +74,602 @@ async function jsonInput(input: Record<string, unknown>, textKey: string, fileKe
56
74
  throw new UsageError('AIWS_USAGE', `${label}: pass --${textKey.replace(/_/g, '-')} or --${fileKey.replace(/_/g, '-')}`)
57
75
  }
58
76
 
77
+ // ---- finding and reading. An entity argument is a path (`/data/销售`, `~<entity_id>/…`) or an entity id.
78
+
79
+ const PATH_HELP = 'Path (/data/销售, ~<entity_id>/…) or entity id'
80
+ const TYPE_OPTIONS: OptionDefinition[] = [
81
+ { name: 'type', property: 'type', description: 'Only these types, comma-separated: table, richtext, record, annotation, block, container (container:<kind>), asset, dir, wish, def, …', type: 'string' },
82
+ { name: 'not-type', property: 'not_type', description: 'Leave these types out, comma-separated', type: 'string' },
83
+ ]
84
+ const CURSOR_OPTION: OptionDefinition = { name: 'cursor', property: 'cursor', description: 'Continue from the next_cursor of a previous page', type: 'string' }
85
+ const READ_ACCESS = { mode: 'fixed', level: 'read' } as const
86
+ const WRITE_ACCESS = { mode: 'fixed', level: 'write' } as const
87
+
88
+ /** The keys of `input` that are given, renamed by `names` ({ input key: param }). */
89
+ function given(input: Record<string, unknown>, names: Record<string, string>): Record<string, unknown> {
90
+ const out: Record<string, unknown> = {}
91
+ for (const [key, param] of Object.entries(names)) {
92
+ const v = input[key]
93
+ if (typeof v === 'string' ? v.trim() !== '' : v !== undefined && v !== false) out[param] = typeof v === 'string' ? v.trim() : v
94
+ }
95
+ return out
96
+ }
97
+
98
+ function jsonArg(text: string, label: string): unknown {
99
+ try {
100
+ return JSON.parse(text) as unknown
101
+ } catch (error) {
102
+ throw new UsageError('AIWS_USAGE', `${label}: ${error instanceof Error ? error.message : String(error)}`)
103
+ }
104
+ }
105
+
59
106
  const readCommand: CommandDefinition = {
60
107
  verb: 'read',
61
- summary: 'Read one entity of a workspace (envelope and content)',
62
- positionals: [{ name: 'entity_id', description: 'Entity id', required: true } satisfies PositionalDefinition],
108
+ summary: 'Read one entity of a workspace: envelope and native content',
109
+ positionals: [{ name: 'entity_id', description: PATH_HELP, required: true } satisfies PositionalDefinition],
63
110
  options: [WORKSPACE_OPTION, { name: 'selector', property: 'selector', description: 'Selector JSON, e.g. {"kind":"table_record","record_id":"r1"}', type: 'string' }],
64
111
  inputSchema: workspaceInput({ entity_id: { type: 'string', minLength: 1 }, selector: { type: 'string' } }, ['entity_id']),
65
112
  outputSchema: OBJECT_OUTPUT,
66
113
  resultSchemaVersion: 1,
67
- access: { mode: 'fixed', level: 'read' },
114
+ access: READ_ACCESS,
68
115
  asyncMode: 'sync',
69
116
  requiresSession: true,
70
- examples: ['buckyos aiws read orders --workspace ws_abc'],
117
+ examples: ['buckyos aiws read orders --workspace ws_abc', 'buckyos aiws read /data/订单 --workspace ws_abc --selector \'{"kind":"table_record","record_id":"r1"}\''],
71
118
  handler: (ctx, input) => {
72
119
  const selector = inputString(input, 'selector')
73
- return aiws(ctx, 'doc.read', { workspace_id: requiredInputString(input, 'workspace_id'), entity_id: requiredInputString(input, 'entity_id'), ...(selector ? { selector: JSON.parse(selector) } : {}) })
120
+ return aiws(ctx, 'doc.read', { workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'entity_id')), ...(selector ? { selector: jsonArg(selector, '--selector') } : {}) })
74
121
  },
75
122
  }
76
123
 
77
- const queryCommand: CommandDefinition = {
78
- verb: 'query',
79
- summary: 'Query the rows of a table (or through a saved view)',
124
+ const lsCommand: CommandDefinition = {
125
+ verb: 'ls',
126
+ summary: 'The direct children of a path (default /), in tree order: name, path, type, title, children, body state',
127
+ positionals: [{ name: 'path', description: `${PATH_HELP} (default /)`, required: false }],
128
+ 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],
129
+ inputSchema: workspaceInput({ path: { type: 'string' }, type: { type: 'string' }, not_type: { type: 'string' }, schema: { type: 'string' }, limit: { type: 'integer', minimum: 1 }, cursor: { type: 'string' } }),
130
+ outputSchema: OBJECT_OUTPUT,
131
+ resultSchemaVersion: 1,
132
+ access: READ_ACCESS,
133
+ asyncMode: 'sync',
134
+ requiresSession: true,
135
+ examples: ['buckyos aiws ls --workspace ws_abc', 'buckyos aiws ls /data --workspace ws_abc --type table'],
136
+ 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' }) }),
137
+ }
138
+
139
+ const findCommand: CommandDefinition = {
140
+ verb: 'find',
141
+ summary: 'Entities whose name or title holds a literal (case-insensitive), by type and schema, walking down from a path',
142
+ 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.',
143
+ positionals: [{ name: 'text', description: 'Literal looked for in names and titles', required: false }],
144
+ 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],
145
+ 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' } }),
146
+ outputSchema: OBJECT_OUTPUT,
147
+ resultSchemaVersion: 1,
148
+ access: READ_ACCESS,
149
+ asyncMode: 'sync',
150
+ requiresSession: true,
151
+ examples: ['buckyos aiws find 销售 --workspace ws_abc', 'buckyos aiws find --workspace ws_abc --type table --at /data'],
152
+ 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' }) }),
153
+ }
154
+
155
+ const grepCommand: CommandDefinition = {
156
+ verb: 'grep',
157
+ 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',
158
+ 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.',
159
+ positionals: [{ name: 'text', description: 'Literal to look for', required: true }],
160
+ 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],
161
+ 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']),
162
+ outputSchema: OBJECT_OUTPUT,
163
+ resultSchemaVersion: 1,
164
+ access: READ_ACCESS,
165
+ asyncMode: 'sync',
166
+ requiresSession: true,
167
+ examples: ['buckyos aiws grep 华东 --workspace ws_abc', 'buckyos aiws grep "Q4 plan" --workspace ws_abc --at /docs --type richtext'],
168
+ 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' }) }),
169
+ }
170
+
171
+ // ---- permissions (buckyos notepads/aiws-permission-system-prd.md §4; README “Permissions”): entries `subject × resource
172
+ // → allow, deny` addressed by path, logical groups, anonymous access, inner-path publications, the operation record.
173
+ const SUBJECT_HELP = 'A principal (user id, DID), @<group>, @all, @guest or @creator'
174
+ const caps = (text: string | undefined): string[] => (text ? ids(text) : [])
175
+
176
+ const aclCommand: CommandDefinition = {
177
+ verb: 'acl',
178
+ summary: 'Read permissions: `ls` (every entry, or your own), `show <path>` (who holds what on it and from where), `who [subject]` (a subject\'s entries; a principal\'s groups), `explain <path> [--principal]` (why each capability is allowed or refused), `groups`, `entries` (share links), `audit` (the operation record)',
179
+ 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.',
180
+ positionals: [
181
+ { name: 'action', description: 'ls | show | who | explain | groups | entries | audit', required: true },
182
+ { name: 'target', description: `show / explain: ${PATH_HELP} (default /); who: ${SUBJECT_HELP}`, required: false },
183
+ ],
80
184
  options: [
81
185
  WORKSPACE_OPTION,
82
- { name: 'source', property: 'source_id', description: 'Table entity id', type: 'string' },
83
- { name: 'view', property: 'view_id', description: 'Table view (Block) id', type: 'string' },
84
- { name: 'filter', property: 'filter', description: 'Filter JSON (README: doc.query)', type: 'string' },
85
- { name: 'limit', property: 'limit', description: 'Rows per page (≤ 1000)', type: 'integer' },
86
- { name: 'cursor', property: 'cursor', description: 'Continue from a previous page', type: 'string' },
186
+ { name: 'principal', property: 'principal', description: 'explain: whose permissions (default: yours; another\'s needs manage)', type: 'string' },
187
+ { name: 'expand', property: 'expand', description: 'show: list the members of each group', type: 'boolean' },
188
+ { name: 'after', property: 'after', description: 'audit: records after this sequence number', type: 'integer' },
189
+ { name: 'limit', property: 'limit', description: 'audit: at most this many records (≤ 1000)', type: 'integer' },
87
190
  ],
88
- inputSchema: workspaceInput({ source_id: { type: 'string' }, view_id: { type: 'string' }, filter: { type: 'string' }, limit: { type: 'integer' }, cursor: { type: 'string' } }),
191
+ inputSchema: workspaceInput({
192
+ action: { type: 'string', enum: ['ls', 'show', 'who', 'explain', 'groups', 'entries', 'audit'] }, target: { type: 'string' }, principal: { type: 'string' },
193
+ expand: { type: 'boolean' }, after: { type: 'integer' }, limit: { type: 'integer', minimum: 1 },
194
+ }, ['action']),
89
195
  outputSchema: OBJECT_OUTPUT,
90
196
  resultSchemaVersion: 1,
91
- access: { mode: 'fixed', level: 'read' },
197
+ access: READ_ACCESS,
92
198
  asyncMode: 'sync',
93
199
  requiresSession: true,
94
- examples: ['buckyos aiws query --workspace ws_abc --source orders --limit 100'],
200
+ examples: [
201
+ 'buckyos aiws acl show /data/成绩 --workspace ws_abc',
202
+ 'buckyos aiws acl explain /data/成绩 --principal bob --workspace ws_abc',
203
+ 'buckyos aiws acl who @teachers --workspace ws_abc',
204
+ 'buckyos aiws acl groups --workspace ws_abc',
205
+ ],
95
206
  handler: (ctx, input) => {
96
- const params: Record<string, unknown> = { workspace_id: requiredInputString(input, 'workspace_id') }
97
- for (const key of ['source_id', 'view_id', 'cursor']) { const value = inputString(input, key); if (value) params[key] = value }
98
- const filter = inputString(input, 'filter')
99
- if (filter) params.filter = JSON.parse(filter)
100
- if (typeof input.limit === 'number') params.limit = input.limit
101
- if (!params.source_id && !params.view_id) throw new UsageError('AIWS_USAGE', 'pass --source or --view')
102
- return aiws(ctx, 'doc.query', params)
207
+ const workspace_id = requiredInputString(input, 'workspace_id')
208
+ const target = inputString(input, 'target')
209
+ switch (requiredInputString(input, 'action')) {
210
+ case 'ls': return aiws(ctx, 'acl.query', { workspace_id, by: 'all' })
211
+ case 'show': return aiws(ctx, 'acl.query', { workspace_id, by: 'entity', resource: target ?? '/', ...given(input, { expand: 'expand' }) })
212
+ case 'who': return aiws(ctx, 'acl.query', { workspace_id, by: 'subject', ...(target ? { subject: target } : {}) })
213
+ case 'explain': return aiws(ctx, 'acl.query', { workspace_id, by: 'explain', resource: target ?? '/', ...given(input, { principal: 'principal' }) })
214
+ case 'groups': return aiws(ctx, 'acl.groups', { workspace_id })
215
+ case 'entries': return aiws(ctx, 'ws.list_entries', { workspace_id })
216
+ case 'audit': return aiws(ctx, 'acl.audit', { workspace_id, ...given(input, { after: 'after', limit: 'limit' }) })
217
+ default: throw new UsageError('AIWS_USAGE', 'acl: ls, show, who, explain, groups, entries or audit')
218
+ }
219
+ },
220
+ }
221
+
222
+ const aclEditCommand: CommandDefinition = {
223
+ verb: 'acl-edit',
224
+ summary: 'Change permissions: `set <subject> <path> --allow … --deny …` (replaces that entry; both empty removes it), `rm <subject> <path>`, `group-add <id> [--title]`, `group-rm <id>`, `member-add <group> <members>`, `member-rm <group> <members>`, `anonymous on|off`, `bind <wish> <group|none> [--mode]`, `entry-add <group> --methods …`, `entry-close <entry_id> [--remove-members]`, `publish <path> [--name]`, `unpublish <path>`',
225
+ description: 'Needs manage (giving or taking manage, or changing the members of a group holding it, is the owner\'s). Members: a principal, group:<system group>, contact:<your did>#<tag>, * (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.',
226
+ positionals: [
227
+ { name: 'action', description: 'set | rm | group-add | group-rm | member-add | member-rm | anonymous | bind | entry-add | entry-close | publish | unpublish', required: true },
228
+ { 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 },
229
+ { name: 'arg', description: `set / rm: ${PATH_HELP} (default /); member-*: members, comma-separated; bind: group id or none`, required: false },
230
+ ],
231
+ options: [
232
+ WORKSPACE_OPTION,
233
+ { name: 'allow', property: 'allow', description: 'set: capabilities, comma-separated (read, append, update, delete, structure, comment, export, manage, run)', type: 'string' },
234
+ { name: 'deny', property: 'deny', description: 'set: capabilities refused, comma-separated', type: 'string' },
235
+ { name: 'title', property: 'title', description: 'group-add: the group\'s title', type: 'string' },
236
+ { name: 'description', property: 'description', description: 'group-add: what the group is for', type: 'string' },
237
+ { name: 'mode', property: 'mode', description: 'bind: union (default) or intersection with the triggerer\'s permissions', type: 'string', enum: ['union', 'intersection'] },
238
+ { name: 'methods', property: 'methods', description: 'entry-add: ways in, comma-separated: guest, password, self_register, did_login', type: 'string' },
239
+ { name: 'expires-at', property: 'expires_at', description: 'entry-add: unix seconds', type: 'integer' },
240
+ { name: 'max-joins', property: 'max_joins', description: 'entry-add: how many may join at most', type: 'integer' },
241
+ { name: 'remove-members', property: 'remove_members', description: 'entry-close: those who joined through it leave the group too', type: 'boolean' },
242
+ { name: 'name', property: 'name', description: 'publish: the last segment of the link', type: 'string' },
243
+ ],
244
+ inputSchema: workspaceInput({
245
+ action: { type: 'string', enum: ['set', 'rm', 'group-add', 'group-rm', 'member-add', 'member-rm', 'anonymous', 'bind', 'entry-add', 'entry-close', 'publish', 'unpublish'] },
246
+ target: { type: 'string' }, arg: { type: 'string' }, allow: { type: 'string' }, deny: { type: 'string' }, title: { type: 'string' }, description: { type: 'string' },
247
+ mode: { type: 'string', enum: ['union', 'intersection'] }, methods: { type: 'string' }, expires_at: { type: 'integer' }, max_joins: { type: 'integer', minimum: 1 },
248
+ remove_members: { type: 'boolean' }, name: { type: 'string' },
249
+ }, ['action']),
250
+ outputSchema: OBJECT_OUTPUT,
251
+ resultSchemaVersion: 1,
252
+ access: WRITE_ACCESS,
253
+ asyncMode: 'sync',
254
+ requiresSession: true,
255
+ examples: [
256
+ 'buckyos aiws acl-edit group-add teachers --title 老师 --workspace ws_abc',
257
+ 'buckyos aiws acl-edit member-add teachers group:staff,bob --workspace ws_abc',
258
+ 'buckyos aiws acl-edit set @teachers /data/成绩 --allow read,update --workspace ws_abc',
259
+ 'buckyos aiws acl-edit set @all /data/工资 --deny read --workspace ws_abc',
260
+ 'buckyos aiws acl-edit anonymous on --workspace ws_abc',
261
+ 'buckyos aiws acl-edit entry-add visitors --methods guest,password --workspace ws_abc',
262
+ ],
263
+ handler: async (ctx, input) => {
264
+ const workspace_id = requiredInputString(input, 'workspace_id')
265
+ const target = () => requiredInputString(input, 'target')
266
+ const arg = inputString(input, 'arg')
267
+ 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)
268
+ switch (requiredInputString(input, 'action')) {
269
+ case 'set': return aiws(ctx, 'acl.set', { workspace_id, changes: [{ subject: target(), resource: arg ?? '/', allow: caps(inputString(input, 'allow')), deny: caps(inputString(input, 'deny')) }] })
270
+ case 'rm': return aiws(ctx, 'acl.set', { workspace_id, changes: [{ subject: target(), resource: arg ?? '/' }] })
271
+ case 'group-add': return aiws(ctx, 'acl.set_group', { workspace_id, group_id: target(), ...given(input, { title: 'title', description: 'description' }) })
272
+ case 'group-rm': return aiws(ctx, 'acl.delete_group', { workspace_id, group_id: target() })
273
+ case 'member-add': return aiws(ctx, 'acl.members', { workspace_id, group_id: target(), add: ids(arg ?? '') })
274
+ case 'member-rm': return aiws(ctx, 'acl.members', { workspace_id, group_id: target(), remove: ids(arg ?? '') })
275
+ case 'anonymous': {
276
+ const on = target()
277
+ if (on !== 'on' && on !== 'off') throw new UsageError('AIWS_USAGE', 'anonymous on | off')
278
+ return aiws(ctx, 'acl.set_anonymous', { workspace_id, enabled: on === 'on' })
279
+ }
280
+ case 'bind': return aiws(ctx, 'acl.bind_macro', { workspace_id, wish: target(), group_id: !arg || arg === 'none' ? null : arg, ...given(input, { mode: 'mode' }) })
281
+ case 'entry-add': {
282
+ const methods = Object.fromEntries(ids(requiredInputString(input, 'methods')).map((m) => [m, true]))
283
+ return aiws(ctx, 'ws.create_entry', { workspace_id, group_id: target(), methods, ...given(input, { expires_at: 'expires_at', max_joins: 'max_joins' }) })
284
+ }
285
+ case 'entry-close': return aiws(ctx, 'ws.close_entry', { workspace_id, entry_id: target(), ...given(input, { remove_members: 'remove_members' }) })
286
+ case 'publish': return aiws(ctx, 'ws.publish', { workspace_id, entity_id: await entityId(target()), ...given(input, { name: 'name' }) })
287
+ case 'unpublish': return aiws(ctx, 'ws.unpublish', { workspace_id, entity_id: await entityId(target()) })
288
+ 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')
289
+ }
103
290
  },
104
291
  }
105
292
 
293
+ const statCommand: CommandDefinition = {
294
+ verb: 'stat',
295
+ 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',
296
+ positionals: [{ name: 'path', description: PATH_HELP, required: true }],
297
+ options: [WORKSPACE_OPTION],
298
+ inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 } }, ['path']),
299
+ outputSchema: OBJECT_OUTPUT,
300
+ resultSchemaVersion: 1,
301
+ access: READ_ACCESS,
302
+ asyncMode: 'sync',
303
+ requiresSession: true,
304
+ examples: ['buckyos aiws stat /data/销售 --workspace ws_abc'],
305
+ handler: (ctx, input) => aiws(ctx, 'doc.read', { workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'path')), as: 'meta' }),
306
+ }
307
+
308
+ /** Pages of a body followed at most this far (32 KiB each by default). */
309
+ const CAT_MAX_PAGES = 512
310
+
311
+ const catCommand: CommandDefinition = {
312
+ verb: 'cat',
313
+ 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',
314
+ 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.',
315
+ positionals: [{ name: 'path', description: PATH_HELP, required: true }],
316
+ options: [
317
+ WORKSPACE_OPTION,
318
+ { name: 'selector', property: 'selector', description: 'Only this part, selector JSON, e.g. {"kind":"richtext_block","block_id":"b3"}', type: 'string' },
319
+ { name: 'max-bytes', property: 'max_bytes', description: 'One page of at most this many bytes (64…262144)', type: 'integer' },
320
+ CURSOR_OPTION,
321
+ ],
322
+ inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, selector: { type: 'string' }, max_bytes: { type: 'integer', minimum: 64 }, cursor: { type: 'string' } }, ['path']),
323
+ outputSchema: OBJECT_OUTPUT,
324
+ resultSchemaVersion: 1,
325
+ access: READ_ACCESS,
326
+ asyncMode: 'sync',
327
+ requiresSession: true,
328
+ examples: ['buckyos aiws cat /docs/周报 --workspace ws_abc --output text', 'buckyos aiws cat /data/销售 --workspace ws_abc --max-bytes 4096'],
329
+ handler: async (ctx, input) => {
330
+ const selector = inputString(input, 'selector')
331
+ const request = {
332
+ workspace_id: requiredInputString(input, 'workspace_id'), ...aiwsTarget(requiredInputString(input, 'path')), as: 'body',
333
+ ...(selector ? { selector: jsonArg(selector, '--selector') } : {}), ...given(input, { max_bytes: 'max_bytes' }),
334
+ }
335
+ let page = await aiws(ctx, 'doc.read', { ...request, ...given(input, { cursor: 'cursor' }) })
336
+ if (input.max_bytes !== undefined || inputString(input, 'cursor')) return page
337
+ let text = String(page.text ?? '')
338
+ for (let n = 1; page.complete === false && typeof page.next_cursor === 'string' && n < CAT_MAX_PAGES; n++) {
339
+ page = await aiws(ctx, 'doc.read', { ...request, cursor: page.next_cursor })
340
+ text += String(page.text ?? '')
341
+ }
342
+ const { parts: _parts, ...last } = page
343
+ return { ...last, text }
344
+ },
345
+ }
346
+
347
+ const resolveCommand: CommandDefinition = {
348
+ verb: 'resolve',
349
+ summary: 'A path (or entity id) as a reference: entity id, canonical reference, path and name',
350
+ positionals: [{ name: 'path', description: PATH_HELP, required: true }],
351
+ options: [WORKSPACE_OPTION],
352
+ inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 } }, ['path']),
353
+ outputSchema: OBJECT_OUTPUT,
354
+ resultSchemaVersion: 1,
355
+ access: READ_ACCESS,
356
+ asyncMode: 'sync',
357
+ requiresSession: true,
358
+ examples: ['buckyos aiws resolve /data/销售 --workspace ws_abc'],
359
+ handler: (ctx, input) => {
360
+ const target = aiwsTarget(requiredInputString(input, 'path'))
361
+ return aiws(ctx, 'doc.resolve', { workspace_id: requiredInputString(input, 'workspace_id'), ...('path' in target ? target : { reference: { entity_id: target.entity_id, mode: 'live' } }) })
362
+ },
363
+ }
364
+
365
+ /** `--table a=/data/销售,b=orders`: aliases of the tables a query reads (a path may hold commas; a pair starts at
366
+ * `<alias>=`). */
367
+ function tableAliases(text: string): Record<string, string> {
368
+ const out: Record<string, string> = {}
369
+ for (const pair of text.split(/,(?=\s*[A-Za-z_][A-Za-z0-9_]*=)/)) {
370
+ const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)=(.+?)\s*$/.exec(pair)
371
+ if (!m) throw new UsageError('AIWS_USAGE', `--table ${pair}: <alias>=<path or entity id>`)
372
+ out[m[1]] = m[2]
373
+ }
374
+ return out
375
+ }
376
+
377
+ const sqlCommand: CommandDefinition = {
378
+ verb: 'sql',
379
+ summary: 'One SQL SELECT over the tables of a workspace: a table is named by its path in double quotes (FROM "/data/销售"), "~<entity_id>", or an alias of --table',
380
+ description: 'Columns: _id (record id), _rev, _body (path of the record body), _record (the record as doc.read gives it, JSON), and per field "<name>" (display value: select label, multi-select JSON array of labels, reference path, decimal / currency amount as a number, boolean 1/0) and "<name>#raw" (stored value: option ids, exact decimal, reference / currency JSON); currency also "<name>#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).',
381
+ positionals: [{ name: 'sql', description: 'The SELECT statement', required: true }],
382
+ options: [
383
+ WORKSPACE_OPTION,
384
+ { name: 'table', property: 'table', description: 'Aliases: alias=<path or entity id>[,alias=…]; only these tables are visible then', type: 'string' },
385
+ { name: 'params', property: 'params', description: 'Positional parameters (?) as a JSON array', type: 'string' },
386
+ { name: 'max-rows', property: 'max_rows', description: 'Rows at most (≤ 5000, default 1000)', type: 'integer' },
387
+ ],
388
+ inputSchema: workspaceInput({ sql: { type: 'string', minLength: 1 }, table: { type: 'string' }, params: { type: 'string' }, max_rows: { type: 'integer', minimum: 1 } }, ['sql']),
389
+ outputSchema: OBJECT_OUTPUT,
390
+ resultSchemaVersion: 1,
391
+ access: READ_ACCESS,
392
+ asyncMode: 'sync',
393
+ requiresSession: true,
394
+ examples: [
395
+ 'buckyos aiws sql \'SELECT "客户", SUM("金额") AS total FROM "/data/销售" GROUP BY "客户" ORDER BY total DESC LIMIT 10\' --workspace ws_abc',
396
+ 'buckyos aiws sql \'SELECT "_id", "客户", "金额" FROM t WHERE "状态" = ? LIMIT 20\' --table t=/data/销售 --params \'["已完成"]\' --workspace ws_abc',
397
+ ],
398
+ handler: (ctx, input) => {
399
+ const table = inputString(input, 'table')
400
+ const params = inputString(input, 'params')
401
+ const values = params ? jsonArg(params, '--params') : undefined
402
+ if (values !== undefined && !Array.isArray(values)) throw new UsageError('AIWS_USAGE', '--params is a JSON array')
403
+ return aiws(ctx, 'doc.query', {
404
+ workspace_id: requiredInputString(input, 'workspace_id'), sql: requiredInputString(input, 'sql'),
405
+ ...(table ? { tables: tableAliases(table) } : {}), ...(values ? { params: values } : {}), ...given(input, { max_rows: 'max_rows' }),
406
+ })
407
+ },
408
+ }
409
+
410
+ // ---- writing: the operations of buckyos-websdk src/aiws_write.ts, committed as one Commit each (an idempotency key, and
411
+ // on an unknown result doc.get_submission, then the same key again). Field names, option labels and `expect` come from
412
+ // what is read just before.
413
+
414
+ type TableRead = Parameters<typeof tableInsert>[0]
415
+ type RichTextRead = Parameters<typeof textReplaceBlock>[0]
416
+ type EntityRead = Parameters<typeof rename>[0]
417
+
418
+ /** The service as the SDK's write helpers take it: a business failure is an `AiwsFailure`, never an unknown result. */
419
+ function writeTransport(ctx: CommandContext) {
420
+ return {
421
+ call: async <T,>(method: string, params: Record<string, unknown>): Promise<T> => {
422
+ const result = expectObject(await callService<unknown>(ctx, SERVICE, method, params), method)
423
+ if (result.ok === false) {
424
+ const error = expectObject(result.error, `${method}.error`)
425
+ 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 })
426
+ }
427
+ return result as T
428
+ },
429
+ }
430
+ }
431
+
432
+ /** A refusal (of the service, or of a helper: an unknown field, a block not read) as the CLI's error, its code first. */
433
+ async function writing<T>(work: () => Promise<T>): Promise<T> {
434
+ try {
435
+ return await work()
436
+ } catch (error) {
437
+ 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 } : {}) })
438
+ throw error
439
+ }
440
+ }
441
+
442
+ async function commit(ctx: CommandContext, ws: string, ops: Record<string, unknown>[], message: string): Promise<Record<string, unknown>> {
443
+ const result = await commitOps(writeTransport(ctx), ws, ops as never, { message, ...(ctx.idempotencyKey ? { idempotencyKey: ctx.idempotencyKey } : {}) })
444
+ return { ok: true, status: result.status, commit_id: result.commit_id, seq: result.seq }
445
+ }
446
+
447
+ /** The envelope of an entity (ids and revs) without its content. */
448
+ function envelopeOf(ctx: CommandContext, ws: string, target: string): Promise<Record<string, unknown>> {
449
+ return aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target), selector: { kind: 'doc_key', key: 'title' } })
450
+ }
451
+
452
+ const ids = (text: string) => text.split(',').map((s) => s.trim()).filter(Boolean)
453
+
454
+ async function markdownInput(input: Record<string, unknown>): Promise<string> {
455
+ const text = typeof input.text === 'string' ? input.text : undefined
456
+ const file = inputString(input, 'file')
457
+ if ((text !== undefined) === (file !== undefined)) throw new UsageError('AIWS_USAGE', 'pass --file <md> or --text <markdown>')
458
+ return file ? await getHost().readTextFile(file) : text!
459
+ }
460
+
461
+ const tableCommand: CommandDefinition = {
462
+ verb: 'table',
463
+ summary: 'Write a table: `add <table> --values` (records), `set <table> <record_id> --values` (cells), `rm <table> <record_id>[,…]`, `field-add <table> --name --type`, `option-add <table> <field> <label>`',
464
+ description: '--values is JSON keyed by field name with display values (a select takes its label, a multi-select labels, a reference an entity id; null clears a cell on set); add takes an object or an array of them, "_id" naming a record id. Each change is expected at the version just read: a concurrent change of the same cell is a REVISION_CONFLICT (read again). field-add --type: text, number, decimal, boolean, date, datetime, select, multi_select, object_ref, currency, json; --options gives a select its labels.',
465
+ positionals: [
466
+ { name: 'action', description: 'add | set | rm | field-add | option-add', required: true },
467
+ { name: 'table', description: `The table: ${PATH_HELP}`, required: true },
468
+ { name: 'target', description: 'set: record id; rm: record ids, comma-separated; option-add: field name', required: false },
469
+ { name: 'label', description: 'option-add: the new option label', required: false },
470
+ ],
471
+ options: [
472
+ WORKSPACE_OPTION,
473
+ { name: 'values', property: 'values', description: 'add / set: JSON keyed by field name', type: 'string' },
474
+ { name: 'name', property: 'name', description: 'field-add: the field name', type: 'string' },
475
+ { name: 'type', property: 'type', description: 'field-add: the field type', type: 'string', enum: ['text', 'number', 'decimal', 'boolean', 'date', 'datetime', 'select', 'multi_select', 'object_ref', 'currency', 'json'] },
476
+ { name: 'options', property: 'options', description: 'field-add: option labels of a select, a JSON array or comma-separated', type: 'string' },
477
+ ],
478
+ inputSchema: workspaceInput({
479
+ action: { type: 'string', enum: ['add', 'set', 'rm', 'field-add', 'option-add'] }, table: { type: 'string', minLength: 1 }, target: { type: 'string' }, label: { type: 'string' },
480
+ values: { type: 'string' }, name: { type: 'string' }, type: { type: 'string' }, options: { type: 'string' },
481
+ }, ['action', 'table']),
482
+ outputSchema: OBJECT_OUTPUT,
483
+ resultSchemaVersion: 1,
484
+ access: WRITE_ACCESS,
485
+ asyncMode: 'sync',
486
+ requiresSession: true,
487
+ examples: [
488
+ 'buckyos aiws table add /data/销售 --values \'{"客户":"ACME","金额":"1200.50","状态":"进行中"}\' --workspace ws_abc',
489
+ 'buckyos aiws table set /data/销售 r123 --values \'{"状态":"已完成"}\' --workspace ws_abc',
490
+ 'buckyos aiws table rm /data/销售 r123,r124 --workspace ws_abc',
491
+ 'buckyos aiws table field-add /data/销售 --name 负责人 --type text --workspace ws_abc',
492
+ 'buckyos aiws table option-add /data/销售 状态 已取消 --workspace ws_abc',
493
+ ],
494
+ handler: (ctx, input) => writing(async () => {
495
+ const ws = requiredInputString(input, 'workspace_id')
496
+ const action = requiredInputString(input, 'action')
497
+ const tablePath = requiredInputString(input, 'table')
498
+ const values = () => {
499
+ const v = jsonArg(requiredInputString(input, 'values'), '--values')
500
+ if (!v || typeof v !== 'object') throw new UsageError('AIWS_USAGE', '--values is a JSON object keyed by field name')
501
+ return v as Record<string, unknown> | Record<string, unknown>[]
502
+ }
503
+ if (action === 'rm') {
504
+ const records = ids(requiredInputString(input, 'target'))
505
+ const reads = await Promise.all(records.map((record_id) => aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(tablePath), selector: { kind: 'table_record', record_id } })))
506
+ const table = String(reads[0].entity_id)
507
+ return { ...await commit(ctx, ws, tableDelete(table, records, reads as never), `delete ${records.length} record(s)`), table, removed: records }
508
+ }
509
+ const table = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(tablePath) }) as unknown as TableRead
510
+ switch (action) {
511
+ case 'add': {
512
+ const rows = values()
513
+ const ops = tableInsert(table, Array.isArray(rows) ? rows : [rows])
514
+ const record_ids = ((ops[0]?.records ?? []) as { record_id: string }[]).map((r) => r.record_id)
515
+ return { ...await commit(ctx, ws, ops, `add ${record_ids.length} record(s)`), table: table.entity_id, record_ids }
516
+ }
517
+ case 'set': {
518
+ const record_id = requiredInputString(input, 'target')
519
+ const v = values()
520
+ if (Array.isArray(v)) throw new UsageError('AIWS_USAGE', 'set takes one --values object')
521
+ const read = await aiws(ctx, 'doc.read', { workspace_id: ws, entity_id: table.entity_id, selector: { kind: 'table_record', record_id } })
522
+ const ops = tableSet(table, record_id, v, read as never)
523
+ if (ops.length === 0) return { ok: true, status: 'unchanged', table: table.entity_id, record_id }
524
+ return { ...await commit(ctx, ws, ops, `update record ${record_id}`), table: table.entity_id, record_id }
525
+ }
526
+ case 'field-add': {
527
+ const options = inputString(input, 'options')
528
+ const labels = options === undefined ? undefined : options.startsWith('[') ? jsonArg(options, '--options') as string[] : ids(options)
529
+ const op = fieldAdd(table, { name: requiredInputString(input, 'name'), type: requiredInputString(input, 'type'), ...(labels ? { options: labels } : {}) })
530
+ const field = op.field as { field_id: string; options?: unknown[] }
531
+ return { ...await commit(ctx, ws, [op], `add field ${requiredInputString(input, 'name')}`), table: table.entity_id, field_id: field.field_id, ...(field.options ? { options: field.options } : {}) }
532
+ }
533
+ case 'option-add': {
534
+ const op = optionAdd(table, requiredInputString(input, 'target'), requiredInputString(input, 'label'))
535
+ return { ...await commit(ctx, ws, [op], `add option ${requiredInputString(input, 'label')}`), table: table.entity_id, field_id: op.field_id, option: op.option }
536
+ }
537
+ default:
538
+ throw new UsageError('AIWS_USAGE', `table: add, set, rm, field-add or option-add, not ${action}`)
539
+ }
540
+ }),
541
+ }
542
+
543
+ const textCommand: CommandDefinition = {
544
+ verb: 'text',
545
+ summary: 'Write a rich text by blocks from Markdown: `append <doc> --file <md>`, `replace <doc> <block_id> --file <md>`, `rm <doc> <block_id>[,…]`',
546
+ description: 'Markdown: headings, paragraphs, bullet / ordered / task lists, fenced code, quotes, rules, pipe tables, inline code, strong, emphasis, strike and links ([label](entity:<id>) links an entity). Block ids are in the rich text as `doc.read` answers it (content.blocks) and in the selectors of `grep` hits; a replaced or removed block is expected at the version just read (REVISION_CONFLICT when it changed meanwhile). replace keeps the block id for the first block of the Markdown and inserts the rest after it.',
547
+ positionals: [
548
+ { name: 'action', description: 'append | replace | rm', required: true },
549
+ { name: 'doc', description: `The rich text: ${PATH_HELP}`, required: true },
550
+ { name: 'block', description: 'replace: block id; rm: block ids, comma-separated', required: false },
551
+ ],
552
+ options: [
553
+ WORKSPACE_OPTION,
554
+ { name: 'file', property: 'file', description: 'append / replace: a local Markdown file', type: 'string' },
555
+ { name: 'text', property: 'text', description: 'append / replace: the Markdown itself', type: 'string' },
556
+ ],
557
+ inputSchema: workspaceInput({ action: { type: 'string', enum: ['append', 'replace', 'rm'] }, doc: { type: 'string', minLength: 1 }, block: { type: 'string' }, file: { type: 'string' }, text: { type: 'string' } }, ['action', 'doc']),
558
+ outputSchema: OBJECT_OUTPUT,
559
+ resultSchemaVersion: 1,
560
+ access: WRITE_ACCESS,
561
+ asyncMode: 'sync',
562
+ requiresSession: true,
563
+ examples: [
564
+ 'buckyos aiws text append /docs/周报 --file notes.md --workspace ws_abc',
565
+ 'buckyos aiws text replace /docs/周报 b12 --text "## 下周计划" --workspace ws_abc',
566
+ 'buckyos aiws text rm /docs/周报 b12,b13 --workspace ws_abc',
567
+ ],
568
+ handler: (ctx, input) => writing(async () => {
569
+ const ws = requiredInputString(input, 'workspace_id')
570
+ const action = requiredInputString(input, 'action')
571
+ const target = requiredInputString(input, 'doc')
572
+ if (action === 'append') {
573
+ const markdown = await markdownInput(input)
574
+ const doc = String((await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target), as: 'meta' })).entity_id)
575
+ const ops = textAppend(doc, markdown)
576
+ const blocks = (ops[0].blocks as { attrs: { block_id: string } }[]).map((b) => b.attrs.block_id)
577
+ return { ...await commit(ctx, ws, ops, 'append text'), doc, blocks }
578
+ }
579
+ if (action !== 'replace' && action !== 'rm') throw new UsageError('AIWS_USAGE', `text: append, replace or rm, not ${action}`)
580
+ const markdown = action === 'replace' ? await markdownInput(input) : ''
581
+ const doc = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target) }) as unknown as RichTextRead
582
+ if (action === 'rm') {
583
+ const blocks = ids(requiredInputString(input, 'block'))
584
+ return { ...await commit(ctx, ws, textDeleteBlocks(doc, blocks), `delete ${blocks.length} block(s)`), doc: doc.entity_id, removed: blocks }
585
+ }
586
+ const block = requiredInputString(input, 'block')
587
+ const ops = textReplaceBlock(doc, block, markdown)
588
+ const added = ops.length > 1 ? ((ops[1] as Record<string, unknown>).blocks as { attrs: { block_id: string } }[]).map((b) => b.attrs.block_id) : []
589
+ return { ...await commit(ctx, ws, ops, `replace block ${block}`), doc: doc.entity_id, blocks: [block, ...added] }
590
+ }),
591
+ }
592
+
593
+ const mvCommand: CommandDefinition = {
594
+ verb: 'mv',
595
+ summary: 'Move an entity under another parent, after its last child (a following name moves aside if taken there)',
596
+ positionals: [{ name: 'path', description: PATH_HELP, required: true }, { name: 'parent', description: `The new parent: ${PATH_HELP}`, required: true }],
597
+ options: [WORKSPACE_OPTION],
598
+ inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, parent: { type: 'string', minLength: 1 } }, ['path', 'parent']),
599
+ outputSchema: OBJECT_OUTPUT,
600
+ resultSchemaVersion: 1,
601
+ access: WRITE_ACCESS,
602
+ asyncMode: 'sync',
603
+ requiresSession: true,
604
+ examples: ['buckyos aiws mv /data/草稿 /archive --workspace ws_abc'],
605
+ handler: (ctx, input) => writing(async () => {
606
+ const ws = requiredInputString(input, 'workspace_id')
607
+ const entity = await envelopeOf(ctx, ws, requiredInputString(input, 'path'))
608
+ const parent = String((await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(requiredInputString(input, 'parent')), as: 'meta' })).entity_id)
609
+ // the new place: after the last child the caller sees there
610
+ let last: string | undefined
611
+ let cursor: string | undefined
612
+ for (let page = 0; page < 100; page++) {
613
+ const listed = await aiws(ctx, 'doc.list', { workspace_id: ws, at: parent, limit: 1000, ...(cursor ? { cursor } : {}) })
614
+ const items = (Array.isArray(listed.items) ? listed.items : []) as { entity_id: string }[]
615
+ last = items.map((i) => i.entity_id).filter((id) => id !== entity.entity_id).at(-1) ?? last
616
+ if (typeof listed.next_cursor !== 'string' || items.length === 0) break
617
+ cursor = listed.next_cursor
618
+ }
619
+ const after = last ? (await envelopeOf(ctx, ws, last)).order_key : undefined
620
+ const op = move(entity as unknown as EntityRead, parent, typeof after === 'string' ? after : null)
621
+ return { ...await commit(ctx, ws, [op], `move ${entity.entity_id}`), entity_id: entity.entity_id, parent }
622
+ }),
623
+ }
624
+
625
+ const renameCommand: CommandDefinition = {
626
+ verb: 'rename',
627
+ summary: 'Give an entity a name of its own (its path segment), or --auto to let it follow its title again',
628
+ positionals: [{ name: 'path', description: PATH_HELP, required: true }, { name: 'name', description: 'The new name (1–128 characters, no /, not starting with ~)', required: false }],
629
+ options: [WORKSPACE_OPTION, { name: 'auto', property: 'auto', description: 'Name it after its title again (or a counter)', type: 'boolean' }],
630
+ inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, name: { type: 'string' }, auto: { type: 'boolean' } }, ['path']),
631
+ outputSchema: OBJECT_OUTPUT,
632
+ resultSchemaVersion: 1,
633
+ access: WRITE_ACCESS,
634
+ asyncMode: 'sync',
635
+ requiresSession: true,
636
+ examples: ['buckyos aiws rename /data/销售 销售-2026 --workspace ws_abc', 'buckyos aiws rename ~sales --auto --workspace ws_abc'],
637
+ handler: (ctx, input) => writing(async () => {
638
+ const ws = requiredInputString(input, 'workspace_id')
639
+ const name = inputString(input, 'name')
640
+ if ((name === undefined) === (input.auto !== true)) throw new UsageError('AIWS_USAGE', 'rename: pass a new name or --auto')
641
+ const entity = await envelopeOf(ctx, ws, requiredInputString(input, 'path'))
642
+ return { ...await commit(ctx, ws, [rename(entity as unknown as EntityRead, name ?? null)], `rename ${entity.entity_id}`), entity_id: entity.entity_id, ...(name ? { name } : {}) }
643
+ }),
644
+ }
645
+
646
+ const setPropCommand: CommandDefinition = {
647
+ verb: 'set-prop',
648
+ summary: 'Set properties of a Block or a container: `config`, `bindings` or `on`, as JSON { <name>: value | null } (null removes one), each expected at the version just read',
649
+ positionals: [
650
+ { name: 'path', description: `The Block or container: ${PATH_HELP}`, required: true },
651
+ { name: 'key', description: 'config | bindings | on', required: true },
652
+ { name: 'props', description: 'JSON object { <name>: value | null }', required: true },
653
+ ],
654
+ options: [WORKSPACE_OPTION],
655
+ inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, key: { type: 'string', enum: ['config', 'bindings', 'on'] }, props: { type: 'string', minLength: 1 } }, ['path', 'key', 'props']),
656
+ outputSchema: OBJECT_OUTPUT,
657
+ resultSchemaVersion: 1,
658
+ access: WRITE_ACCESS,
659
+ asyncMode: 'sync',
660
+ requiresSession: true,
661
+ examples: ['buckyos aiws set-prop /surfaces/看板/kpi config \'{"label":"本月销售"}\' --workspace ws_abc'],
662
+ handler: (ctx, input) => writing(async () => {
663
+ const ws = requiredInputString(input, 'workspace_id')
664
+ const key = requiredInputString(input, 'key')
665
+ if (key !== 'config' && key !== 'bindings' && key !== 'on') throw new UsageError('AIWS_USAGE', 'set-prop: the key is config, bindings or on')
666
+ const props = jsonArg(requiredInputString(input, 'props'), 'props')
667
+ if (!props || typeof props !== 'object' || Array.isArray(props)) throw new UsageError('AIWS_USAGE', 'props is a JSON object { <name>: value | null }')
668
+ const entity = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(requiredInputString(input, 'path')) })
669
+ return { ...await commit(ctx, ws, [setProps(entity as unknown as EntityRead, key, props as Record<string, unknown>)], `set ${key} of ${entity.entity_id}`), entity_id: entity.entity_id }
670
+ }),
671
+ }
672
+
106
673
  const infoCommand: CommandDefinition = {
107
674
  verb: 'info',
108
675
  summary: 'Workspace info: versions, capabilities of the caller, usage, hosted execution configuration',
@@ -167,8 +734,8 @@ const runHeartbeatCommand: CommandDefinition = {
167
734
 
168
735
  const runFilesCommand: CommandDefinition = {
169
736
  verb: 'run-files',
170
- summary: 'Write the stage of a claimed run into a directory: the snapshot (context/), request.json, the Renderer catalog and the program host (lib/)',
171
- description: 'Run the program there the way the service does: `deno run -A lib/run.js` reads program/main.js and writes output/.aiws/results.json.',
737
+ summary: 'Write the stage of a claimed run into a directory: the snapshot (context/), request.json, the Renderer catalog, the program host (lib/, with the stage budget and manifest in lib/stage.json) and, when there is one, program/main.js',
738
+ description: 'Run the macro there with `run-exec` (or `run-program`, which also hands it in): it reads program/main.js and writes output/.aiws/results.json, exactly as every executor runs it.',
172
739
  options: [WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION, { name: 'dir', property: 'dir', description: 'Directory to write into (created)', type: 'string', required: true }],
173
740
  inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, dir: { type: 'string', minLength: 1 } }, ['run_id', 'attempt', 'dir']),
174
741
  outputSchema: { type: 'object', properties: { dir: { type: 'string' }, files: { type: 'array', items: { type: 'string' } } }, required: ['dir', 'files'], additionalProperties: true },
@@ -193,13 +760,15 @@ const runFilesCommand: CommandDefinition = {
193
760
  }
194
761
  await host.mkdir(`${dir}/output`, { recursive: true })
195
762
  await host.mkdir(`${dir}/program`, { recursive: true })
763
+ await host.mkdir(`${dir}/lib`, { recursive: true })
764
+ await host.writeTextFile(`${dir}/lib/stage.json`, JSON.stringify(result.stage ?? {}))
196
765
  return { dir, files: written }
197
766
  },
198
767
  }
199
768
 
200
769
  const runToolCommand: CommandDefinition = {
201
770
  verb: 'run-tool',
202
- summary: 'Call one stage tool of a claimed run (ws_profile, ws_read, ws_query, submit_analysis, put_result, check_results, finish, …): the service answers as it answers the model',
771
+ summary: 'Call one stage tool of a claimed run (ws_profile, ws_read, ws_query, submit_analysis, check_results, finish, …): the service answers as it answers the model',
203
772
  options: [WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION, { name: 'name', property: 'name', description: 'Tool name (the claim answered the list, with their argument schemas)', type: 'string', required: true }, { name: 'args', property: 'args', description: 'Arguments JSON', type: 'string' }, { name: 'args-file', property: 'args_file', description: 'Path of a JSON file holding the arguments', type: 'string' }],
204
773
  inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, name: { type: 'string', minLength: 1 }, args: { type: 'string' }, args_file: { type: 'string' } }, ['run_id', 'attempt', 'name']),
205
774
  outputSchema: OBJECT_OUTPUT,
@@ -214,29 +783,150 @@ const runToolCommand: CommandDefinition = {
214
783
  },
215
784
  }
216
785
 
786
+ // ---- running a wish macro the way every executor runs it (AI Native phase 1, section 2.6): a Deno child that reads only
787
+ // the stage directory, writes only its output/, reaches only the Zone's host, with an empty environment and no token; its
788
+ // bridge calls (`aiws.sql`, `aiws.ai.complete`, `aiws.llm.map`, `aiws.zone.fetch`) come back over stdio and are answered
789
+ // here with the stage's lib/host.js: SQL by the service, AI with this session's own AICC, Zone resources with this session.
790
+
791
+ const BRIDGE_PREFIX = '\x1eaiws '
792
+ const REFUSALS: Record<string, string> = {
793
+ quota_exhausted: 'AI_QUOTA_EXHAUSTED', quota_budget_exceeded: 'AI_QUOTA_BUDGET_EXCEEDED', resource_not_permitted: 'AI_RESOURCE_NOT_PERMITTED',
794
+ attribution_unavailable: 'AI_ATTRIBUTION_UNAVAILABLE', credentials: 'AI_UNAVAILABLE',
795
+ }
796
+
797
+ interface MacroRun { source: string; results: unknown; log: string; code: number }
798
+
799
+ /** One inference with this session's AICC; a refusal carries the run's sub-code. */
800
+ function sessionInfer(ctx: CommandContext) {
801
+ const call = async (method: string, params: unknown) => {
802
+ try {
803
+ return await ctx.clients.call('aicc', method, params as Record<string, unknown>, rpcOptions(ctx))
804
+ } catch (error) {
805
+ throw providerErrorFromRpc(`aicc ${method} failed`, error)
806
+ }
807
+ }
808
+ const client = new AiccLlmClient({ chatCompletionsCreate: (r: unknown) => call('chat.completions.create', r), helperLlmChat: (r: unknown) => call('helper.llm_chat', r) } as never)
809
+ return async (req: { model: string; messages: { role: 'system' | 'user' | 'assistant'; text: string }[]; schema: unknown; max_tokens: number }) => {
810
+ try {
811
+ const r: { message: { content: { type: string; text?: string }[] }; usage?: { output_tokens?: number } } = await client.infer({
812
+ messages: req.messages.map((m) => ({ role: m.role, content: [{ type: 'text' as const, text: m.text }] })), model_alias: req.model, fallbacks: [], temperature: 0,
813
+ max_completion_tokens: req.max_tokens, force_json: req.schema !== null, ...(req.schema !== null ? { json_schema: req.schema as never } : {}),
814
+ disable_capabilities: [], tool_specs: [], allow_tool_calls: false, signal: ctx.signal,
815
+ })
816
+ return { text: r.message.content.map((c) => (c.type === 'text' ? c.text ?? '' : '')).join(''), tokens: r.usage?.output_tokens }
817
+ } catch (error) {
818
+ if (error instanceof LLMComputeException && error.error.kind === 'provider' && typeof error.error.failure === 'object' && 'refused' in error.error.failure) {
819
+ const e = new Error(error.message) as Error & { code?: string }
820
+ e.code = REFUSALS[error.error.failure.refused.code] ?? 'AI_QUOTA_EXHAUSTED'
821
+ throw e
822
+ }
823
+ throw error
824
+ }
825
+ }
826
+ }
827
+
828
+ async function execMacro(ctx: CommandContext, input: Record<string, unknown>): Promise<MacroRun> {
829
+ const host = getHost()
830
+ // Subprocess cwd resolves directory aliases (e.g. /var -> /private/var on macOS).
831
+ // Use the same canonical path for the macro's read/write permission scopes.
832
+ const dir = await host.realPath(host.path.resolve(ctx.cwd, requiredInputString(input, 'dir')))
833
+ const ids = { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt }
834
+ const source = await host.readTextFile(`${dir}/program/main.js`)
835
+ let stage: { budget?: Record<string, unknown>; manifest?: unknown } = {}
836
+ try { stage = JSON.parse(await host.readTextFile(`${dir}/lib/stage.json`)) } catch { stage = {} }
837
+ const budget = stage.budget ?? {}
838
+ const manifest = stage.manifest && typeof stage.manifest === 'object' ? stage.manifest as { resources?: { timeout_secs?: number } } : null
839
+ const { createBridgeHost } = await import(new URL(`file://${dir}/lib/host.js`).href) as { createBridgeHost: (o: Record<string, unknown>) => { handle(op: string, req: unknown): Promise<unknown> } }
840
+ const origin = gatewayOrigin(ctx.connection.endpoint)
841
+ const zoneHost = new URL(origin).hostname
842
+ const bridge = createBridgeHost({
843
+ tool: async (name: string, args: unknown) => {
844
+ try {
845
+ return await aiws(ctx, 'proc.tool', { ...ids, name, args })
846
+ } catch (error) {
847
+ return { status: 'error', text: error instanceof Error ? error.message : String(error) }
848
+ }
849
+ },
850
+ infer: sessionInfer(ctx),
851
+ zoneFetch: async (url: string, init: { method: string; headers: Record<string, string>; body: string | null }) => {
852
+ const res = await fetch(url, { method: init.method, headers: { ...init.headers, Authorization: `Bearer ${await sessionToken(ctx)}` }, body: init.body ?? undefined, signal: ctx.signal })
853
+ const bytes = new Uint8Array(await res.arrayBuffer())
854
+ const headers: Record<string, string> = {}
855
+ res.headers.forEach((v, k) => { headers[k] = v })
856
+ try { return { status: res.status, headers, text: new TextDecoder('utf-8', { fatal: true }).decode(bytes) } } catch { return { status: res.status, headers, base64: btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join('')) } }
857
+ },
858
+ zoneHosts: [zoneHost], zoneOrigin: origin, budget, manifest,
859
+ })
860
+ await host.remove(`${dir}/output/.aiws/results.json`).catch(() => undefined)
861
+ await host.mkdir(`${dir}/output`, { recursive: true })
862
+ // under Deno the tool's own runtime runs the macro; the Node distribution uses the Deno on PATH
863
+ const child = host.spawn(host.kind === 'deno' ? host.runtimeExecutable : 'deno', [
864
+ 'run', '--no-prompt', '--quiet', '--no-remote', `--allow-read=${dir}`, `--allow-write=${dir}/output`, `--allow-net=${zoneHost}`, 'lib/run.js', '--bridge',
865
+ ], { cwd: dir, env: { NO_COLOR: '1', DENO_NO_UPDATE_CHECK: '1', DENO_DIR: `${dir}/.deno` } })
866
+ const cap = Number(budget.program_timeout_secs) || 120
867
+ const limit = Math.min(cap, Number(manifest?.resources?.timeout_secs) || cap)
868
+ let timedOut = false
869
+ const timer = setTimeout(() => { timedOut = true; child.kill() }, limit * 1000)
870
+ const out: string[] = []
871
+ try {
872
+ for await (const line of child.lines()) {
873
+ if (!line.startsWith(BRIDGE_PREFIX)) { out.push(line); continue }
874
+ const msg = JSON.parse(line.slice(BRIDGE_PREFIX.length)) as { id: number; op: string; req: unknown }
875
+ await child.writeLine(JSON.stringify({ id: msg.id, body: await bridge.handle(msg.op, msg.req) }))
876
+ }
877
+ } finally {
878
+ clearTimeout(timer)
879
+ await child.closeInput()
880
+ }
881
+ const code = await child.status
882
+ const log = [...out, await child.stderr, ...(timedOut ? [`The macro timed out (${limit} s)`] : [])].filter(Boolean).join('\n')
883
+ let results: unknown = null
884
+ try { results = JSON.parse(await host.readTextFile(`${dir}/output/.aiws/results.json`)) } catch { results = null }
885
+ if (timedOut) results = { error: `The macro timed out (${limit} s)` }
886
+ return { source, results, log, code }
887
+ }
888
+
889
+ const RUN_EXEC_OPTIONS: OptionDefinition[] = [
890
+ WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION,
891
+ { name: 'dir', property: 'dir', description: 'The stage directory written by run-files (program/main.js, lib/, output/), under the current directory', type: 'string', required: true },
892
+ ]
893
+ const RUN_EXEC_INPUT = workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, dir: { type: 'string', minLength: 1 } }, ['run_id', 'attempt', 'dir'])
894
+
895
+ const runExecCommand: CommandDefinition = {
896
+ verb: 'run-exec',
897
+ summary: 'Run program/main.js of a stage directory as every executor runs a wish macro: reads only the directory, writes only output/, reaches only the Zone, its AI calls with your session; prints its outcome',
898
+ description: 'The macro gets no token and no environment. Use it to debug a macro; `run-program` runs it the same way and hands it in. API: the wish macro guide (src/frame/aiworkspace/aiws/README.md in buckyos).',
899
+ options: RUN_EXEC_OPTIONS,
900
+ inputSchema: RUN_EXEC_INPUT,
901
+ outputSchema: OBJECT_OUTPUT,
902
+ resultSchemaVersion: 1,
903
+ access: { mode: 'fixed', level: 'write' },
904
+ asyncMode: 'sync',
905
+ requiresSession: true,
906
+ examples: ['buckyos aiws run-exec --workspace ws_abc --run run_xyz --attempt 1 --dir work'],
907
+ handler: async (ctx, input) => {
908
+ const run = await execMacro(ctx, input)
909
+ const r = (run.results ?? {}) as Record<string, unknown>
910
+ return { exit_code: run.code, error: r.error ?? null, error_code: r.error_code ?? null, ai: r.ai ?? null, declare: r.declare ?? null, log: run.log }
911
+ },
912
+ }
913
+
217
914
  const runProgramCommand: CommandDefinition = {
218
915
  verb: 'run-program',
219
- summary: 'Hand in a program run: the program source, what lib/run.js wrote to output/.aiws/results.json, the files under output/ and the log; the service validates it like its own run_program',
220
- options: [
221
- WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION,
222
- { name: 'dir', property: 'dir', description: 'The stage directory written by run-files (program/main.js, output/)', type: 'string', required: true },
223
- { name: 'log-file', property: 'log_file', description: 'Path of the program log to attach (stdout/stderr of deno run)', type: 'string' },
224
- ],
225
- inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, dir: { type: 'string', minLength: 1 }, log_file: { type: 'string' } }, ['run_id', 'attempt', 'dir']),
916
+ summary: 'Run the macro of a stage directory (as run-exec) and hand the run in: the source, its results, the files under output/ and its log; the service judges it against the contract',
917
+ description: 'While coding, the answer is what the model would read (previews, checks, manifest, problems); running a stored macro, a failure ends the run. Then `run-report --finished`.',
918
+ options: RUN_EXEC_OPTIONS,
919
+ inputSchema: RUN_EXEC_INPUT,
226
920
  outputSchema: OBJECT_OUTPUT,
227
921
  resultSchemaVersion: 1,
228
922
  access: { mode: 'fixed', level: 'write' },
229
923
  asyncMode: 'sync',
230
924
  requiresSession: true,
231
- examples: ['buckyos aiws run-program --workspace ws_abc --run run_xyz --attempt 1 --dir work --log-file work/run.log'],
925
+ examples: ['buckyos aiws run-program --workspace ws_abc --run run_xyz --attempt 1 --dir work'],
232
926
  handler: async (ctx, input) => {
233
- const dir = requiredInputString(input, 'dir')
234
927
  const host = getHost()
235
- const source = await host.readTextFile(`${dir}/program/main.js`)
236
- let results: unknown = null
237
- try { results = JSON.parse(await host.readTextFile(`${dir}/output/.aiws/results.json`)) } catch { results = null }
238
- const logFile = inputString(input, 'log_file')
239
- const log = logFile ? await host.readTextFile(logFile).catch(() => '') : ''
928
+ const dir = host.path.resolve(ctx.cwd, requiredInputString(input, 'dir'))
929
+ const run = await execMacro(ctx, input)
240
930
  const files: Record<string, unknown> = {}
241
931
  const walk = async (rel: string) => {
242
932
  for (const entry of await host.readDir(`${dir}/output${rel ? `/${rel}` : ''}`)) {
@@ -252,26 +942,43 @@ const runProgramCommand: CommandDefinition = {
252
942
  }
253
943
  }
254
944
  await walk('')
255
- return aiws(ctx, 'proc.program', { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt, source, results, log, files })
945
+ return aiws(ctx, 'proc.program', { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt, source: run.source, results: run.results, log: run.log, files })
256
946
  },
257
947
  }
258
948
 
949
+ const runStartCommand: CommandDefinition = {
950
+ verb: 'run-start',
951
+ summary: 'Start a wish run that you execute yourself (an analysis you work out in a conversation, coding, running): answers the run and its claim token; your AI resources pay',
952
+ description: 'Then `run-claim` with that token and work it like any run. An analysis is handed in with `run-tool --name submit_analysis` then `run-report --finished`, or `run-report --analysis-file`. Needs update on the wish.',
953
+ options: [WORKSPACE_OPTION, { name: 'wish', property: 'wish_id', description: 'The wish (its entity id)', type: 'string', required: true },
954
+ { name: 'stage', property: 'stage', description: 'analyze | code | run (default analyze)', type: 'string' }],
955
+ inputSchema: workspaceInput({ wish_id: { type: 'string', minLength: 1 }, stage: { type: 'string', enum: ['analyze', 'code', 'run'] } }, ['wish_id']),
956
+ outputSchema: OBJECT_OUTPUT,
957
+ resultSchemaVersion: 1,
958
+ access: { mode: 'fixed', level: 'write' },
959
+ asyncMode: 'sync',
960
+ requiresSession: true,
961
+ examples: ['buckyos aiws run-start --workspace ws_abc --wish wish_q3 --stage analyze'],
962
+ handler: (ctx, input) => aiws(ctx, 'proc.start', {
963
+ workspace_id: requiredInputString(input, 'workspace_id'), program: 'wish.xllm@1', idempotency_key: ctx.idempotencyKey ?? `cli-${ctx.traceId}`,
964
+ params: { wish_id: requiredInputString(input, 'wish_id'), stage: inputString(input, 'stage') || 'analyze', execution: { mode: 'local' } },
965
+ }),
966
+ }
967
+
259
968
  const runReportCommand: CommandDefinition = {
260
969
  verb: 'run-report',
261
- summary: 'End a claimed run: --finished after the stage tools accepted the work (submit_analysis / finish), or the candidate itself (results / analysis), or a failure',
262
- description: 'The service validates and plans what is reported; the user confirms it in the workspace. A superseded attempt or a cancelled run gets RUN_REVOKED.',
970
+ summary: 'End a claimed run: --finished after the stage is done (submit_analysis or finish accepted, or the stored macro handed in), an analysis made elsewhere, or a failure',
971
+ description: 'The service validates and plans what the stage collected; the user confirms it in the workspace. Results always come from the macro (run-program). A superseded attempt or a cancelled run gets RUN_REVOKED.',
263
972
  options: [
264
973
  WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION,
265
- { name: 'finished', property: 'finished', description: 'The stage is done: what the tools collected becomes the candidate', type: 'boolean' },
266
- { name: 'results', property: 'results', description: 'Results JSON array (execute runs): [{ name, type, title?, content, config? }]', type: 'string' },
267
- { name: 'results-file', property: 'results_file', description: 'Path of a JSON file holding the results array', type: 'string' },
268
- { name: 'analysis', property: 'analysis', description: 'Analysis JSON (analyze runs, wish.analysis.v2)', type: 'string' },
974
+ { name: 'finished', property: 'finished', description: 'The stage is done: what it collected becomes the candidate', type: 'boolean' },
975
+ { name: 'analysis', property: 'analysis', description: 'Analysis JSON (analyze runs, wish.analysis.v3)', type: 'string' },
269
976
  { name: 'analysis-file', property: 'analysis_file', description: 'Path of a JSON file holding the analysis', type: 'string' },
270
977
  { name: 'summary', property: 'summary', description: 'One paragraph on what was done', type: 'string' },
271
978
  { name: 'warning', property: 'warnings', description: 'A warning for the user (repeatable)', type: 'string' },
272
979
  { name: 'error', property: 'error', description: 'Report a failure instead: its reason', type: 'string' },
273
980
  ],
274
- inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, finished: { type: 'boolean' }, results: { type: 'string' }, results_file: { type: 'string' }, analysis: { type: 'string' }, analysis_file: { type: 'string' }, summary: { type: 'string' }, warnings: { type: 'string' }, error: { type: 'string' } }, ['run_id', 'attempt']),
981
+ inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, finished: { type: 'boolean' }, analysis: { type: 'string' }, analysis_file: { type: 'string' }, summary: { type: 'string' }, warnings: { type: 'string' }, error: { type: 'string' } }, ['run_id', 'attempt']),
275
982
  outputSchema: OBJECT_OUTPUT,
276
983
  resultSchemaVersion: 1,
277
984
  access: { mode: 'fixed', level: 'write' },
@@ -279,7 +986,6 @@ const runReportCommand: CommandDefinition = {
279
986
  requiresSession: true,
280
987
  examples: [
281
988
  'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --finished',
282
- 'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --results-file out/results.json --summary "monthly totals and a commentary"',
283
989
  'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --analysis-file out/analysis.json',
284
990
  'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --error "the input table is empty"',
285
991
  ],
@@ -290,11 +996,8 @@ const runReportCommand: CommandDefinition = {
290
996
  params.error = { code: 'EXECUTOR_FAILED', detail: error }
291
997
  } else if (input.finished === true) {
292
998
  params.finished = true
293
- } else if (inputString(input, 'analysis') || inputString(input, 'analysis_file')) {
294
- params.analysis = await jsonInput(input, 'analysis', 'analysis_file', 'an analysis')
295
999
  } else {
296
- params.results = await jsonInput(input, 'results', 'results_file', 'results')
297
- params.read_set = []
1000
+ params.analysis = await jsonInput(input, 'analysis', 'analysis_file', 'an analysis')
298
1001
  }
299
1002
  const summary = inputString(input, 'summary')
300
1003
  if (summary) params.summary = summary
@@ -1005,7 +1708,7 @@ const templateCommand: CommandDefinition = {
1005
1708
  export function createAiwsModule(): CommandModule {
1006
1709
  return {
1007
1710
  name: 'aiws',
1008
- summary: 'AI Workspace: read a workspace, Block-controls (catalogue, import, export), extension controls (build, pull, export, library, import, upgrade), Workspace templates (list, create, export), and execute wish runs as their executor (claim, heartbeat, report)',
1009
- commands: [infoCommand, readCommand, queryCommand, controlsCommand, importCommand, exportCommand, buildCommand, pullCommand, extExportCommand, libraryCommand, extImportCommand, extUpgradeCommand, templateCommand, runGetCommand, runClaimCommand, runHeartbeatCommand, runFilesCommand, runToolCommand, runProgramCommand, runReportCommand],
1711
+ summary: 'AI Workspace: find and read a workspace by path (ls, find, grep, stat, cat, resolve, read), its permissions (acl, acl-edit), query its tables in SQL (sql), write tables, rich text and common properties (table, text, mv, rename, set-prop), your to-do list and calendar (todo, cal), Block-controls (catalogue, import, export), extension controls (build, pull, export, library, import, upgrade), Workspace templates (list, create, export), and execute wish runs as their executor (claim, heartbeat, report)',
1712
+ commands: [infoCommand, lsCommand, findCommand, grepCommand, statCommand, aclCommand, aclEditCommand, catCommand, resolveCommand, readCommand, sqlCommand, tableCommand, textCommand, mvCommand, renameCommand, setPropCommand, todoCommand, calCommand, placeCommand, controlsCommand, importCommand, exportCommand, buildCommand, pullCommand, extExportCommand, libraryCommand, extImportCommand, extUpgradeCommand, templateCommand, runGetCommand, runClaimCommand, runHeartbeatCommand, runFilesCommand, runToolCommand, runExecCommand, runProgramCommand, runReportCommand, runStartCommand],
1010
1713
  }
1011
1714
  }