buckyos 0.7.180 → 0.7.184
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.
- package/LICENSE +202 -21
- package/NOTICE +35 -0
- package/README.md +4 -0
- package/cli/deno.json +3 -2
- package/cli/dist/cli.mjs +1569 -216
- package/cli/dist/cli.mjs.map +1 -1
- package/cli/modules/aiws.ts +798 -58
- package/cli/modules/aiws_place.ts +385 -0
- package/cli/modules/aiws_schedule.ts +256 -0
- package/cli/runtime/host.ts +18 -0
- package/cli/runtime/host_deno.ts +34 -0
- package/cli/runtime/host_node.ts +32 -1
- package/cli/runtime/node_entry.ts +1 -0
- package/cli/system_bootstrap.ts +1 -0
- package/cli/system_launcher.ts +1 -0
- package/cli/version.ts +1 -1
- package/dist/aicc_client.d.ts +1 -1
- package/dist/aicc_client.d.ts.map +1 -1
- package/dist/aiworkspace_client.d.ts +253 -2
- package/dist/aiworkspace_client.d.ts.map +1 -1
- package/dist/aiws_bind-3b874f77.mjs +2235 -0
- package/dist/aiws_bind-3b874f77.mjs.map +1 -0
- package/dist/aiws_bind-82bace11.js +2 -0
- package/dist/aiws_bind-82bace11.js.map +1 -0
- package/dist/aiws_bind.d.ts +233 -0
- package/dist/aiws_bind.d.ts.map +1 -0
- package/dist/aiws_ext.cjs +1 -1
- package/dist/aiws_ext.cjs.map +1 -1
- package/dist/aiws_ext.d.ts +9 -5
- package/dist/aiws_ext.d.ts.map +1 -1
- package/dist/aiws_ext.mjs +146 -11
- package/dist/aiws_ext.mjs.map +1 -1
- package/dist/aiws_rrule.d.ts +121 -0
- package/dist/aiws_rrule.d.ts.map +1 -0
- package/dist/aiws_schedule.d.ts +324 -0
- package/dist/aiws_schedule.d.ts.map +1 -0
- package/dist/aiws_write-1c748f36.js +13 -0
- package/dist/aiws_write-1c748f36.js.map +1 -0
- package/dist/{executor_client-bfc8a1e1.mjs → aiws_write-ed4f0ec4.mjs} +726 -285
- package/dist/aiws_write-ed4f0ec4.mjs.map +1 -0
- package/dist/aiws_write.d.ts +182 -0
- package/dist/aiws_write.d.ts.map +1 -0
- package/dist/browser.cjs +1 -1
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.ts +4 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.mjs +112 -21
- package/dist/browser.mjs.map +1 -1
- package/dist/content_objid-8a793481.js +2 -0
- package/dist/{content_objid-1aff74b6.js.map → content_objid-8a793481.js.map} +1 -1
- package/dist/{content_objid-9232bcaf.mjs → content_objid-c25fec12.mjs} +2 -2
- package/dist/{content_objid-9232bcaf.mjs.map → content_objid-c25fec12.mjs.map} +1 -1
- package/dist/{did_object_client-7fa36f90.mjs → did_object_client-cb2f9aba.mjs} +2 -2
- package/dist/{did_object_client-7fa36f90.mjs.map → did_object_client-cb2f9aba.mjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +113 -22
- package/dist/index.mjs.map +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.ts +5 -0
- package/dist/node.d.ts.map +1 -1
- package/dist/node.mjs +99 -6
- package/dist/node.mjs.map +1 -1
- package/dist/{object_url-f72c1704.mjs → object_url-376c5222.mjs} +4 -4
- package/dist/{object_url-f72c1704.mjs.map → object_url-376c5222.mjs.map} +1 -1
- package/dist/xllm.mjs +2 -2
- package/package.json +5 -4
- package/dist/content_objid-1aff74b6.js +0 -2
- package/dist/executor_client-7ce0ddc7.js +0 -13
- package/dist/executor_client-7ce0ddc7.js.map +0 -1
- package/dist/executor_client-bfc8a1e1.mjs.map +0 -1
package/cli/modules/aiws.ts
CHANGED
|
@@ -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
|
|
23
|
-
//
|
|
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,605 @@ 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
|
|
62
|
-
positionals: [{ name: 'entity_id', description:
|
|
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:
|
|
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'),
|
|
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
|
|
78
|
-
verb: '
|
|
79
|
-
summary: '
|
|
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: '
|
|
83
|
-
{ name: '
|
|
84
|
-
{ name: '
|
|
85
|
-
{ name: 'limit', property: 'limit', description: '
|
|
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({
|
|
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:
|
|
197
|
+
access: READ_ACCESS,
|
|
92
198
|
asyncMode: 'sync',
|
|
93
199
|
requiresSession: true,
|
|
94
|
-
examples: [
|
|
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
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
+
}
|
|
103
219
|
},
|
|
104
220
|
}
|
|
105
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
|
+
}
|
|
290
|
+
},
|
|
291
|
+
}
|
|
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; --default is what new records get when they do not give the field (a display value, like --values: a select takes its label; not on object_ref).',
|
|
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
|
+
{ name: 'default', property: 'default', description: 'field-add: the value new records get when they do not give the field (display form)', type: 'string' },
|
|
478
|
+
],
|
|
479
|
+
inputSchema: workspaceInput({
|
|
480
|
+
action: { type: 'string', enum: ['add', 'set', 'rm', 'field-add', 'option-add'] }, table: { type: 'string', minLength: 1 }, target: { type: 'string' }, label: { type: 'string' },
|
|
481
|
+
values: { type: 'string' }, name: { type: 'string' }, type: { type: 'string' }, options: { type: 'string' }, default: { type: 'string' },
|
|
482
|
+
}, ['action', 'table']),
|
|
483
|
+
outputSchema: OBJECT_OUTPUT,
|
|
484
|
+
resultSchemaVersion: 1,
|
|
485
|
+
access: WRITE_ACCESS,
|
|
486
|
+
asyncMode: 'sync',
|
|
487
|
+
requiresSession: true,
|
|
488
|
+
examples: [
|
|
489
|
+
'buckyos aiws table add /data/销售 --values \'{"客户":"ACME","金额":"1200.50","状态":"进行中"}\' --workspace ws_abc',
|
|
490
|
+
'buckyos aiws table set /data/销售 r123 --values \'{"状态":"已完成"}\' --workspace ws_abc',
|
|
491
|
+
'buckyos aiws table rm /data/销售 r123,r124 --workspace ws_abc',
|
|
492
|
+
'buckyos aiws table field-add /data/销售 --name 负责人 --type text --workspace ws_abc',
|
|
493
|
+
'buckyos aiws table field-add /data/销售 --name 阶段 --type select --options 线索,成交 --default 线索 --workspace ws_abc',
|
|
494
|
+
'buckyos aiws table option-add /data/销售 状态 已取消 --workspace ws_abc',
|
|
495
|
+
],
|
|
496
|
+
handler: (ctx, input) => writing(async () => {
|
|
497
|
+
const ws = requiredInputString(input, 'workspace_id')
|
|
498
|
+
const action = requiredInputString(input, 'action')
|
|
499
|
+
const tablePath = requiredInputString(input, 'table')
|
|
500
|
+
const values = () => {
|
|
501
|
+
const v = jsonArg(requiredInputString(input, 'values'), '--values')
|
|
502
|
+
if (!v || typeof v !== 'object') throw new UsageError('AIWS_USAGE', '--values is a JSON object keyed by field name')
|
|
503
|
+
return v as Record<string, unknown> | Record<string, unknown>[]
|
|
504
|
+
}
|
|
505
|
+
if (action === 'rm') {
|
|
506
|
+
const records = ids(requiredInputString(input, 'target'))
|
|
507
|
+
const reads = await Promise.all(records.map((record_id) => aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(tablePath), selector: { kind: 'table_record', record_id } })))
|
|
508
|
+
const table = String(reads[0].entity_id)
|
|
509
|
+
return { ...await commit(ctx, ws, tableDelete(table, records, reads as never), `delete ${records.length} record(s)`), table, removed: records }
|
|
510
|
+
}
|
|
511
|
+
const table = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(tablePath) }) as unknown as TableRead
|
|
512
|
+
switch (action) {
|
|
513
|
+
case 'add': {
|
|
514
|
+
const rows = values()
|
|
515
|
+
const ops = tableInsert(table, Array.isArray(rows) ? rows : [rows])
|
|
516
|
+
const record_ids = ((ops[0]?.records ?? []) as { record_id: string }[]).map((r) => r.record_id)
|
|
517
|
+
return { ...await commit(ctx, ws, ops, `add ${record_ids.length} record(s)`), table: table.entity_id, record_ids }
|
|
518
|
+
}
|
|
519
|
+
case 'set': {
|
|
520
|
+
const record_id = requiredInputString(input, 'target')
|
|
521
|
+
const v = values()
|
|
522
|
+
if (Array.isArray(v)) throw new UsageError('AIWS_USAGE', 'set takes one --values object')
|
|
523
|
+
const read = await aiws(ctx, 'doc.read', { workspace_id: ws, entity_id: table.entity_id, selector: { kind: 'table_record', record_id } })
|
|
524
|
+
const ops = tableSet(table, record_id, v, read as never)
|
|
525
|
+
if (ops.length === 0) return { ok: true, status: 'unchanged', table: table.entity_id, record_id }
|
|
526
|
+
return { ...await commit(ctx, ws, ops, `update record ${record_id}`), table: table.entity_id, record_id }
|
|
527
|
+
}
|
|
528
|
+
case 'field-add': {
|
|
529
|
+
const options = inputString(input, 'options')
|
|
530
|
+
const labels = options === undefined ? undefined : options.startsWith('[') ? jsonArg(options, '--options') as string[] : ids(options)
|
|
531
|
+
const fallback = inputString(input, 'default')
|
|
532
|
+
const op = fieldAdd(table, { name: requiredInputString(input, 'name'), type: requiredInputString(input, 'type'), ...(labels ? { options: labels } : {}), ...(fallback !== undefined ? { default: fallback } : {}) })
|
|
533
|
+
const field = op.field as { field_id: string; options?: unknown[] }
|
|
534
|
+
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 } : {}) }
|
|
535
|
+
}
|
|
536
|
+
case 'option-add': {
|
|
537
|
+
const op = optionAdd(table, requiredInputString(input, 'target'), requiredInputString(input, 'label'))
|
|
538
|
+
return { ...await commit(ctx, ws, [op], `add option ${requiredInputString(input, 'label')}`), table: table.entity_id, field_id: op.field_id, option: op.option }
|
|
539
|
+
}
|
|
540
|
+
default:
|
|
541
|
+
throw new UsageError('AIWS_USAGE', `table: add, set, rm, field-add or option-add, not ${action}`)
|
|
542
|
+
}
|
|
543
|
+
}),
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const textCommand: CommandDefinition = {
|
|
547
|
+
verb: 'text',
|
|
548
|
+
summary: 'Write a rich text by blocks from Markdown: `append <doc> --file <md>`, `replace <doc> <block_id> --file <md>`, `rm <doc> <block_id>[,…]`',
|
|
549
|
+
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.',
|
|
550
|
+
positionals: [
|
|
551
|
+
{ name: 'action', description: 'append | replace | rm', required: true },
|
|
552
|
+
{ name: 'doc', description: `The rich text: ${PATH_HELP}`, required: true },
|
|
553
|
+
{ name: 'block', description: 'replace: block id; rm: block ids, comma-separated', required: false },
|
|
554
|
+
],
|
|
555
|
+
options: [
|
|
556
|
+
WORKSPACE_OPTION,
|
|
557
|
+
{ name: 'file', property: 'file', description: 'append / replace: a local Markdown file', type: 'string' },
|
|
558
|
+
{ name: 'text', property: 'text', description: 'append / replace: the Markdown itself', type: 'string' },
|
|
559
|
+
],
|
|
560
|
+
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']),
|
|
561
|
+
outputSchema: OBJECT_OUTPUT,
|
|
562
|
+
resultSchemaVersion: 1,
|
|
563
|
+
access: WRITE_ACCESS,
|
|
564
|
+
asyncMode: 'sync',
|
|
565
|
+
requiresSession: true,
|
|
566
|
+
examples: [
|
|
567
|
+
'buckyos aiws text append /docs/周报 --file notes.md --workspace ws_abc',
|
|
568
|
+
'buckyos aiws text replace /docs/周报 b12 --text "## 下周计划" --workspace ws_abc',
|
|
569
|
+
'buckyos aiws text rm /docs/周报 b12,b13 --workspace ws_abc',
|
|
570
|
+
],
|
|
571
|
+
handler: (ctx, input) => writing(async () => {
|
|
572
|
+
const ws = requiredInputString(input, 'workspace_id')
|
|
573
|
+
const action = requiredInputString(input, 'action')
|
|
574
|
+
const target = requiredInputString(input, 'doc')
|
|
575
|
+
if (action === 'append') {
|
|
576
|
+
const markdown = await markdownInput(input)
|
|
577
|
+
const doc = String((await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target), as: 'meta' })).entity_id)
|
|
578
|
+
const ops = textAppend(doc, markdown)
|
|
579
|
+
const blocks = (ops[0].blocks as { attrs: { block_id: string } }[]).map((b) => b.attrs.block_id)
|
|
580
|
+
return { ...await commit(ctx, ws, ops, 'append text'), doc, blocks }
|
|
581
|
+
}
|
|
582
|
+
if (action !== 'replace' && action !== 'rm') throw new UsageError('AIWS_USAGE', `text: append, replace or rm, not ${action}`)
|
|
583
|
+
const markdown = action === 'replace' ? await markdownInput(input) : ''
|
|
584
|
+
const doc = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(target) }) as unknown as RichTextRead
|
|
585
|
+
if (action === 'rm') {
|
|
586
|
+
const blocks = ids(requiredInputString(input, 'block'))
|
|
587
|
+
return { ...await commit(ctx, ws, textDeleteBlocks(doc, blocks), `delete ${blocks.length} block(s)`), doc: doc.entity_id, removed: blocks }
|
|
588
|
+
}
|
|
589
|
+
const block = requiredInputString(input, 'block')
|
|
590
|
+
const ops = textReplaceBlock(doc, block, markdown)
|
|
591
|
+
const added = ops.length > 1 ? ((ops[1] as Record<string, unknown>).blocks as { attrs: { block_id: string } }[]).map((b) => b.attrs.block_id) : []
|
|
592
|
+
return { ...await commit(ctx, ws, ops, `replace block ${block}`), doc: doc.entity_id, blocks: [block, ...added] }
|
|
593
|
+
}),
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const mvCommand: CommandDefinition = {
|
|
597
|
+
verb: 'mv',
|
|
598
|
+
summary: 'Move an entity under another parent, after its last child (a following name moves aside if taken there)',
|
|
599
|
+
positionals: [{ name: 'path', description: PATH_HELP, required: true }, { name: 'parent', description: `The new parent: ${PATH_HELP}`, required: true }],
|
|
600
|
+
options: [WORKSPACE_OPTION],
|
|
601
|
+
inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, parent: { type: 'string', minLength: 1 } }, ['path', 'parent']),
|
|
602
|
+
outputSchema: OBJECT_OUTPUT,
|
|
603
|
+
resultSchemaVersion: 1,
|
|
604
|
+
access: WRITE_ACCESS,
|
|
605
|
+
asyncMode: 'sync',
|
|
606
|
+
requiresSession: true,
|
|
607
|
+
examples: ['buckyos aiws mv /data/草稿 /archive --workspace ws_abc'],
|
|
608
|
+
handler: (ctx, input) => writing(async () => {
|
|
609
|
+
const ws = requiredInputString(input, 'workspace_id')
|
|
610
|
+
const entity = await envelopeOf(ctx, ws, requiredInputString(input, 'path'))
|
|
611
|
+
const parent = String((await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(requiredInputString(input, 'parent')), as: 'meta' })).entity_id)
|
|
612
|
+
// the new place: after the last child the caller sees there
|
|
613
|
+
let last: string | undefined
|
|
614
|
+
let cursor: string | undefined
|
|
615
|
+
for (let page = 0; page < 100; page++) {
|
|
616
|
+
const listed = await aiws(ctx, 'doc.list', { workspace_id: ws, at: parent, limit: 1000, ...(cursor ? { cursor } : {}) })
|
|
617
|
+
const items = (Array.isArray(listed.items) ? listed.items : []) as { entity_id: string }[]
|
|
618
|
+
last = items.map((i) => i.entity_id).filter((id) => id !== entity.entity_id).at(-1) ?? last
|
|
619
|
+
if (typeof listed.next_cursor !== 'string' || items.length === 0) break
|
|
620
|
+
cursor = listed.next_cursor
|
|
621
|
+
}
|
|
622
|
+
const after = last ? (await envelopeOf(ctx, ws, last)).order_key : undefined
|
|
623
|
+
const op = move(entity as unknown as EntityRead, parent, typeof after === 'string' ? after : null)
|
|
624
|
+
return { ...await commit(ctx, ws, [op], `move ${entity.entity_id}`), entity_id: entity.entity_id, parent }
|
|
625
|
+
}),
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
const renameCommand: CommandDefinition = {
|
|
629
|
+
verb: 'rename',
|
|
630
|
+
summary: 'Give an entity a name of its own (its path segment), or --auto to let it follow its title again',
|
|
631
|
+
positionals: [{ name: 'path', description: PATH_HELP, required: true }, { name: 'name', description: 'The new name (1–128 characters, no /, not starting with ~)', required: false }],
|
|
632
|
+
options: [WORKSPACE_OPTION, { name: 'auto', property: 'auto', description: 'Name it after its title again (or a counter)', type: 'boolean' }],
|
|
633
|
+
inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, name: { type: 'string' }, auto: { type: 'boolean' } }, ['path']),
|
|
634
|
+
outputSchema: OBJECT_OUTPUT,
|
|
635
|
+
resultSchemaVersion: 1,
|
|
636
|
+
access: WRITE_ACCESS,
|
|
637
|
+
asyncMode: 'sync',
|
|
638
|
+
requiresSession: true,
|
|
639
|
+
examples: ['buckyos aiws rename /data/销售 销售-2026 --workspace ws_abc', 'buckyos aiws rename ~sales --auto --workspace ws_abc'],
|
|
640
|
+
handler: (ctx, input) => writing(async () => {
|
|
641
|
+
const ws = requiredInputString(input, 'workspace_id')
|
|
642
|
+
const name = inputString(input, 'name')
|
|
643
|
+
if ((name === undefined) === (input.auto !== true)) throw new UsageError('AIWS_USAGE', 'rename: pass a new name or --auto')
|
|
644
|
+
const entity = await envelopeOf(ctx, ws, requiredInputString(input, 'path'))
|
|
645
|
+
return { ...await commit(ctx, ws, [rename(entity as unknown as EntityRead, name ?? null)], `rename ${entity.entity_id}`), entity_id: entity.entity_id, ...(name ? { name } : {}) }
|
|
646
|
+
}),
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
const setPropCommand: CommandDefinition = {
|
|
650
|
+
verb: 'set-prop',
|
|
651
|
+
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',
|
|
652
|
+
positionals: [
|
|
653
|
+
{ name: 'path', description: `The Block or container: ${PATH_HELP}`, required: true },
|
|
654
|
+
{ name: 'key', description: 'config | bindings | on', required: true },
|
|
655
|
+
{ name: 'props', description: 'JSON object { <name>: value | null }', required: true },
|
|
656
|
+
],
|
|
657
|
+
options: [WORKSPACE_OPTION],
|
|
658
|
+
inputSchema: workspaceInput({ path: { type: 'string', minLength: 1 }, key: { type: 'string', enum: ['config', 'bindings', 'on'] }, props: { type: 'string', minLength: 1 } }, ['path', 'key', 'props']),
|
|
659
|
+
outputSchema: OBJECT_OUTPUT,
|
|
660
|
+
resultSchemaVersion: 1,
|
|
661
|
+
access: WRITE_ACCESS,
|
|
662
|
+
asyncMode: 'sync',
|
|
663
|
+
requiresSession: true,
|
|
664
|
+
examples: ['buckyos aiws set-prop /surfaces/看板/kpi config \'{"label":"本月销售"}\' --workspace ws_abc'],
|
|
665
|
+
handler: (ctx, input) => writing(async () => {
|
|
666
|
+
const ws = requiredInputString(input, 'workspace_id')
|
|
667
|
+
const key = requiredInputString(input, 'key')
|
|
668
|
+
if (key !== 'config' && key !== 'bindings' && key !== 'on') throw new UsageError('AIWS_USAGE', 'set-prop: the key is config, bindings or on')
|
|
669
|
+
const props = jsonArg(requiredInputString(input, 'props'), 'props')
|
|
670
|
+
if (!props || typeof props !== 'object' || Array.isArray(props)) throw new UsageError('AIWS_USAGE', 'props is a JSON object { <name>: value | null }')
|
|
671
|
+
const entity = await aiws(ctx, 'doc.read', { workspace_id: ws, ...aiwsTarget(requiredInputString(input, 'path')) })
|
|
672
|
+
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 }
|
|
673
|
+
}),
|
|
674
|
+
}
|
|
675
|
+
|
|
106
676
|
const infoCommand: CommandDefinition = {
|
|
107
677
|
verb: 'info',
|
|
108
678
|
summary: 'Workspace info: versions, capabilities of the caller, usage, hosted execution configuration',
|
|
@@ -167,8 +737,8 @@ const runHeartbeatCommand: CommandDefinition = {
|
|
|
167
737
|
|
|
168
738
|
const runFilesCommand: CommandDefinition = {
|
|
169
739
|
verb: 'run-files',
|
|
170
|
-
summary: 'Write the stage of a claimed run into a directory: the snapshot (context/), request.json, the Renderer catalog
|
|
171
|
-
description: 'Run the
|
|
740
|
+
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',
|
|
741
|
+
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
742
|
options: [WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION, { name: 'dir', property: 'dir', description: 'Directory to write into (created)', type: 'string', required: true }],
|
|
173
743
|
inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, dir: { type: 'string', minLength: 1 } }, ['run_id', 'attempt', 'dir']),
|
|
174
744
|
outputSchema: { type: 'object', properties: { dir: { type: 'string' }, files: { type: 'array', items: { type: 'string' } } }, required: ['dir', 'files'], additionalProperties: true },
|
|
@@ -193,13 +763,15 @@ const runFilesCommand: CommandDefinition = {
|
|
|
193
763
|
}
|
|
194
764
|
await host.mkdir(`${dir}/output`, { recursive: true })
|
|
195
765
|
await host.mkdir(`${dir}/program`, { recursive: true })
|
|
766
|
+
await host.mkdir(`${dir}/lib`, { recursive: true })
|
|
767
|
+
await host.writeTextFile(`${dir}/lib/stage.json`, JSON.stringify(result.stage ?? {}))
|
|
196
768
|
return { dir, files: written }
|
|
197
769
|
},
|
|
198
770
|
}
|
|
199
771
|
|
|
200
772
|
const runToolCommand: CommandDefinition = {
|
|
201
773
|
verb: 'run-tool',
|
|
202
|
-
summary: 'Call one stage tool of a claimed run (ws_profile, ws_read, ws_query, submit_analysis,
|
|
774
|
+
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
775
|
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
776
|
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
777
|
outputSchema: OBJECT_OUTPUT,
|
|
@@ -214,29 +786,184 @@ const runToolCommand: CommandDefinition = {
|
|
|
214
786
|
},
|
|
215
787
|
}
|
|
216
788
|
|
|
789
|
+
// ---- running a wish macro the way every executor runs it (AI Native phase 1, section 2.6): a Deno child that reads only
|
|
790
|
+
// the stage directory, writes only its output/, reaches only the Zone's host, with an empty environment and no token; its
|
|
791
|
+
// bridge calls (`aiws.sql`, `aiws.ai.complete`, `aiws.llm.map`, `aiws.zone.fetch`) come back over stdio and are answered
|
|
792
|
+
// here with the stage's lib/host.js: SQL by the service, AI with this session's own AICC, Zone resources with this session.
|
|
793
|
+
|
|
794
|
+
const BRIDGE_PREFIX = '\x1eaiws '
|
|
795
|
+
const REFUSALS: Record<string, string> = {
|
|
796
|
+
quota_exhausted: 'AI_QUOTA_EXHAUSTED', quota_budget_exceeded: 'AI_QUOTA_BUDGET_EXCEEDED', resource_not_permitted: 'AI_RESOURCE_NOT_PERMITTED',
|
|
797
|
+
attribution_unavailable: 'AI_ATTRIBUTION_UNAVAILABLE', credentials: 'AI_UNAVAILABLE',
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
interface MacroRun { source: string; results: unknown; log: string; code: number }
|
|
801
|
+
|
|
802
|
+
/** An AICC refusal as the run's sub-code (AI_QUOTA_EXHAUSTED…), anything else as it came. */
|
|
803
|
+
function refusalOf(error: unknown): unknown {
|
|
804
|
+
if (error instanceof LLMComputeException && error.error.kind === 'provider' && typeof error.error.failure === 'object' && 'refused' in error.error.failure) {
|
|
805
|
+
const e = new Error(error.message) as Error & { code?: string }
|
|
806
|
+
e.code = REFUSALS[error.error.failure.refused.code] ?? 'AI_QUOTA_EXHAUSTED'
|
|
807
|
+
return e
|
|
808
|
+
}
|
|
809
|
+
return error
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/** One AICC call of a macro's generated picture or clip, with this session; a refusal carries the run's sub-code. */
|
|
813
|
+
function sessionAicc(ctx: CommandContext) {
|
|
814
|
+
return async (method: string, params: Record<string, unknown>) => {
|
|
815
|
+
try {
|
|
816
|
+
return await ctx.clients.call('aicc', method, params, rpcOptions(ctx))
|
|
817
|
+
} catch (error) {
|
|
818
|
+
throw refusalOf(providerErrorFromRpc(`aicc ${method} failed`, error))
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** One inference with this session's AICC; a refusal carries the run's sub-code. */
|
|
824
|
+
function sessionInfer(ctx: CommandContext) {
|
|
825
|
+
const call = async (method: string, params: unknown) => {
|
|
826
|
+
try {
|
|
827
|
+
return await ctx.clients.call('aicc', method, params as Record<string, unknown>, rpcOptions(ctx))
|
|
828
|
+
} catch (error) {
|
|
829
|
+
throw providerErrorFromRpc(`aicc ${method} failed`, error)
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
const client = new AiccLlmClient({ chatCompletionsCreate: (r: unknown) => call('chat.completions.create', r), helperLlmChat: (r: unknown) => call('helper.llm_chat', r) } as never)
|
|
833
|
+
return async (req: { model: string; messages: { role: 'system' | 'user' | 'assistant'; text: string }[]; schema: unknown; max_tokens: number }) => {
|
|
834
|
+
try {
|
|
835
|
+
const r: { message: { content: { type: string; text?: string }[] }; usage?: { output_tokens?: number } } = await client.infer({
|
|
836
|
+
messages: req.messages.map((m) => ({ role: m.role, content: [{ type: 'text' as const, text: m.text }] })), model_alias: req.model, fallbacks: [], temperature: 0,
|
|
837
|
+
max_completion_tokens: req.max_tokens, force_json: req.schema !== null, ...(req.schema !== null ? { json_schema: req.schema as never } : {}),
|
|
838
|
+
disable_capabilities: [], tool_specs: [], allow_tool_calls: false, signal: ctx.signal,
|
|
839
|
+
})
|
|
840
|
+
return { text: r.message.content.map((c) => (c.type === 'text' ? c.text ?? '' : '')).join(''), tokens: r.usage?.output_tokens }
|
|
841
|
+
} catch (error) {
|
|
842
|
+
throw refusalOf(error)
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
async function execMacro(ctx: CommandContext, input: Record<string, unknown>): Promise<MacroRun> {
|
|
848
|
+
const host = getHost()
|
|
849
|
+
// Subprocess cwd resolves directory aliases (e.g. /var -> /private/var on macOS).
|
|
850
|
+
// Use the same canonical path for the macro's read/write permission scopes.
|
|
851
|
+
const dir = await host.realPath(host.path.resolve(ctx.cwd, requiredInputString(input, 'dir')))
|
|
852
|
+
const ids = { workspace_id: requiredInputString(input, 'workspace_id'), run_id: requiredInputString(input, 'run_id'), attempt: input.attempt }
|
|
853
|
+
const source = await host.readTextFile(`${dir}/program/main.js`)
|
|
854
|
+
let stage: { budget?: Record<string, unknown>; manifest?: unknown } = {}
|
|
855
|
+
try { stage = JSON.parse(await host.readTextFile(`${dir}/lib/stage.json`)) } catch { stage = {} }
|
|
856
|
+
const budget = stage.budget ?? {}
|
|
857
|
+
const manifest = stage.manifest && typeof stage.manifest === 'object' ? stage.manifest as { resources?: { timeout_secs?: number } } : null
|
|
858
|
+
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> } }
|
|
859
|
+
const origin = gatewayOrigin(ctx.connection.endpoint)
|
|
860
|
+
const zoneHost = new URL(origin).hostname
|
|
861
|
+
const bridge = createBridgeHost({
|
|
862
|
+
tool: async (name: string, args: unknown) => {
|
|
863
|
+
try {
|
|
864
|
+
return await aiws(ctx, 'proc.tool', { ...ids, name, args })
|
|
865
|
+
} catch (error) {
|
|
866
|
+
return { status: 'error', text: error instanceof Error ? error.message : String(error) }
|
|
867
|
+
}
|
|
868
|
+
},
|
|
869
|
+
infer: sessionInfer(ctx),
|
|
870
|
+
zoneFetch: async (url: string, init: { method: string; headers: Record<string, string>; body: string | null }) => {
|
|
871
|
+
const res = await fetch(url, { method: init.method, headers: { ...init.headers, Authorization: `Bearer ${await sessionToken(ctx)}` }, body: init.body ?? undefined, signal: ctx.signal })
|
|
872
|
+
const bytes = new Uint8Array(await res.arrayBuffer())
|
|
873
|
+
const headers: Record<string, string> = {}
|
|
874
|
+
res.headers.forEach((v, k) => { headers[k] = v })
|
|
875
|
+
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('')) } }
|
|
876
|
+
},
|
|
877
|
+
aicc: sessionAicc(ctx),
|
|
878
|
+
task: (id: string) => ctx.clients.call('task-manager', 'get_task', { task_id: id }, rpcOptions(ctx)),
|
|
879
|
+
importAsset: (objId: string) => aiws(ctx, 'asset.import_object', { workspace_id: ids.workspace_id, obj_id: objId }),
|
|
880
|
+
zoneHosts: [zoneHost], zoneOrigin: origin, budget, manifest,
|
|
881
|
+
})
|
|
882
|
+
await host.remove(`${dir}/output/.aiws/results.json`).catch(() => undefined)
|
|
883
|
+
await host.mkdir(`${dir}/output`, { recursive: true })
|
|
884
|
+
// under Deno the tool's own runtime runs the macro; the Node distribution uses the Deno on PATH
|
|
885
|
+
const child = host.spawn(host.kind === 'deno' ? host.runtimeExecutable : 'deno', [
|
|
886
|
+
'run', '--no-prompt', '--quiet', '--no-remote', `--allow-read=${dir}`, `--allow-write=${dir}/output`, `--allow-net=${zoneHost}`, 'lib/run.js', '--bridge',
|
|
887
|
+
], { cwd: dir, env: { NO_COLOR: '1', DENO_NO_UPDATE_CHECK: '1', DENO_DIR: `${dir}/.deno` } })
|
|
888
|
+
const cap = Number(budget.program_timeout_secs) || 120
|
|
889
|
+
const limit = Math.min(cap, Number(manifest?.resources?.timeout_secs) || cap)
|
|
890
|
+
let timedOut = false
|
|
891
|
+
// the time the macro itself took: waits for generated pictures and clips have their own limit
|
|
892
|
+
const started = Date.now()
|
|
893
|
+
let media = 0
|
|
894
|
+
let mediaSince = 0
|
|
895
|
+
let mediaMs = 0
|
|
896
|
+
const timer = setInterval(() => {
|
|
897
|
+
if (Date.now() - started - mediaMs - (media ? Date.now() - mediaSince : 0) > limit * 1000) { timedOut = true; child.kill() }
|
|
898
|
+
}, 1000)
|
|
899
|
+
const out: string[] = []
|
|
900
|
+
const pending = new Set<Promise<void>>()
|
|
901
|
+
try {
|
|
902
|
+
for await (const line of child.lines()) {
|
|
903
|
+
if (!line.startsWith(BRIDGE_PREFIX)) { out.push(line); continue }
|
|
904
|
+
const msg = JSON.parse(line.slice(BRIDGE_PREFIX.length)) as { id: number; op: string; req: unknown }
|
|
905
|
+
// answered as they come: a macro that generates several pictures at once waits for the slowest, not the sum
|
|
906
|
+
const waiting = msg.op === 'ai.image' || msg.op === 'ai.video'
|
|
907
|
+
if (waiting && media++ === 0) mediaSince = Date.now()
|
|
908
|
+
const answer: Promise<void> = bridge.handle(msg.op, msg.req)
|
|
909
|
+
.then((body) => child.writeLine(JSON.stringify({ id: msg.id, body })))
|
|
910
|
+
.finally(() => { if (waiting && --media === 0) mediaMs += Date.now() - mediaSince; pending.delete(answer) })
|
|
911
|
+
pending.add(answer)
|
|
912
|
+
}
|
|
913
|
+
await Promise.allSettled([...pending])
|
|
914
|
+
} finally {
|
|
915
|
+
clearInterval(timer)
|
|
916
|
+
await child.closeInput()
|
|
917
|
+
}
|
|
918
|
+
const code = await child.status
|
|
919
|
+
const log = [...out, await child.stderr, ...(timedOut ? [`The macro timed out (${limit} s)`] : [])].filter(Boolean).join('\n')
|
|
920
|
+
let results: unknown = null
|
|
921
|
+
try { results = JSON.parse(await host.readTextFile(`${dir}/output/.aiws/results.json`)) } catch { results = null }
|
|
922
|
+
if (timedOut) results = { error: `The macro timed out (${limit} s)` }
|
|
923
|
+
return { source, results, log, code }
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
const RUN_EXEC_OPTIONS: OptionDefinition[] = [
|
|
927
|
+
WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION,
|
|
928
|
+
{ 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 },
|
|
929
|
+
]
|
|
930
|
+
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'])
|
|
931
|
+
|
|
932
|
+
const runExecCommand: CommandDefinition = {
|
|
933
|
+
verb: 'run-exec',
|
|
934
|
+
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',
|
|
935
|
+
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).',
|
|
936
|
+
options: RUN_EXEC_OPTIONS,
|
|
937
|
+
inputSchema: RUN_EXEC_INPUT,
|
|
938
|
+
outputSchema: OBJECT_OUTPUT,
|
|
939
|
+
resultSchemaVersion: 1,
|
|
940
|
+
access: { mode: 'fixed', level: 'write' },
|
|
941
|
+
asyncMode: 'sync',
|
|
942
|
+
requiresSession: true,
|
|
943
|
+
examples: ['buckyos aiws run-exec --workspace ws_abc --run run_xyz --attempt 1 --dir work'],
|
|
944
|
+
handler: async (ctx, input) => {
|
|
945
|
+
const run = await execMacro(ctx, input)
|
|
946
|
+
const r = (run.results ?? {}) as Record<string, unknown>
|
|
947
|
+
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 }
|
|
948
|
+
},
|
|
949
|
+
}
|
|
950
|
+
|
|
217
951
|
const runProgramCommand: CommandDefinition = {
|
|
218
952
|
verb: 'run-program',
|
|
219
|
-
summary: '
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
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']),
|
|
953
|
+
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',
|
|
954
|
+
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`.',
|
|
955
|
+
options: RUN_EXEC_OPTIONS,
|
|
956
|
+
inputSchema: RUN_EXEC_INPUT,
|
|
226
957
|
outputSchema: OBJECT_OUTPUT,
|
|
227
958
|
resultSchemaVersion: 1,
|
|
228
959
|
access: { mode: 'fixed', level: 'write' },
|
|
229
960
|
asyncMode: 'sync',
|
|
230
961
|
requiresSession: true,
|
|
231
|
-
examples: ['buckyos aiws run-program --workspace ws_abc --run run_xyz --attempt 1 --dir work
|
|
962
|
+
examples: ['buckyos aiws run-program --workspace ws_abc --run run_xyz --attempt 1 --dir work'],
|
|
232
963
|
handler: async (ctx, input) => {
|
|
233
|
-
const dir = requiredInputString(input, 'dir')
|
|
234
964
|
const host = getHost()
|
|
235
|
-
const
|
|
236
|
-
|
|
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(() => '') : ''
|
|
965
|
+
const dir = host.path.resolve(ctx.cwd, requiredInputString(input, 'dir'))
|
|
966
|
+
const run = await execMacro(ctx, input)
|
|
240
967
|
const files: Record<string, unknown> = {}
|
|
241
968
|
const walk = async (rel: string) => {
|
|
242
969
|
for (const entry of await host.readDir(`${dir}/output${rel ? `/${rel}` : ''}`)) {
|
|
@@ -252,26 +979,43 @@ const runProgramCommand: CommandDefinition = {
|
|
|
252
979
|
}
|
|
253
980
|
}
|
|
254
981
|
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 })
|
|
982
|
+
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
983
|
},
|
|
257
984
|
}
|
|
258
985
|
|
|
986
|
+
const runStartCommand: CommandDefinition = {
|
|
987
|
+
verb: 'run-start',
|
|
988
|
+
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',
|
|
989
|
+
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.',
|
|
990
|
+
options: [WORKSPACE_OPTION, { name: 'wish', property: 'wish_id', description: 'The wish (its entity id)', type: 'string', required: true },
|
|
991
|
+
{ name: 'stage', property: 'stage', description: 'analyze | code | run (default analyze)', type: 'string' }],
|
|
992
|
+
inputSchema: workspaceInput({ wish_id: { type: 'string', minLength: 1 }, stage: { type: 'string', enum: ['analyze', 'code', 'run'] } }, ['wish_id']),
|
|
993
|
+
outputSchema: OBJECT_OUTPUT,
|
|
994
|
+
resultSchemaVersion: 1,
|
|
995
|
+
access: { mode: 'fixed', level: 'write' },
|
|
996
|
+
asyncMode: 'sync',
|
|
997
|
+
requiresSession: true,
|
|
998
|
+
examples: ['buckyos aiws run-start --workspace ws_abc --wish wish_q3 --stage analyze'],
|
|
999
|
+
handler: (ctx, input) => aiws(ctx, 'proc.start', {
|
|
1000
|
+
workspace_id: requiredInputString(input, 'workspace_id'), program: 'wish.xllm@1', idempotency_key: ctx.idempotencyKey ?? `cli-${ctx.traceId}`,
|
|
1001
|
+
params: { wish_id: requiredInputString(input, 'wish_id'), stage: inputString(input, 'stage') || 'analyze', execution: { mode: 'local' } },
|
|
1002
|
+
}),
|
|
1003
|
+
}
|
|
1004
|
+
|
|
259
1005
|
const runReportCommand: CommandDefinition = {
|
|
260
1006
|
verb: 'run-report',
|
|
261
|
-
summary: 'End a claimed run: --finished after the stage
|
|
262
|
-
description: 'The service validates and plans what
|
|
1007
|
+
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',
|
|
1008
|
+
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
1009
|
options: [
|
|
264
1010
|
WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION,
|
|
265
|
-
{ name: 'finished', property: 'finished', description: 'The stage is done: what
|
|
266
|
-
{ name: '
|
|
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' },
|
|
1011
|
+
{ name: 'finished', property: 'finished', description: 'The stage is done: what it collected becomes the candidate', type: 'boolean' },
|
|
1012
|
+
{ name: 'analysis', property: 'analysis', description: 'Analysis JSON (analyze runs, wish.analysis.v3)', type: 'string' },
|
|
269
1013
|
{ name: 'analysis-file', property: 'analysis_file', description: 'Path of a JSON file holding the analysis', type: 'string' },
|
|
270
1014
|
{ name: 'summary', property: 'summary', description: 'One paragraph on what was done', type: 'string' },
|
|
271
1015
|
{ name: 'warning', property: 'warnings', description: 'A warning for the user (repeatable)', type: 'string' },
|
|
272
1016
|
{ name: 'error', property: 'error', description: 'Report a failure instead: its reason', type: 'string' },
|
|
273
1017
|
],
|
|
274
|
-
inputSchema: workspaceInput({ run_id: { type: 'string', minLength: 1 }, attempt: { type: 'integer', minimum: 1 }, finished: { type: 'boolean' },
|
|
1018
|
+
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
1019
|
outputSchema: OBJECT_OUTPUT,
|
|
276
1020
|
resultSchemaVersion: 1,
|
|
277
1021
|
access: { mode: 'fixed', level: 'write' },
|
|
@@ -279,7 +1023,6 @@ const runReportCommand: CommandDefinition = {
|
|
|
279
1023
|
requiresSession: true,
|
|
280
1024
|
examples: [
|
|
281
1025
|
'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
1026
|
'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --analysis-file out/analysis.json',
|
|
284
1027
|
'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --error "the input table is empty"',
|
|
285
1028
|
],
|
|
@@ -290,11 +1033,8 @@ const runReportCommand: CommandDefinition = {
|
|
|
290
1033
|
params.error = { code: 'EXECUTOR_FAILED', detail: error }
|
|
291
1034
|
} else if (input.finished === true) {
|
|
292
1035
|
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
1036
|
} else {
|
|
296
|
-
params.
|
|
297
|
-
params.read_set = []
|
|
1037
|
+
params.analysis = await jsonInput(input, 'analysis', 'analysis_file', 'an analysis')
|
|
298
1038
|
}
|
|
299
1039
|
const summary = inputString(input, 'summary')
|
|
300
1040
|
if (summary) params.summary = summary
|
|
@@ -1005,7 +1745,7 @@ const templateCommand: CommandDefinition = {
|
|
|
1005
1745
|
export function createAiwsModule(): CommandModule {
|
|
1006
1746
|
return {
|
|
1007
1747
|
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,
|
|
1748
|
+
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)',
|
|
1749
|
+
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
1750
|
}
|
|
1011
1751
|
}
|