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
@@ -0,0 +1,383 @@
1
+ import {
2
+ AIWS_PROTOCOL_VERSION,
3
+ BindFailure,
4
+ bindingsPayload,
5
+ createOps,
6
+ noUiDialogs,
7
+ orderKeyBetween,
8
+ resolveBindings,
9
+ } from 'buckyos/node'
10
+ import type { CommandDefinition, JsonSchema } from '../core/command.ts'
11
+ import type { CommandContext } from '../core/context.ts'
12
+ import { ToolError, UsageError } from '../core/errors.ts'
13
+ import { callService, expectObject, inputString, requiredInputString } from '../core/service.ts'
14
+
15
+ // Placing a control on a canvas as an Agent (buckyos notepads/aiworkspace-control-on-bind-todo.md §2.8, Q6): the same
16
+ // on_bind / on_init_control a person's insertion runs (buckyos-websdk aiws_bind.ts), without dialogs (`no_ui`). What the
17
+ // Agent gives (--bind) is taken; what the default rule settles without a choice (none → created, one → bound) is done;
18
+ // where a person would have to choose, the command fails naming the binding to give. One Commit. An HTML control that
19
+ // decides its bindings in its own script (on_bind "script", TODO §2.9) is not run here: what the Agent gives is its ctx,
20
+ // taken as it is (owner 11-12).
21
+
22
+ const OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }
23
+ const SERVICE = 'aiworkspace'
24
+ const NOT_DATA = new Set([
25
+ 'buckyos.cell',
26
+ 'buckyos.container',
27
+ 'buckyos.block-def',
28
+ 'buckyos.viewport',
29
+ 'buckyos.show-path',
30
+ ])
31
+ const BUILTIN_SIZE: Record<string, { w: number; h: number }> = {
32
+ todo: { w: 420, h: 520 },
33
+ calendar: { w: 860, h: 620 },
34
+ }
35
+
36
+ type Envelope = Record<string, unknown> & {
37
+ entity_id: string
38
+ type_id: string
39
+ parent_id?: string | null
40
+ order_key?: string | null
41
+ deleted?: boolean
42
+ }
43
+ // the shapes of buckyos-websdk aiws_bind.ts (the CLI reads the SDK's built JavaScript)
44
+ type BindingDecl = {
45
+ accepts?: string[]
46
+ required?: boolean
47
+ many?: boolean
48
+ schema_id?: string
49
+ title?: string
50
+ }
51
+ type DataInfo = {
52
+ entity_id: string
53
+ type_id: string
54
+ schema_id: string | null
55
+ title: string | null
56
+ }
57
+ type DataQuery = { accepts?: string[]; schema_id?: string; ids?: string[] }
58
+ type GivenCtx = {
59
+ node: string
60
+ given: Record<string, string | string[]>
61
+ decls: Record<string, BindingDecl>
62
+ }
63
+
64
+ /** An HTML control's on_bind for an Agent: its script runs in a person's browser only, so the bindings given are taken as
65
+ * they are; a required one not given fails naming it. */
66
+ function givenOnly(title: string) {
67
+ return (ctx: GivenCtx) => {
68
+ const missing = Object.entries(ctx.decls).filter(([name, d]) =>
69
+ d.required && ctx.given[name] === undefined
70
+ )
71
+ .map(([name]) => name)
72
+ if (missing.length > 0) {
73
+ throw new BindFailure(
74
+ `${title} decides its data in its own script, which runs in a person's browser only: give ${
75
+ missing.join(', ')
76
+ } with --bind`,
77
+ 'NEEDS_UI',
78
+ ctx.node,
79
+ missing[0],
80
+ )
81
+ }
82
+ return Promise.resolve({ bindings: ctx.given, create: [] })
83
+ }
84
+ }
85
+ type Outcome =
86
+ | {
87
+ ok: true
88
+ results: Map<string, { bindings: Record<string, string | string[]> }>
89
+ then: { node: string; action: string }[]
90
+ }
91
+ | { ok: false; error: { code: string; message: string; binding?: string } }
92
+
93
+ async function call(
94
+ ctx: CommandContext,
95
+ method: string,
96
+ params: Record<string, unknown>,
97
+ ): Promise<Record<string, unknown>> {
98
+ const result = expectObject(await callService<unknown>(ctx, SERVICE, method, params), method)
99
+ if (result.ok === false) {
100
+ const error = expectObject(result.error, `${method}.error`)
101
+ const code = typeof error.code === 'string' ? error.code : 'AIWS_ERROR'
102
+ throw new ToolError(code, `${code}: ${String(error.detail ?? code)}`, undefined, false, {
103
+ ...(error.sub_code ? { sub_code: error.sub_code } : {}),
104
+ ...(error.data !== undefined ? { data: error.data } : {}),
105
+ })
106
+ }
107
+ return result
108
+ }
109
+
110
+ /** `name=id[,id];name2=id` → given bindings. */
111
+ function parseBind(text: string | undefined): Record<string, string | string[]> {
112
+ const out: Record<string, string | string[]> = {}
113
+ for (const part of (text ?? '').split(';').map((s) => s.trim()).filter(Boolean)) {
114
+ const at = part.indexOf('=')
115
+ if (at <= 0) throw new UsageError('AIWS_USAGE', `--bind ${part}: name=id[,id]`)
116
+ const ids = part.slice(at + 1).split(',').map((s) => s.trim()).filter(Boolean)
117
+ out[part.slice(0, at).trim()] = ids.length === 1 ? ids[0] : ids
118
+ }
119
+ return out
120
+ }
121
+
122
+ function freeName(taken: Set<string>, base: string): string {
123
+ let name = base
124
+ for (let n = 2; taken.has(name); n++) name = `${base} (${n})`
125
+ taken.add(name)
126
+ return name
127
+ }
128
+
129
+ export const placeCommand: CommandDefinition = {
130
+ verb: 'place',
131
+ summary:
132
+ 'Place a control on a canvas the way a person inserts it: its on_bind settles its data (none → created, one → bound); give a binding where it would ask',
133
+ description:
134
+ 'CONTROL is `todo`, `calendar` or a definition of the workspace (its entity id, or its identity <author_did>#<name>). Bindings you give (--bind "photos=d1;votes=t1,t2", a list for a `many` binding) are taken; the rest follow the control\'s on_bind with no dialogs: a choice a person would make fails with NEEDS_UI naming the binding to give. Data it creates (a standard table, a composite\'s declared table or folder) goes into the canvas\'s content folder, owned by the control. A composite\'s on_init_control actions (e.g. preparing a ballot) are listed in `then`: run them yourself (the Desktop runs them for a person). An HTML control whose own script decides its data (on_bind "script", see its AGENT.md) is not run here: give its bindings with --bind; a required one missing fails with NEEDS_UI.',
135
+ positionals: [{
136
+ name: 'control',
137
+ description: 'todo | calendar | a definition id | <author_did>#<name>',
138
+ required: true,
139
+ }],
140
+ options: [
141
+ {
142
+ name: 'workspace',
143
+ property: 'workspace_id',
144
+ description: 'Workspace id (ws_…)',
145
+ type: 'string',
146
+ required: true,
147
+ },
148
+ {
149
+ name: 'surface',
150
+ property: 'surface',
151
+ description: 'Canvas (Surface) id',
152
+ type: 'string',
153
+ required: true,
154
+ },
155
+ {
156
+ name: 'bind',
157
+ property: 'bind',
158
+ description: 'Bindings you give: "name=id[,id];name=id"',
159
+ type: 'string',
160
+ },
161
+ { name: 'title', property: 'title', description: 'Title of the control', type: 'string' },
162
+ {
163
+ name: 'at',
164
+ property: 'at',
165
+ description: 'Position x,y on a free canvas (default: right of what is on it)',
166
+ type: 'string',
167
+ },
168
+ {
169
+ name: 'config',
170
+ property: 'config',
171
+ description: 'Instance properties, a JSON object',
172
+ type: 'string',
173
+ },
174
+ ],
175
+ inputSchema: {
176
+ type: 'object',
177
+ properties: {
178
+ control: { type: 'string', minLength: 1 },
179
+ workspace_id: { type: 'string', minLength: 1 },
180
+ surface: { type: 'string', minLength: 1 },
181
+ bind: { type: 'string' },
182
+ title: { type: 'string' },
183
+ at: { type: 'string' },
184
+ config: { type: 'string' },
185
+ },
186
+ required: ['control', 'workspace_id', 'surface'],
187
+ additionalProperties: false,
188
+ },
189
+ outputSchema: OBJECT_OUTPUT,
190
+ resultSchemaVersion: 1,
191
+ access: { mode: 'fixed', level: 'write' },
192
+ asyncMode: 'sync',
193
+ requiresSession: true,
194
+ examples: [
195
+ 'buckyos aiws place todo --workspace ws_… --surface sf_…',
196
+ 'buckyos aiws place calendar --workspace ws_… --surface sf_… --bind "events=t_cal"',
197
+ 'buckyos aiws place did:bns:buckyos#photo-vote --workspace ws_… --surface sf_… --bind "photos=d_trip"',
198
+ ],
199
+ handler: async (ctx, input) => {
200
+ const ws = requiredInputString(input, 'workspace_id')
201
+ const surfaceId = requiredInputString(input, 'surface')
202
+ const control = requiredInputString(input, 'control')
203
+ const info = await call(ctx, 'ws.get_info', { workspace_id: ws })
204
+ const entities = (await call(ctx, 'doc.outline', { workspace_id: ws })).entities as Envelope[]
205
+ const byId = new Map(entities.map((e) => [e.entity_id, e]))
206
+ const surface = byId.get(surfaceId)
207
+ if (!surface || surface.kind !== 'surface') {
208
+ throw new UsageError('AIWS_USAGE', `${surfaceId} is not a canvas of this workspace`)
209
+ }
210
+ const folderId = String(surface.content_folder_id ?? '')
211
+ const config = inputString(input, 'config')
212
+ ? JSON.parse(inputString(input, 'config')!) as Record<string, unknown>
213
+ : undefined
214
+ // by default right of what is already on the canvas, so the controls an Agent places do not cover each other
215
+ const right = entities.filter((e) => e.parent_id === surfaceId && !e.deleted).reduce(
216
+ (max, e) => {
217
+ const p = e.placement as { x?: unknown; w?: unknown } | undefined
218
+ return typeof p?.x === 'number'
219
+ ? Math.max(max, p.x + (typeof p.w === 'number' ? p.w : 320))
220
+ : max
221
+ },
222
+ 0,
223
+ )
224
+ const at = inputString(input, 'at')
225
+ ? inputString(input, 'at')!.split(',').map(Number)
226
+ : [right > 0 ? right + 40 : 40, 40]
227
+
228
+ // the control: a built-in data control's contract, or a definition of the workspace
229
+ let decls: Record<string, BindingDecl>
230
+ let node: { onBind?: unknown; onInit?: unknown } = {}
231
+ let op: Record<string, unknown>
232
+ let title = inputString(input, 'title') ?? undefined
233
+ const id = `c${Math.random().toString(36).slice(2, 14)}`
234
+ if (control === 'todo' || control === 'calendar') {
235
+ const contract = expectObject(
236
+ (await call(ctx, 'control.describe', { kind: control })).control,
237
+ 'control',
238
+ ).contract as Record<string, unknown>
239
+ decls = (contract.bindings ?? {}) as Record<string, BindingDecl>
240
+ title ??= String(contract.title ?? control)
241
+ const size = BUILTIN_SIZE[control]
242
+ op = {
243
+ op: 'entity.create',
244
+ entity_id: id,
245
+ type_id: 'buckyos.container',
246
+ parent_id: surfaceId,
247
+ placement: { x: at[0] || 40, y: at[1] || 40, ...size },
248
+ payload: { kind: control, layout: { mode: 'data' }, title },
249
+ }
250
+ } else {
251
+ const def = entities.find((e) =>
252
+ e.type_id === 'buckyos.block-def' && !e.deleted &&
253
+ (e.entity_id === control || e.ident === control)
254
+ )
255
+ if (!def) {
256
+ throw new UsageError(
257
+ 'AIWS_USAGE',
258
+ `no control ${control} in this workspace (build or import it first)`,
259
+ )
260
+ }
261
+ const payload =
262
+ ((await call(ctx, 'doc.read', { workspace_id: ws, entity_id: def.entity_id })).content as {
263
+ payload: Record<string, unknown>
264
+ }).payload
265
+ decls = (payload.bindings ?? {}) as Record<string, BindingDecl>
266
+ title ??= String(payload.title ?? def.entity_id)
267
+ // a composite's declared steps; an HTML control's script is not run (its init check is the default one)
268
+ node = payload.on_bind === 'script'
269
+ ? { onBind: givenOnly(title) }
270
+ : payload.kind === 'composite'
271
+ ? { onBind: payload.on_bind, onInit: payload.on_init_control }
272
+ : {}
273
+ const size = (payload.default_size as { w: number; h: number } | undefined) ??
274
+ { w: 320, h: 240 }
275
+ op = payload.kind === 'composite'
276
+ ? {
277
+ op: 'entity.create',
278
+ entity_id: id,
279
+ type_id: 'buckyos.container',
280
+ parent_id: surfaceId,
281
+ placement: { x: at[0] || 40, y: at[1] || 40, w: 'auto', h: 'auto' },
282
+ payload: {
283
+ kind: 'composite',
284
+ def_ref: { entity_id: def.entity_id },
285
+ ...(config ? { config } : {}),
286
+ },
287
+ }
288
+ : {
289
+ op: 'entity.create',
290
+ entity_id: id,
291
+ type_id: 'buckyos.cell',
292
+ parent_id: surfaceId,
293
+ placement: { x: at[0] || 40, y: at[1] || 40, ...size },
294
+ payload: {
295
+ view: { type: String(payload.kind) },
296
+ def_ref: { entity_id: def.entity_id },
297
+ ...(config ? { config } : {}),
298
+ },
299
+ }
300
+ }
301
+
302
+ const data: DataInfo[] = entities.filter((e) => !e.deleted && !NOT_DATA.has(e.type_id))
303
+ .map((e) => ({
304
+ entity_id: e.entity_id,
305
+ type_id: e.type_id,
306
+ schema_id: (e.schema_id as string | null) ?? null,
307
+ title: (e.title as string | null) ?? (e.name as string | null) ?? null,
308
+ }))
309
+ const outcome = await resolveBindings(
310
+ {
311
+ id,
312
+ title: title!,
313
+ decls,
314
+ given: parseBind(inputString(input, 'bind') ?? undefined),
315
+ children: [],
316
+ ...node,
317
+ } as never,
318
+ {
319
+ reason: 'insert',
320
+ no_ui: true,
321
+ dialogs: noUiDialogs(),
322
+ find: (q: DataQuery) =>
323
+ data.filter((d) =>
324
+ (!q.accepts?.length || q.accepts.includes(d.type_id)) &&
325
+ (!q.schema_id || d.schema_id === q.schema_id) && (!q.ids || q.ids.includes(d.entity_id))
326
+ ),
327
+ },
328
+ ) as Outcome
329
+ if (!outcome.ok) {
330
+ throw new ToolError(
331
+ outcome.error.code,
332
+ `${outcome.error.code}: ${outcome.error.message}`,
333
+ undefined,
334
+ false,
335
+ { ...(outcome.error.binding ? { binding: outcome.error.binding } : {}) },
336
+ )
337
+ }
338
+
339
+ const children = entities.filter((e) => e.parent_id === folderId && !e.deleted)
340
+ const taken = new Set(children.map((e) => String(e.name ?? '')).filter(Boolean))
341
+ let last = children.map((e) => e.order_key ?? '').filter(Boolean).sort().at(-1) ?? null
342
+ const made = createOps(outcome.results, {
343
+ folderId,
344
+ newId: () => `d${Math.random().toString(36).slice(2, 14)}`,
345
+ orderKey: () => {
346
+ last = orderKeyBetween(last, null)
347
+ return last
348
+ },
349
+ freeName: (name: string) => freeName(taken, name),
350
+ locale: /^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale) ? 'zh' : 'en',
351
+ })
352
+ const bindings = bindingsPayload(outcome.results.get(id)!.bindings, decls, made.ids)
353
+ const lastOnCanvas =
354
+ entities.filter((e) => e.parent_id === surfaceId && !e.deleted).map((e) => e.order_key ?? '')
355
+ .filter(Boolean).sort().at(-1) ?? null
356
+ op.order_key = orderKeyBetween(lastOnCanvas, null)
357
+ if (Object.keys(bindings).length > 0) {
358
+ ;(op.payload as Record<string, unknown>).bindings = bindings
359
+ }
360
+ const commit = await call(ctx, 'doc.commit', {
361
+ protocol_version: AIWS_PROTOCOL_VERSION,
362
+ workspace_id: ws,
363
+ epoch: info.epoch,
364
+ idempotency_key: `place-${id}`,
365
+ origin: 'agent',
366
+ message: `place ${title}`,
367
+ operations: [...made.ops, op],
368
+ })
369
+ if (commit.status !== 'accepted') {
370
+ throw new ToolError(
371
+ 'AIWS_COMMIT_REFUSED',
372
+ `the placement was not accepted: ${JSON.stringify(commit).slice(0, 500)}`,
373
+ )
374
+ }
375
+ return {
376
+ entity_id: id,
377
+ bindings,
378
+ created: Object.values(made.ids),
379
+ then: outcome.then.map((t) => t.action),
380
+ commit_seq: commit.seq ?? null,
381
+ }
382
+ },
383
+ }
@@ -0,0 +1,256 @@
1
+ import { AiwsFailure, calendarOccurrences, localDate, ScheduleClient, viewerTimeZone } from 'buckyos/node'
2
+ import type { CommandDefinition, JsonSchema, OptionDefinition } from '../core/command.ts'
3
+ import type { CommandContext } from '../core/context.ts'
4
+ import { ToolError, UsageError } from '../core/errors.ts'
5
+ import { callService, expectObject, inputString, requiredInputString } from '../core/service.ts'
6
+
7
+ // The person's private schedule in AI Workspace (buckyos notepads/aiworkspace-control-mechanism-todo.md G9, G11): the
8
+ // Workspace named `schedule`, its to-do table `todo` and calendar table `calendar` (created on first use), read and
9
+ // changed with the same operations the official to-do and calendar controls use (buckyos-websdk aiws_schedule.ts).
10
+ // What the controls show changes at once. Times are RFC 3339 instants or YYYY-MM-DD dates.
11
+
12
+ const OBJECT_OUTPUT: JsonSchema = { type: 'object', additionalProperties: true }
13
+
14
+ // the module's types, as its functions declare them (the CLI reads the SDK's built JavaScript)
15
+ type EventOccurrence = ReturnType<typeof calendarOccurrences>[number]
16
+ type TodoItem = Awaited<ReturnType<ScheduleClient['todos']>>[number]
17
+ type EventChange = Parameters<ScheduleClient['editEvent']>[1]
18
+ type RecurrenceScope = NonNullable<Parameters<ScheduleClient['editEvent']>[2]>
19
+
20
+ function schedule(ctx: CommandContext): ScheduleClient {
21
+ return new ScheduleClient({
22
+ call: async <T,>(method: string, params: Record<string, unknown>): Promise<T> => {
23
+ const result = expectObject(await callService<unknown>(ctx, 'aiworkspace', method, params), method)
24
+ if (result.ok === false) {
25
+ const error = expectObject(result.error, `${method}.error`)
26
+ 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 })
27
+ }
28
+ return result as T
29
+ },
30
+ }, { locale: /^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale) ? 'zh' : 'en' })
31
+ }
32
+
33
+ /** A service refusal as the CLI's error (its code first, so an Agent can branch on it). */
34
+ async function run<T>(work: () => Promise<T>): Promise<T> {
35
+ try {
36
+ return await work()
37
+ } catch (error) {
38
+ 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 } : {}) })
39
+ throw error
40
+ }
41
+ }
42
+
43
+ const todoView = (i: TodoItem) => ({ id: i.record_id, title: i.title, status: i.status, done: i.done, due: i.due, order: i.order, ...(i.done_at ? { done_at: i.done_at } : {}), ...(Object.keys(i.ext).length ? { ext: i.ext } : {}) })
44
+
45
+ const eventView = (o: EventOccurrence) => ({
46
+ id: o.id, record_id: o.row.record_id, title: o.title, all_day: o.allDay,
47
+ ...(o.allDay ? { start_date: o.startDate, end_date: o.endDate } : { start: new Date(o.startMs!).toISOString(), end: new Date(o.endMs!).toISOString() }),
48
+ ...(o.recurring ? { recurring: true, original: o.original } : {}), ...(o.override ? { changed_once: true } : {}), ...(o.agentWritten ? { agent_written: true } : {}),
49
+ ...(o.status ? { status: o.status } : {}), ...(Object.keys(o.ext).length ? { ext: o.ext } : {}),
50
+ })
51
+
52
+ const DATE = /^\d{4}-\d{2}-\d{2}$/
53
+
54
+ function parseExt(input: Record<string, unknown>): Record<string, unknown> | undefined {
55
+ const text = inputString(input, 'ext')
56
+ if (!text) return undefined
57
+ const ext = JSON.parse(text) as unknown
58
+ if (!ext || typeof ext !== 'object' || Array.isArray(ext)) throw new UsageError('AIWS_USAGE', '--ext must be a JSON object')
59
+ return ext as Record<string, unknown>
60
+ }
61
+
62
+ const ID: OptionDefinition = { name: 'id', property: 'id', description: 'To-do record id (`todo list` shows them)', type: 'string' }
63
+
64
+ export const todoCommand: CommandDefinition = {
65
+ verb: 'todo',
66
+ summary: 'Your to-do list (the private schedule Workspace): list | add | done | undone | update | move | rm',
67
+ description: 'The to-dos are records of the table `todo` in your Workspace named `schedule` (created on first use); the to-do control shows every change at once. Status is a board column (`todo`, `doing`, `done` unless columns were added); `done` completes.',
68
+ positionals: [{ name: 'action', description: 'list | add | done | undone | update | move | rm', required: true }, { name: 'title', description: 'add: the title', required: false }],
69
+ options: [
70
+ ID,
71
+ { name: 'all', property: 'all', description: 'list: completed ones too', type: 'boolean' },
72
+ { name: 'title', property: 'new_title', description: 'update: the new title', type: 'string' },
73
+ { name: 'status', property: 'status', description: 'add / update / move: the status (board column) option id', type: 'string' },
74
+ { name: 'due', property: 'due', description: 'add / update: due date YYYY-MM-DD (update: "none" clears it)', type: 'string' },
75
+ { name: 'priority', property: 'priority', description: 'add / update: low | normal | high | urgent | none', type: 'string', enum: ['low', 'normal', 'high', 'urgent', 'none'] },
76
+ { name: 'before', property: 'before', description: 'add / move: place before this to-do id', type: 'string' },
77
+ { name: 'after', property: 'after', description: 'add / move: place after this to-do id', type: 'string' },
78
+ { name: 'ext', property: 'ext', description: 'add / update: extension fields JSON (merged on update; null removes a key)', type: 'string' },
79
+ ],
80
+ inputSchema: {
81
+ type: 'object',
82
+ properties: { action: { type: 'string', enum: ['list', 'add', 'done', 'undone', 'update', 'move', 'rm'] }, title: { type: 'string' }, id: { type: 'string' }, all: { type: 'boolean' }, new_title: { type: 'string' }, status: { type: 'string' }, due: { type: 'string' }, priority: { type: 'string' }, before: { type: 'string' }, after: { type: 'string' }, ext: { type: 'string' } },
83
+ required: ['action'], additionalProperties: false,
84
+ },
85
+ outputSchema: OBJECT_OUTPUT,
86
+ resultSchemaVersion: 1,
87
+ access: { mode: 'fixed', level: 'write' },
88
+ asyncMode: 'sync',
89
+ requiresSession: true,
90
+ examples: [
91
+ 'buckyos aiws todo list',
92
+ 'buckyos aiws todo add "Renew the passport" --due 2026-12-01 --priority high',
93
+ 'buckyos aiws todo done --id t…',
94
+ 'buckyos aiws todo move --id t… --status doing --before t…',
95
+ ],
96
+ handler: (ctx, input) => run(async () => {
97
+ const s = schedule(ctx)
98
+ const action = requiredInputString(input, 'action')
99
+ const id = () => requiredInputString(input, 'id')
100
+ const due = inputString(input, 'due')
101
+ if (due && due !== 'none' && !DATE.test(due)) throw new UsageError('AIWS_USAGE', '--due must be YYYY-MM-DD')
102
+ const priority = inputString(input, 'priority')
103
+ switch (action) {
104
+ case 'list': {
105
+ const handle = await s.ensure()
106
+ const items = await s.todos({ includeDone: input.all === true })
107
+ return { workspace_id: handle.workspace_id, table: handle.todo, items: items.map(todoView) }
108
+ }
109
+ case 'add': {
110
+ const title = requiredInputString(input, 'title')
111
+ const ext = { ...(parseExt(input) ?? {}), ...(priority && priority !== 'none' ? { priority } : {}) }
112
+ const item = await s.addTodo({ title, status: inputString(input, 'status') ?? undefined, due: due && due !== 'none' ? due : undefined, ext: ext as never }, { before: inputString(input, 'before') ?? undefined, after: inputString(input, 'after') ?? undefined })
113
+ return { item: todoView(item) }
114
+ }
115
+ case 'done': case 'undone': await s.completeTodo(id(), action === 'done'); return { ok: true, id: id(), done: action === 'done' }
116
+ case 'update': {
117
+ const ext = parseExt(input)
118
+ const merge: Record<string, unknown> = { ...(ext ?? {}) }
119
+ if (priority) merge.priority = priority === 'none' ? null : priority
120
+ await s.updateTodo(id(), { ...(inputString(input, 'new_title') ? { title: inputString(input, 'new_title')! } : {}), ...(inputString(input, 'status') ? { status: inputString(input, 'status')! } : {}), ...(due ? { due: due === 'none' ? null : due } : {}), ...(Object.keys(merge).length ? { ext_merge: merge as never } : {}) })
121
+ return { ok: true, id: id() }
122
+ }
123
+ case 'move': await s.moveTodo(id(), { status: inputString(input, 'status') ?? undefined, before: inputString(input, 'before') ?? undefined, after: inputString(input, 'after') ?? undefined }); return { ok: true, id: id() }
124
+ case 'rm': { const ids = id().split(',').map((x) => x.trim()).filter(Boolean); await s.removeTodos(ids); return { ok: true, removed: ids } }
125
+ default: throw new UsageError('AIWS_USAGE', `todo: unknown action ${action}`)
126
+ }
127
+ }),
128
+ }
129
+
130
+ const SCOPE: OptionDefinition = { name: 'scope', property: 'scope', description: 'A repeating event: one (only this occurrence, default) | following (this and later) | all', type: 'string', enum: ['one', 'following', 'all'] }
131
+
132
+ export const calCommand: CommandDefinition = {
133
+ verb: 'cal',
134
+ summary: 'Your calendar (the private schedule Workspace): list | add | update | rm | skip | postpone',
135
+ description: 'Events are records of the table `calendar` in your Workspace named `schedule`. A repeating event has `ext.rrule` (iCalendar RRULE subset: FREQ DAILY/WEEKLY/MONTHLY/YEARLY, INTERVAL, COUNT or UNTIL, BYDAY with -1FR style ordinals, BYMONTHDAY, BYMONTH, BYSETPOS); `list` expands it and names each occurrence `<record_id>@<original start>` — pass that id to change, skip or postpone one occurrence. Rules the subset cannot express go to ext.rule_text with ext.occurrences written by you.',
136
+ positionals: [{ name: 'action', description: 'list | add | update | rm | skip | postpone', required: true }, { name: 'title', description: 'add: the title', required: false }],
137
+ options: [
138
+ { name: 'id', property: 'id', description: 'Event id or occurrence id (`cal list` shows them)', type: 'string' },
139
+ { name: 'from', property: 'from', description: 'list: first day YYYY-MM-DD (default today)', type: 'string' },
140
+ { name: 'days', property: 'days', description: 'list: how many days (default 7, ≤ 366)', type: 'integer' },
141
+ { name: 'start', property: 'start', description: 'add / update: start, RFC 3339 instant (timed) or YYYY-MM-DD (all-day)', type: 'string' },
142
+ { name: 'end', property: 'end', description: 'add / update: end, same form as --start (all-day: the last day, inclusive)', type: 'string' },
143
+ { name: 'title', property: 'new_title', description: 'update: the new title', type: 'string' },
144
+ { name: 'rrule', property: 'rrule', description: 'add / update: repeat rule, e.g. FREQ=WEEKLY;BYDAY=MO,WE ("none" stops repeating)', type: 'string' },
145
+ { name: 'tz', property: 'tz', description: 'add: the IANA time zone a series repeats in (default this machine’s)', type: 'string' },
146
+ { name: 'location', property: 'location', description: 'add / update: where', type: 'string' },
147
+ { name: 'reminder', property: 'reminder', description: 'add: minutes before to remind, comma separated (e.g. 10,1440)', type: 'string' },
148
+ { name: 'minutes', property: 'minutes', description: 'postpone: by how many minutes', type: 'integer' },
149
+ { name: 'ext', property: 'ext', description: 'add / update: extension fields JSON (merged on update; null removes a key)', type: 'string' },
150
+ SCOPE,
151
+ ],
152
+ inputSchema: {
153
+ type: 'object',
154
+ properties: {
155
+ action: { type: 'string', enum: ['list', 'add', 'update', 'rm', 'skip', 'postpone'] }, title: { type: 'string' }, id: { type: 'string' }, from: { type: 'string' }, days: { type: 'integer' },
156
+ start: { type: 'string' }, end: { type: 'string' }, new_title: { type: 'string' }, rrule: { type: 'string' }, tz: { type: 'string' }, location: { type: 'string' }, reminder: { type: 'string' },
157
+ minutes: { type: 'integer' }, ext: { type: 'string' }, scope: { type: 'string', enum: ['one', 'following', 'all'] },
158
+ },
159
+ required: ['action'], additionalProperties: false,
160
+ },
161
+ outputSchema: OBJECT_OUTPUT,
162
+ resultSchemaVersion: 1,
163
+ access: { mode: 'fixed', level: 'write' },
164
+ asyncMode: 'sync',
165
+ requiresSession: true,
166
+ examples: [
167
+ 'buckyos aiws cal list --days 14',
168
+ 'buckyos aiws cal add "Stand-up" --start 2026-11-16T09:00:00+08:00 --end 2026-11-16T09:15:00+08:00 --rrule "FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"',
169
+ 'buckyos aiws cal add "Trip" --start 2026-11-20 --end 2026-11-22',
170
+ 'buckyos aiws cal skip --id e…@2026-11-18T01:00:00.000Z',
171
+ 'buckyos aiws cal update --id e…@2026-11-18T01:00:00.000Z --start 2026-11-18T10:00:00+08:00 --end 2026-11-18T10:15:00+08:00 --scope following',
172
+ ],
173
+ handler: (ctx, input) => run(async () => {
174
+ const s = schedule(ctx)
175
+ const action = requiredInputString(input, 'action')
176
+ const tz = viewerTimeZone()
177
+ const scope = (inputString(input, 'scope') ?? 'one') as RecurrenceScope
178
+ const times = (): EventChange['times'] | undefined => {
179
+ const start = inputString(input, 'start'), end = inputString(input, 'end')
180
+ if (!start && !end) return undefined
181
+ if (!start) throw new UsageError('AIWS_USAGE', '--end needs --start')
182
+ if (DATE.test(start)) {
183
+ const last = end ?? start
184
+ if (!DATE.test(last)) throw new UsageError('AIWS_USAGE', 'an all-day event takes dates for --start and --end')
185
+ return { allDay: true, startDate: start, endDate: last }
186
+ }
187
+ const s0 = Date.parse(start)
188
+ const e0 = end ? Date.parse(end) : s0 + 3600_000
189
+ if (!Number.isFinite(s0) || !Number.isFinite(e0)) throw new UsageError('AIWS_USAGE', '--start / --end must be RFC 3339 instants with an offset (or dates for all-day)')
190
+ return { allDay: false, start: new Date(s0).toISOString(), end: new Date(e0).toISOString() }
191
+ }
192
+ switch (action) {
193
+ case 'list': {
194
+ const handle = await s.ensure()
195
+ const from = inputString(input, 'from') ?? localDate(Date.now(), tz)
196
+ if (!DATE.test(from)) throw new UsageError('AIWS_USAGE', '--from must be YYYY-MM-DD')
197
+ const days = typeof input.days === 'number' ? Math.max(1, Math.min(366, input.days)) : 7
198
+ const fromMs = Date.parse(`${from}T00:00:00Z`) - 14 * 3600_000
199
+ const window = { fromMs, toMs: fromMs + days * 86_400_000 + 28 * 3600_000 }
200
+ const rows = await s.rows(handle.calendar)
201
+ const last = localDate(Date.parse(`${from}T12:00:00Z`) + (days - 1) * 86_400_000, 'UTC')
202
+ // only what touches the asked days on this machine's calendar
203
+ const occ = calendarOccurrences(rows, window, { viewerTz: tz }).filter((o) => (o.allDay ? o.endDate! >= from && o.startDate! <= last : localDate(o.endMs!, tz) >= from && localDate(o.startMs!, tz) <= last))
204
+ return { workspace_id: handle.workspace_id, table: handle.calendar, from, days, time_zone: tz, events: occ.map(eventView) }
205
+ }
206
+ case 'add': {
207
+ const title = requiredInputString(input, 'title')
208
+ const t = times()
209
+ if (!t) throw new UsageError('AIWS_USAGE', 'add needs --start')
210
+ const ext: Record<string, unknown> = { ...(parseExt(input) ?? {}) }
211
+ const rrule = inputString(input, 'rrule')
212
+ if (rrule && rrule !== 'none') { ext.rrule = rrule; ext.tz = inputString(input, 'tz') ?? tz }
213
+ const location = inputString(input, 'location')
214
+ if (location) ext.location = location
215
+ const reminder = inputString(input, 'reminder')
216
+ if (reminder) ext.reminders = reminder.split(',').map((m) => ({ before_min: Number(m.trim()) })).filter((r) => Number.isFinite(r.before_min))
217
+ const id = await s.addEvent(t.allDay
218
+ ? { title, all_day: true, start_date: t.startDate, end_date: t.endDate, ext: ext as never }
219
+ : { title, start: t.start, end: t.end, ext: ext as never })
220
+ return { ok: true, id }
221
+ }
222
+ case 'update': {
223
+ const change: EventChange = {}
224
+ const t = times()
225
+ if (t) change.times = t
226
+ const title = inputString(input, 'new_title')
227
+ if (title) change.values = { title }
228
+ const merge: Record<string, unknown> = { ...(parseExt(input) ?? {}) }
229
+ const location = inputString(input, 'location')
230
+ if (location !== undefined && location !== null) merge.location = location || null
231
+ if (Object.keys(merge).length) change.ext_merge = merge as never
232
+ const rrule = inputString(input, 'rrule')
233
+ if (rrule) change.rrule = rrule === 'none' ? null : rrule
234
+ const id = await s.editEvent(requiredInputString(input, 'id'), change, scope)
235
+ return { ok: true, id }
236
+ }
237
+ case 'rm': await s.deleteEvent(requiredInputString(input, 'id'), scope); return { ok: true }
238
+ case 'skip': await s.deleteEvent(requiredInputString(input, 'id'), 'one'); return { ok: true }
239
+ case 'postpone': {
240
+ const minutes = typeof input.minutes === 'number' ? input.minutes : 0
241
+ if (minutes <= 0) throw new UsageError('AIWS_USAGE', 'postpone needs --minutes')
242
+ const { occ } = await s.occurrence(requiredInputString(input, 'id'))
243
+ const change: EventChange = occ.allDay
244
+ ? { times: { allDay: true, startDate: shiftDate(occ.startDate!, Math.max(1, Math.round(minutes / 1440))), endDate: shiftDate(occ.endDate!, Math.max(1, Math.round(minutes / 1440))) } }
245
+ : { times: { allDay: false, start: new Date(occ.startMs! + minutes * 60_000).toISOString(), end: new Date(occ.endMs! + minutes * 60_000).toISOString() } }
246
+ const id = await s.editEvent(requiredInputString(input, 'id'), change, 'one')
247
+ return { ok: true, id }
248
+ }
249
+ default: throw new UsageError('AIWS_USAGE', `cal: unknown action ${action}`)
250
+ }
251
+ }),
252
+ }
253
+
254
+ function shiftDate(date: string, days: number): string {
255
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * 86_400_000).toISOString().slice(0, 10)
256
+ }