buckyos 0.7.177 → 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 (93) 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 +1725 -301
  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/modules/pikg.ts +193 -51
  11. package/cli/runtime/fs_retry.ts +26 -0
  12. package/cli/runtime/host.ts +18 -0
  13. package/cli/runtime/host_deno.ts +51 -2
  14. package/cli/runtime/host_node.ts +48 -3
  15. package/cli/runtime/node_entry.ts +1 -0
  16. package/cli/system_bootstrap.ts +1 -0
  17. package/cli/system_launcher.ts +1 -0
  18. package/cli/version.ts +1 -1
  19. package/dist/aicc_client.d.ts +1 -1
  20. package/dist/aicc_client.d.ts.map +1 -1
  21. package/dist/aiworkspace_client.d.ts +253 -2
  22. package/dist/aiworkspace_client.d.ts.map +1 -1
  23. package/dist/aiws_bind-3b874f77.mjs +2235 -0
  24. package/dist/aiws_bind-3b874f77.mjs.map +1 -0
  25. package/dist/aiws_bind-82bace11.js +2 -0
  26. package/dist/aiws_bind-82bace11.js.map +1 -0
  27. package/dist/aiws_bind.d.ts +233 -0
  28. package/dist/aiws_bind.d.ts.map +1 -0
  29. package/dist/aiws_ext.cjs +1 -1
  30. package/dist/aiws_ext.cjs.map +1 -1
  31. package/dist/aiws_ext.d.ts +9 -5
  32. package/dist/aiws_ext.d.ts.map +1 -1
  33. package/dist/aiws_ext.mjs +146 -11
  34. package/dist/aiws_ext.mjs.map +1 -1
  35. package/dist/aiws_rrule.d.ts +121 -0
  36. package/dist/aiws_rrule.d.ts.map +1 -0
  37. package/dist/aiws_schedule.d.ts +324 -0
  38. package/dist/aiws_schedule.d.ts.map +1 -0
  39. package/dist/aiws_write-89b5cc2a.js +13 -0
  40. package/dist/aiws_write-89b5cc2a.js.map +1 -0
  41. package/dist/{executor_client-bfc8a1e1.mjs → aiws_write-c2de498e.mjs} +724 -285
  42. package/dist/aiws_write-c2de498e.mjs.map +1 -0
  43. package/dist/aiws_write.d.ts +178 -0
  44. package/dist/aiws_write.d.ts.map +1 -0
  45. package/dist/app-frame.cjs +1 -1
  46. package/dist/app-frame.cjs.map +1 -1
  47. package/dist/app-frame.d.ts +1 -0
  48. package/dist/app-frame.d.ts.map +1 -1
  49. package/dist/app-frame.mjs +6 -2
  50. package/dist/app-frame.mjs.map +1 -1
  51. package/dist/browser.cjs +1 -1
  52. package/dist/browser.cjs.map +1 -1
  53. package/dist/browser.d.ts +4 -0
  54. package/dist/browser.d.ts.map +1 -1
  55. package/dist/browser.mjs +112 -21
  56. package/dist/browser.mjs.map +1 -1
  57. package/dist/{content_objid-9232bcaf.mjs → content_objid-a2cafba9.mjs} +2 -2
  58. package/dist/{content_objid-9232bcaf.mjs.map → content_objid-a2cafba9.mjs.map} +1 -1
  59. package/dist/content_objid-dff803ff.js +2 -0
  60. package/dist/{content_objid-1aff74b6.js.map → content_objid-dff803ff.js.map} +1 -1
  61. package/dist/{did_object_client-7fa36f90.mjs → did_object_client-cb2f9aba.mjs} +2 -2
  62. package/dist/{did_object_client-7fa36f90.mjs.map → did_object_client-cb2f9aba.mjs.map} +1 -1
  63. package/dist/executor_client.d.ts +1 -1
  64. package/dist/executor_client.d.ts.map +1 -1
  65. package/dist/index.cjs +1 -1
  66. package/dist/index.cjs.map +1 -1
  67. package/dist/index.d.ts +4 -0
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.mjs +113 -22
  70. package/dist/index.mjs.map +1 -1
  71. package/dist/nfsp.cjs.map +1 -1
  72. package/dist/nfsp.d.ts +2 -1
  73. package/dist/nfsp.d.ts.map +1 -1
  74. package/dist/nfsp.mjs.map +1 -1
  75. package/dist/node.cjs +1 -1
  76. package/dist/node.cjs.map +1 -1
  77. package/dist/node.d.ts +5 -0
  78. package/dist/node.d.ts.map +1 -1
  79. package/dist/node.mjs +99 -6
  80. package/dist/node.mjs.map +1 -1
  81. package/dist/{object_url-f72c1704.mjs → object_url-376c5222.mjs} +4 -4
  82. package/dist/{object_url-f72c1704.mjs.map → object_url-376c5222.mjs.map} +1 -1
  83. package/dist/provision.cjs +1 -1
  84. package/dist/provision.cjs.map +1 -1
  85. package/dist/provision.mjs +48 -16
  86. package/dist/provision.mjs.map +1 -1
  87. package/dist/provision_activate.d.ts.map +1 -1
  88. package/dist/xllm.mjs +2 -2
  89. package/package.json +5 -4
  90. package/dist/content_objid-1aff74b6.js +0 -2
  91. package/dist/executor_client-7ce0ddc7.js +0 -13
  92. package/dist/executor_client-7ce0ddc7.js.map +0 -1
  93. package/dist/executor_client-bfc8a1e1.mjs.map +0 -1
package/cli/dist/cli.mjs CHANGED
@@ -2,11 +2,12 @@ import process from "node:process";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import * as nodePath from "node:path";
4
4
  import { resolve as resolve$5, dirname as dirname$3 } from "node:path";
5
- import { BuckyOSSDK, RuntimeType, buckyos, namelib, VerifyHubClient, createAppInstanceId, parseSessionTokenClaims, ndn, verifyBundle, controlSkeleton, aiwsContentDigest, AIWS_MANIFEST_VERSION, AIWS_MANIFEST_FILE, taskMgrTaskEventPath, ndm_proxy, objectUrl as objectUrl$1, ExecutorCommandStream, watchControl, buildControl, pullControl, exportBundle, NfspClient, AiwsSourceError, packBuildFiles, templateDir, isSourcePath } from "buckyos/node";
5
+ import { BuckyOSSDK, RuntimeType, buckyos, namelib, VerifyHubClient, createAppInstanceId, parseSessionTokenClaims, ndn, verifyBundle, controlSkeleton, aiwsContentDigest, AIWS_MANIFEST_VERSION, AIWS_MANIFEST_FILE, taskMgrTaskEventPath, ndm_proxy, objectUrl as objectUrl$1, ExecutorCommandStream, AiwsFailure, viewerTimeZone, localDate, calendarOccurrences, ScheduleClient, resolveBindings, noUiDialogs, createOps, orderKeyBetween, bindingsPayload, AIWS_PROTOCOL_VERSION, BindFailure, aiwsTarget, watchControl, buildControl, pullControl, exportBundle, tableDelete, optionAdd, fieldAdd, tableSet, tableInsert, textAppend, textDeleteBlocks, textReplaceBlock, move, rename, setProps, NfspClient, AiwsSourceError, packBuildFiles, commitOps, templateDir, isSourcePath } from "buckyos/node";
6
6
  import * as provisionSdk from "buckyos/provision";
7
+ import { AiccLlmClient, LLMComputeException, providerErrorFromRpc } from "buckyos/xllm";
7
8
  import { createHash } from "node:crypto";
8
- import { readFile, writeFile, readdir, stat, lstat, realpath, mkdtemp, rename, rm, mkdir, chmod, symlink, copyFile, open } from "node:fs/promises";
9
- import { createReadStream, createWriteStream } from "node:fs";
9
+ import { readFile, writeFile, readdir, stat, lstat, realpath, mkdtemp, rename as rename$1, rm, mkdir, chmod, symlink, copyFile, open } from "node:fs/promises";
10
+ import { createReadStream, createWriteStream, existsSync } from "node:fs";
10
11
  import { tmpdir } from "node:os";
11
12
  import { spawn } from "node:child_process";
12
13
  import { createInterface } from "node:readline/promises";
@@ -541,7 +542,7 @@ function buildDistributionPolicy(options) {
541
542
  for (const candidate of parsed.writeParents) {
542
543
  writePaths.add(path.dirname(resolveInputPath(candidate, cwd, path)));
543
544
  }
544
- const subprocesses = parsed.module === "pikg" && ["init", "build"].includes(parsed.verb ?? "") ? ["docker"] : [];
545
+ const subprocesses = parsed.module === "pikg" && ["init", "build"].includes(parsed.verb ?? "") ? ["docker"] : parsed.module === "aiws" && ["run-exec", "run-program"].includes(parsed.verb ?? "") && options.runtimeExecutable ? [options.runtimeExecutable] : [];
545
546
  const network = parsed.module !== void 0 && !["pikg", "command", "completion", "config", "provision"].includes(parsed.module);
546
547
  const allowedEnvironment = options.distribution === "developer" ? TOOL_ENVIRONMENT_NAMES.filter((name) => name !== "BUCKYOS_ROOT") : TOOL_ENVIRONMENT_NAMES;
547
548
  return Object.freeze({
@@ -2520,7 +2521,7 @@ function replPrompt(config) {
2520
2521
  return `buckyos[${profile}|${zone}|${identity}]> `;
2521
2522
  }
2522
2523
  const EMPTY_INPUT$3 = { type: "object", properties: {}, additionalProperties: false };
2523
- const OBJECT_OUTPUT$h = { type: "object", additionalProperties: true };
2524
+ const OBJECT_OUTPUT$j = { type: "object", additionalProperties: true };
2524
2525
  function createAuthModule() {
2525
2526
  return {
2526
2527
  name: "auth",
@@ -2530,7 +2531,7 @@ function createAuthModule() {
2530
2531
  verb: "whoami",
2531
2532
  summary: "Show the effective principal and application identity",
2532
2533
  inputSchema: EMPTY_INPUT$3,
2533
- outputSchema: OBJECT_OUTPUT$h,
2534
+ outputSchema: OBJECT_OUTPUT$j,
2534
2535
  resultSchemaVersion: 1,
2535
2536
  access: { mode: "fixed", level: "read" },
2536
2537
  asyncMode: "sync",
@@ -2548,7 +2549,7 @@ function createAuthModule() {
2548
2549
  verb: "session-status",
2549
2550
  summary: "Show the in-memory session state without exposing credentials",
2550
2551
  inputSchema: EMPTY_INPUT$3,
2551
- outputSchema: OBJECT_OUTPUT$h,
2552
+ outputSchema: OBJECT_OUTPUT$j,
2552
2553
  resultSchemaVersion: 1,
2553
2554
  access: { mode: "fixed", level: "read" },
2554
2555
  asyncMode: "sync",
@@ -2569,7 +2570,7 @@ const EMPTY_INPUT$2 = {
2569
2570
  properties: {},
2570
2571
  additionalProperties: false
2571
2572
  };
2572
- const OBJECT_OUTPUT$g = { type: "object", additionalProperties: true };
2573
+ const OBJECT_OUTPUT$i = { type: "object", additionalProperties: true };
2573
2574
  function createCoreModules(registry) {
2574
2575
  return [createCommandModule(registry), createConfigModule(), createCompletionModule(registry)];
2575
2576
  }
@@ -2582,7 +2583,7 @@ function createCommandModule(registry) {
2582
2583
  verb: "list",
2583
2584
  summary: "List registered modules and commands",
2584
2585
  inputSchema: EMPTY_INPUT$2,
2585
- outputSchema: OBJECT_OUTPUT$g,
2586
+ outputSchema: OBJECT_OUTPUT$i,
2586
2587
  resultSchemaVersion: 1,
2587
2588
  access: { mode: "fixed", level: "read" },
2588
2589
  asyncMode: "sync",
@@ -2615,7 +2616,7 @@ function createCommandModule(registry) {
2615
2616
  required: ["target_module", "target_verb"],
2616
2617
  additionalProperties: false
2617
2618
  },
2618
- outputSchema: OBJECT_OUTPUT$g,
2619
+ outputSchema: OBJECT_OUTPUT$i,
2619
2620
  resultSchemaVersion: 1,
2620
2621
  access: { mode: "fixed", level: "read" },
2621
2622
  asyncMode: "sync",
@@ -2637,7 +2638,7 @@ function createConfigModule() {
2637
2638
  verb: "list",
2638
2639
  summary: "List the global configuration and available profiles",
2639
2640
  inputSchema: EMPTY_INPUT$2,
2640
- outputSchema: OBJECT_OUTPUT$g,
2641
+ outputSchema: OBJECT_OUTPUT$i,
2641
2642
  resultSchemaVersion: 1,
2642
2643
  access: { mode: "fixed", level: "read" },
2643
2644
  asyncMode: "sync",
@@ -2668,7 +2669,7 @@ function createConfigModule() {
2668
2669
  },
2669
2670
  additionalProperties: false
2670
2671
  },
2671
- outputSchema: OBJECT_OUTPUT$g,
2672
+ outputSchema: OBJECT_OUTPUT$i,
2672
2673
  resultSchemaVersion: 1,
2673
2674
  access: { mode: "fixed", level: "read" },
2674
2675
  asyncMode: "sync",
@@ -2714,7 +2715,7 @@ function createConfigModule() {
2714
2715
  required: ["key", "value"],
2715
2716
  additionalProperties: false
2716
2717
  },
2717
- outputSchema: OBJECT_OUTPUT$g,
2718
+ outputSchema: OBJECT_OUTPUT$i,
2718
2719
  resultSchemaVersion: 1,
2719
2720
  access: { mode: "fixed", level: "write" },
2720
2721
  asyncMode: "sync",
@@ -2754,7 +2755,7 @@ function createConfigModule() {
2754
2755
  required: ["profile_name"],
2755
2756
  additionalProperties: false
2756
2757
  },
2757
- outputSchema: OBJECT_OUTPUT$g,
2758
+ outputSchema: OBJECT_OUTPUT$i,
2758
2759
  resultSchemaVersion: 1,
2759
2760
  access: { mode: "fixed", level: "write" },
2760
2761
  asyncMode: "sync",
@@ -2786,7 +2787,7 @@ function createConfigModule() {
2786
2787
  properties: { effective: { type: "boolean" } },
2787
2788
  additionalProperties: false
2788
2789
  },
2789
- outputSchema: OBJECT_OUTPUT$g,
2790
+ outputSchema: OBJECT_OUTPUT$i,
2790
2791
  resultSchemaVersion: 1,
2791
2792
  access: { mode: "fixed", level: "read" },
2792
2793
  asyncMode: "sync",
@@ -3028,7 +3029,7 @@ async function buckyosInfo(ctx) {
3028
3029
  );
3029
3030
  }
3030
3031
  const SERVICE_NAME = "system_config";
3031
- const OBJECT_OUTPUT$f = { type: "object", additionalProperties: false };
3032
+ const OBJECT_OUTPUT$h = { type: "object", additionalProperties: false };
3032
3033
  const KEY_INPUT = {
3033
3034
  type: "object",
3034
3035
  properties: { key: { type: "string", minLength: 1 } },
@@ -3046,7 +3047,7 @@ function createSystemConfigModule() {
3046
3047
  positionals: [{ name: "key", description: "System-config key" }],
3047
3048
  inputSchema: KEY_INPUT,
3048
3049
  outputSchema: {
3049
- ...OBJECT_OUTPUT$f,
3050
+ ...OBJECT_OUTPUT$h,
3050
3051
  properties: {
3051
3052
  key: { type: "string" },
3052
3053
  value: { type: "string" },
@@ -3089,7 +3090,7 @@ function createSystemConfigModule() {
3089
3090
  additionalProperties: false
3090
3091
  },
3091
3092
  outputSchema: {
3092
- ...OBJECT_OUTPUT$f,
3093
+ ...OBJECT_OUTPUT$h,
3093
3094
  properties: {
3094
3095
  key: { type: "string" },
3095
3096
  items: { type: "array", items: { type: "string" } }
@@ -3143,7 +3144,7 @@ function setCommand() {
3143
3144
  additionalProperties: false
3144
3145
  },
3145
3146
  outputSchema: {
3146
- ...OBJECT_OUTPUT$f,
3147
+ ...OBJECT_OUTPUT$h,
3147
3148
  properties: { key: { type: "string" }, updated: { type: "boolean" } },
3148
3149
  required: ["key", "updated"]
3149
3150
  },
@@ -3182,7 +3183,7 @@ function setFileCommand() {
3182
3183
  additionalProperties: false
3183
3184
  },
3184
3185
  outputSchema: {
3185
- ...OBJECT_OUTPUT$f,
3186
+ ...OBJECT_OUTPUT$h,
3186
3187
  properties: { key: { type: "string" }, updated: { type: "boolean" } },
3187
3188
  required: ["key", "updated"]
3188
3189
  },
@@ -3219,7 +3220,7 @@ function mutationCommand(options) {
3219
3220
  additionalProperties: false
3220
3221
  },
3221
3222
  outputSchema: {
3222
- ...OBJECT_OUTPUT$f,
3223
+ ...OBJECT_OUTPUT$h,
3223
3224
  properties: {
3224
3225
  key: { type: "string" },
3225
3226
  [options.resultProperty]: { type: "boolean" }
@@ -5531,13 +5532,13 @@ function stableJsonDigest(value) {
5531
5532
  function validateContentHandlers(value, permissions) {
5532
5533
  if (!Array.isArray(value))
5533
5534
  throw invalid("appdoc", "content_handlers must be an array");
5534
- const ids = /* @__PURE__ */ new Set();
5535
+ const ids2 = /* @__PURE__ */ new Set();
5535
5536
  for (const raw of value) {
5536
5537
  const h = expectObject$3(raw, "content handler");
5537
5538
  const id = expectNonEmptyString(h.handler_id, "handler_id");
5538
- if (!/^[a-zA-Z0-9_-]+$/.test(id) || ids.has(id))
5539
+ if (!/^[a-zA-Z0-9_-]+$/.test(id) || ids2.has(id))
5539
5540
  throw invalid("appdoc", "invalid or duplicate handler_id");
5540
- ids.add(id);
5541
+ ids2.add(id);
5541
5542
  if (!Number.isSafeInteger(h.version) || Number(h.version) < 1)
5542
5543
  throw invalid("appdoc", "invalid handler version");
5543
5544
  if (!Array.isArray(h.selectors) || !h.selectors.length)
@@ -6114,7 +6115,7 @@ async function readSkillDirectory(root, limit) {
6114
6115
  await walk(realRoot, "");
6115
6116
  return { files, ignored };
6116
6117
  }
6117
- const PACKAGE_VERSION = "0.7.177";
6118
+ const PACKAGE_VERSION = "0.7.183";
6118
6119
  const TOOL_VERSION = PACKAGE_VERSION;
6119
6120
  const SDK_VERSION = PACKAGE_VERSION;
6120
6121
  const PROTOCOL_VERSION = "1";
@@ -6131,7 +6132,7 @@ const VERSION$1 = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
6131
6132
  const SHA256_ID = /^sha256:[0-9a-f]{64}$/;
6132
6133
  const OBJECT_ID = /^(?:appdoc|pkg):[0-9a-f]{64}$/;
6133
6134
  const SAFE_GENERATED_FILE = /^[A-Za-z0-9._-]+$/;
6134
- const OBJECT_OUTPUT$e = { type: "object", additionalProperties: true };
6135
+ const OBJECT_OUTPUT$g = { type: "object", additionalProperties: true };
6135
6136
  const APP_KINDS = ["static-web", "script", "docker", "agent-skills", "aiws-controls", "ext-tools"];
6136
6137
  const PATH_KINDS = {
6137
6138
  "static-web": { key: "web", category: "web", selectorType: "static" },
@@ -6189,7 +6190,7 @@ function createPikgModule(dependencies = {}) {
6189
6190
  },
6190
6191
  additionalProperties: false
6191
6192
  },
6192
- outputSchema: OBJECT_OUTPUT$e,
6193
+ outputSchema: OBJECT_OUTPUT$g,
6193
6194
  resultSchemaVersion: 1,
6194
6195
  access: { mode: "fixed", level: "read" },
6195
6196
  asyncMode: "sync",
@@ -6246,7 +6247,7 @@ function createPikgModule(dependencies = {}) {
6246
6247
  },
6247
6248
  additionalProperties: false
6248
6249
  },
6249
- outputSchema: OBJECT_OUTPUT$e,
6250
+ outputSchema: OBJECT_OUTPUT$g,
6250
6251
  resultSchemaVersion: 1,
6251
6252
  access: { mode: "fixed", level: "write" },
6252
6253
  asyncMode: "sync",
@@ -6274,7 +6275,7 @@ function createPikgModule(dependencies = {}) {
6274
6275
  properties: { meta_dir: { type: "string", minLength: 1 } },
6275
6276
  additionalProperties: false
6276
6277
  },
6277
- outputSchema: OBJECT_OUTPUT$e,
6278
+ outputSchema: OBJECT_OUTPUT$g,
6278
6279
  resultSchemaVersion: 1,
6279
6280
  access: { mode: "fixed", level: "write" },
6280
6281
  asyncMode: "sync",
@@ -6295,7 +6296,7 @@ function createPikgModule(dependencies = {}) {
6295
6296
  properties: { dist_dir: { type: "string", minLength: 1 } },
6296
6297
  additionalProperties: false
6297
6298
  },
6298
- outputSchema: OBJECT_OUTPUT$e,
6299
+ outputSchema: OBJECT_OUTPUT$g,
6299
6300
  resultSchemaVersion: 1,
6300
6301
  access: { mode: "fixed", level: "write" },
6301
6302
  asyncMode: "sync",
@@ -6315,7 +6316,7 @@ function createPikgModule(dependencies = {}) {
6315
6316
  required: ["pikg_path"],
6316
6317
  additionalProperties: false
6317
6318
  },
6318
- outputSchema: OBJECT_OUTPUT$e,
6319
+ outputSchema: OBJECT_OUTPUT$g,
6319
6320
  resultSchemaVersion: 1,
6320
6321
  access: { mode: "fixed", level: "read" },
6321
6322
  asyncMode: "sync",
@@ -6336,7 +6337,7 @@ function createPikgModule(dependencies = {}) {
6336
6337
  properties: { meta_dir: { type: "string", minLength: 1 } },
6337
6338
  additionalProperties: false
6338
6339
  },
6339
- outputSchema: OBJECT_OUTPUT$e,
6340
+ outputSchema: OBJECT_OUTPUT$g,
6340
6341
  resultSchemaVersion: 1,
6341
6342
  access: { mode: "fixed", level: "destructive" },
6342
6343
  asyncMode: "sync",
@@ -6423,7 +6424,14 @@ async function doctorCommand(ctx, input) {
6423
6424
  }
6424
6425
  if (app.categories[0] === PATH_KINDS["ext-tools"].category) {
6425
6426
  const catalog2 = optionalInputString(input, "catalog");
6426
- checks.push(...await extToolsChecks(app, pikg, metaDir, catalog2 ? resolveFromCwd$1(ctx, catalog2) : void 0));
6427
+ checks.push(
6428
+ ...await extToolsChecks(
6429
+ app,
6430
+ pikg,
6431
+ metaDir,
6432
+ catalog2 ? resolveFromCwd$1(ctx, catalog2) : void 0
6433
+ )
6434
+ );
6427
6435
  }
6428
6436
  } catch (error) {
6429
6437
  checks.push({
@@ -6496,9 +6504,15 @@ async function initCommand(ctx, input, docker) {
6496
6504
  selector = platform.selector;
6497
6505
  sourceValue = {
6498
6506
  type: "path",
6499
- path: toPortablePath(relative(join(projectDir, "dapp_meta"), join(absoluteSource, "payload", platform.name)))
6507
+ path: toPortablePath(
6508
+ relative(join(projectDir, "dapp_meta"), join(absoluteSource, "payload", platform.name))
6509
+ )
6510
+ };
6511
+ sourceSummary2 = {
6512
+ type: "path",
6513
+ path: displaySource(projectDir, absoluteSource),
6514
+ platform: platform.name
6500
6515
  };
6501
- sourceSummary2 = { type: "path", path: displaySource(projectDir, absoluteSource), platform: platform.name };
6502
6516
  try {
6503
6517
  await getHost().lstat(join(absoluteSource, EXT_TOOLS_MANIFEST_FILE));
6504
6518
  } catch (error) {
@@ -6608,14 +6622,18 @@ async function skillLintCheck(packageName, source) {
6608
6622
  } else {
6609
6623
  files = /* @__PURE__ */ new Map();
6610
6624
  for (const entry of await readTarGz(await getHost().readFile(source), MAX_SKILL_SOURCE_BYTES)) {
6611
- if (SKILL_DIRS.includes(entry.path.split("/")[0]))
6625
+ if (SKILL_DIRS.includes(entry.path.split("/")[0])) {
6612
6626
  files.set(entry.path, { bytes: entry.bytes });
6613
- else
6627
+ } else
6614
6628
  ignored.push(entry.path);
6615
6629
  }
6616
6630
  }
6617
6631
  } catch (error) {
6618
- return { ...check, status: "error", detail: error instanceof Error ? error.message : String(error) };
6632
+ return {
6633
+ ...check,
6634
+ status: "error",
6635
+ detail: error instanceof Error ? error.message : String(error)
6636
+ };
6619
6637
  }
6620
6638
  const { skills, findings } = lintSkillPackage(packageName, files);
6621
6639
  const errors = findings.filter((finding) => finding.level === "error");
@@ -6624,7 +6642,13 @@ async function skillLintCheck(packageName, source) {
6624
6642
  status: errors.length ? "error" : "ok",
6625
6643
  ...errors.length ? { detail: errors.map((finding) => finding.note).join("; "), errors } : {},
6626
6644
  ...errors.length ? {} : { digest: skillContentDigest(files) },
6627
- skills: skills.map(({ kind, name, scope, size, commands }) => ({ kind, name, scope, size, commands })),
6645
+ skills: skills.map(({ kind, name, scope, size, commands }) => ({
6646
+ kind,
6647
+ name,
6648
+ scope,
6649
+ size,
6650
+ commands
6651
+ })),
6628
6652
  warnings: findings.filter((finding) => finding.level !== "error"),
6629
6653
  ...ignored.length ? { ignored_files: ignored } : {}
6630
6654
  };
@@ -6660,14 +6684,27 @@ async function writeAiwsSkeleton(dir, ownerDid, name, composite) {
6660
6684
  const encoder = new TextEncoder();
6661
6685
  const host2 = getHost();
6662
6686
  await host2.mkdir(join(dir, "controls", name), { recursive: true });
6663
- for (const [file, text2] of Object.entries(files))
6687
+ for (const [file, text2] of Object.entries(files)) {
6664
6688
  await host2.writeTextFile(join(dir, "controls", name, file), text2);
6665
- const digest = await aiwsContentDigest(Object.entries(files).map(([file, text2]) => [file, encoder.encode(text2)]));
6689
+ }
6690
+ const digest = await aiwsContentDigest(
6691
+ Object.entries(files).map(
6692
+ ([file, text2]) => [file, encoder.encode(text2)]
6693
+ )
6694
+ );
6666
6695
  const manifest = {
6667
6696
  manifest_version: AIWS_MANIFEST_VERSION,
6668
6697
  purpose: "aiws",
6669
6698
  host_api: composite ? {} : { declarative: 1 },
6670
- controls: [{ ident: `${ownerDid}#${name}`, name, kind, version: 1, digest, dir: `controls/${name}/`, title: name }],
6699
+ controls: [{
6700
+ ident: `${ownerDid}#${name}`,
6701
+ name,
6702
+ kind,
6703
+ version: 1,
6704
+ digest,
6705
+ dir: `controls/${name}/`,
6706
+ title: name
6707
+ }],
6671
6708
  workspace_templates: []
6672
6709
  };
6673
6710
  await host2.writeTextFile(join(dir, AIWS_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}
@@ -6677,9 +6714,14 @@ function hostExtToolsPlatform() {
6677
6714
  const host2 = getHost();
6678
6715
  const os = host2.platform === "darwin" ? "macos" : host2.platform === "win32" ? "windows" : host2.platform;
6679
6716
  const arch = normalizeArch$1(host2.arch);
6680
- const platform = EXT_TOOLS_PLATFORMS.find((known) => known.selector.os === os && known.selector.arch === arch);
6717
+ const platform = EXT_TOOLS_PLATFORMS.find(
6718
+ (known) => known.selector.os === os && known.selector.arch === arch
6719
+ );
6681
6720
  if (!platform) {
6682
- throw new UsageError("UNSUPPORTED_PLATFORM", `extension packages have no payload for ${os}/${arch}`);
6721
+ throw new UsageError(
6722
+ "UNSUPPORTED_PLATFORM",
6723
+ `extension packages have no payload for ${os}/${arch}`
6724
+ );
6683
6725
  }
6684
6726
  return platform;
6685
6727
  }
@@ -6699,8 +6741,9 @@ async function writeExtToolsSkeleton(dir, id, version, platform) {
6699
6741
  const text2 = `${JSON.stringify(manifest, null, 2)}
6700
6742
  `;
6701
6743
  const payload = join(dir, "payload", platform);
6702
- for (const sub of ["bin", "smoke", join("store", id)])
6744
+ for (const sub of ["bin", "smoke", join("store", id)]) {
6703
6745
  await host2.mkdir(join(payload, sub), { recursive: true });
6746
+ }
6704
6747
  await host2.writeTextFile(join(dir, EXT_TOOLS_MANIFEST_FILE), text2);
6705
6748
  await host2.writeTextFile(join(payload, EXT_TOOLS_MANIFEST_FILE), text2);
6706
6749
  const windows = platform.startsWith("windows-");
@@ -6750,7 +6793,11 @@ async function readExtToolsManifestFile(path) {
6750
6793
  }
6751
6794
  async function readExtToolsPayloadTree(root) {
6752
6795
  const host2 = getHost();
6753
- const tree = { files: /* @__PURE__ */ new Map(), directories: /* @__PURE__ */ new Set(), launchers: /* @__PURE__ */ new Map() };
6796
+ const tree = {
6797
+ files: /* @__PURE__ */ new Map(),
6798
+ directories: /* @__PURE__ */ new Set(),
6799
+ launchers: /* @__PURE__ */ new Map()
6800
+ };
6754
6801
  const errors = [];
6755
6802
  const realRoot = await host2.realPath(root);
6756
6803
  const walk = async (directory, prefix) => {
@@ -6764,7 +6811,9 @@ async function readExtToolsPayloadTree(root) {
6764
6811
  try {
6765
6812
  physical = await host2.realPath(path);
6766
6813
  } catch (error) {
6767
- errors.push(`${archivePath}: ${isHostError(error, "NotFound") ? "a dangling symlink" : "a symlink out of the payload"}`);
6814
+ errors.push(
6815
+ `${archivePath}: ${isHostError(error, "NotFound") ? "a dangling symlink" : "a symlink out of the payload"}`
6816
+ );
6768
6817
  continue;
6769
6818
  }
6770
6819
  const inside = relative(realRoot, physical);
@@ -6806,20 +6855,27 @@ async function extToolsChecks(app, pikg, metaDir, catalogDir) {
6806
6855
  const source = sources.length > 0 ? dirname(dirname(sources[0])) : dirname(metaDir);
6807
6856
  const master = await readExtToolsManifestFile(join(source, EXT_TOOLS_MANIFEST_FILE));
6808
6857
  const manifestErrors = [...master.errors];
6809
- if (stray.length > 0)
6810
- manifestErrors.push(`sub packages must be ext_tools_<os>_<arch> from a directory: ${stray.join(", ")}`);
6858
+ if (stray.length > 0) {
6859
+ manifestErrors.push(
6860
+ `sub packages must be ext_tools_<os>_<arch> from a directory: ${stray.join(", ")}`
6861
+ );
6862
+ }
6811
6863
  const manifest = master.manifest;
6812
6864
  if (manifest) {
6813
- if (manifest.id !== app.name)
6865
+ if (manifest.id !== app.name) {
6814
6866
  manifestErrors.push(`id ${manifest.id} is not the App name ${app.name}`);
6815
- if (manifest.version !== app.version)
6867
+ }
6868
+ if (manifest.version !== app.version) {
6816
6869
  manifestErrors.push(`version ${manifest.version} is not the App version ${app.version}`);
6870
+ }
6817
6871
  const without = manifest.platforms.filter((name) => !platforms.has(name));
6818
- if (without.length > 0)
6872
+ if (without.length > 0) {
6819
6873
  manifestErrors.push(`platforms without a sub package: ${without.join(", ")}`);
6874
+ }
6820
6875
  const unlisted = [...platforms.keys()].filter((name) => !manifest.platforms.includes(name));
6821
- if (unlisted.length > 0)
6876
+ if (unlisted.length > 0) {
6822
6877
  manifestErrors.push(`sub packages of platforms it does not list: ${unlisted.join(", ")}`);
6878
+ }
6823
6879
  }
6824
6880
  checks.push({
6825
6881
  name: "ext_tools_manifest",
@@ -6835,10 +6891,11 @@ async function extToolsChecks(app, pikg, metaDir, catalogDir) {
6835
6891
  const { tree, errors: walkErrors } = await readExtToolsPayloadTree(dir);
6836
6892
  errors.push(...walkErrors);
6837
6893
  const copy = await readExtToolsManifestFile(join(dir, EXT_TOOLS_MANIFEST_FILE));
6838
- if (copy.errors.length > 0)
6894
+ if (copy.errors.length > 0) {
6839
6895
  errors.push(`${EXT_TOOLS_MANIFEST_FILE}: ${copy.errors.join("; ")}`);
6840
- else if (copy.text !== master.text)
6896
+ } else if (copy.text !== master.text) {
6841
6897
  errors.push(`${EXT_TOOLS_MANIFEST_FILE}: differs from the package's manifest`);
6898
+ }
6842
6899
  errors.push(...extToolsPayloadErrors(manifest, platform, tree, [source, metaDir]));
6843
6900
  } catch (error) {
6844
6901
  if (!isHostError(error, "NotFound"))
@@ -6866,13 +6923,16 @@ async function extToolsChecks(app, pikg, metaDir, catalogDir) {
6866
6923
  for (const entry of await getHost().readDir(catalogDir)) {
6867
6924
  if (entry.isFile)
6868
6925
  continue;
6869
- const candidate = await readExtToolsManifestFile(join(catalogDir, entry.name, EXT_TOOLS_MANIFEST_FILE));
6926
+ const candidate = await readExtToolsManifestFile(
6927
+ join(catalogDir, entry.name, EXT_TOOLS_MANIFEST_FILE)
6928
+ );
6870
6929
  if (candidate.errors.includes("not found"))
6871
6930
  continue;
6872
6931
  if (!candidate.manifest)
6873
6932
  catalogErrors.push(`${entry.name}: ${candidate.errors.join("; ")}`);
6874
- else if (candidate.manifest.id !== manifest.id)
6933
+ else if (candidate.manifest.id !== manifest.id) {
6875
6934
  others.set(candidate.manifest.id, candidate.manifest);
6935
+ }
6876
6936
  }
6877
6937
  for (const required of manifest.requires) {
6878
6938
  if (!others.has(required.id))
@@ -6882,9 +6942,14 @@ async function extToolsChecks(app, pikg, metaDir, catalogDir) {
6882
6942
  for (const other of others.values()) {
6883
6943
  if (manifest.conflicts.includes(other.id) || other.conflicts.includes(manifest.id))
6884
6944
  continue;
6885
- const shared = other.provides.map((provided) => provided.command).filter((command2) => commands.has(command2));
6886
- if (shared.length > 0)
6887
- catalogErrors.push(`${other.id} also provides ${shared.join(", ")}: one of the two must list the other in conflicts`);
6945
+ const shared = other.provides.map((provided) => provided.command).filter(
6946
+ (command2) => commands.has(command2)
6947
+ );
6948
+ if (shared.length > 0) {
6949
+ catalogErrors.push(
6950
+ `${other.id} also provides ${shared.join(", ")}: one of the two must list the other in conflicts`
6951
+ );
6952
+ }
6888
6953
  }
6889
6954
  checks.push({
6890
6955
  name: "ext_tools_catalog",
@@ -7257,7 +7322,11 @@ function parseAppMeta(value) {
7257
7322
  },
7258
7323
  categories,
7259
7324
  permissions,
7260
- ...value.content_handlers === void 0 ? {} : { content_handlers: developmentValidation(() => validateContentHandlers(value.content_handlers, permissions)) },
7325
+ ...value.content_handlers === void 0 ? {} : {
7326
+ content_handlers: developmentValidation(
7327
+ () => validateContentHandlers(value.content_handlers, permissions)
7328
+ )
7329
+ },
7261
7330
  selector_type: developmentString(value.selector_type, "app.json.selector_type"),
7262
7331
  service_config_tips: serviceConfig
7263
7332
  };
@@ -7483,18 +7552,26 @@ function assertSafeCleanTarget(ctx, metaDir, distDir, sourcePaths) {
7483
7552
  throw new ToolError("UNSAFE_CLEAN_TARGET", "refusing to clean an unsafe output directory");
7484
7553
  }
7485
7554
  }
7486
- async function replaceDirectory(temporary, destination) {
7487
- let exists = false;
7555
+ async function pathExists(path) {
7488
7556
  try {
7489
- await getHost().lstat(destination);
7490
- exists = true;
7557
+ await getHost().lstat(path);
7558
+ return true;
7491
7559
  } catch (error) {
7492
- if (!isHostError(error, "NotFound"))
7493
- throw error;
7560
+ if (isHostError(error, "NotFound"))
7561
+ return false;
7562
+ throw error;
7494
7563
  }
7495
- if (!exists) {
7496
- await getHost().rename(temporary, destination);
7497
- return;
7564
+ }
7565
+ async function replaceDirectory(temporary, destination) {
7566
+ if (!await pathExists(destination)) {
7567
+ try {
7568
+ await getHost().rename(temporary, destination);
7569
+ return;
7570
+ } catch (error) {
7571
+ if (getHost().platform !== "windows" || !isHostError(error, "PermissionDenied") || !await pathExists(destination)) {
7572
+ throw error;
7573
+ }
7574
+ }
7498
7575
  }
7499
7576
  const backup = `${destination}.previous-${crypto.randomUUID()}`;
7500
7577
  await getHost().rename(destination, backup);
@@ -7938,7 +8015,7 @@ const CONTROL_PANEL_SERVICE = "control-panel";
7938
8015
  const PLAN_SCHEMA_VERSION = 4;
7939
8016
  const STAGING_RELEASE_TIMEOUT_MS = 5e3;
7940
8017
  const ZIP_LOCAL_MAGIC = [80, 75, 3, 4];
7941
- const OBJECT_OUTPUT$d = { type: "object", additionalProperties: true };
8018
+ const OBJECT_OUTPUT$f = { type: "object", additionalProperties: true };
7942
8019
  const INSTALL_POLICIES = [
7943
8020
  "strict-public",
7944
8021
  "normal",
@@ -7989,7 +8066,7 @@ function cancelCommand$1() {
7989
8066
  required: ["task_id"],
7990
8067
  additionalProperties: false
7991
8068
  },
7992
- outputSchema: OBJECT_OUTPUT$d,
8069
+ outputSchema: OBJECT_OUTPUT$f,
7993
8070
  resultSchemaVersion: 1,
7994
8071
  access: { mode: "fixed", level: "write" },
7995
8072
  asyncMode: "sync",
@@ -8024,7 +8101,7 @@ function fetchCommand(dependencies) {
8024
8101
  target: { type: "object", additionalProperties: true },
8025
8102
  install_params: { type: "object", additionalProperties: true }
8026
8103
  }),
8027
- outputSchema: OBJECT_OUTPUT$d,
8104
+ outputSchema: OBJECT_OUTPUT$f,
8028
8105
  resultSchemaVersion: 1,
8029
8106
  access: { mode: "fixed", level: "read" },
8030
8107
  asyncMode: "sync",
@@ -8041,7 +8118,7 @@ function listCommand$3() {
8041
8118
  verb: "list",
8042
8119
  summary: "List visible installed Apps",
8043
8120
  inputSchema: emptyInputSchema(),
8044
- outputSchema: OBJECT_OUTPUT$d,
8121
+ outputSchema: OBJECT_OUTPUT$f,
8045
8122
  resultSchemaVersion: 1,
8046
8123
  access: { mode: "fixed", level: "read" },
8047
8124
  asyncMode: "sync",
@@ -8099,7 +8176,7 @@ function installCommand$1(dependencies) {
8099
8176
  no_wait: { type: "boolean" },
8100
8177
  policy: { type: "string", enum: [...INSTALL_POLICIES] }
8101
8178
  }),
8102
- outputSchema: OBJECT_OUTPUT$d,
8179
+ outputSchema: OBJECT_OUTPUT$f,
8103
8180
  resultSchemaVersion: 1,
8104
8181
  access: { mode: "fixed", level: "write" },
8105
8182
  asyncMode: "either",
@@ -8143,7 +8220,7 @@ function upgradeCommand(dependencies) {
8143
8220
  },
8144
8221
  additionalProperties: false
8145
8222
  },
8146
- outputSchema: OBJECT_OUTPUT$d,
8223
+ outputSchema: OBJECT_OUTPUT$f,
8147
8224
  resultSchemaVersion: 1,
8148
8225
  access: { mode: "fixed", level: "write" },
8149
8226
  asyncMode: "either",
@@ -8272,7 +8349,7 @@ function statusCommand$1() {
8272
8349
  properties: { app_name: { type: "string", minLength: 1 } },
8273
8350
  additionalProperties: false
8274
8351
  },
8275
- outputSchema: OBJECT_OUTPUT$d,
8352
+ outputSchema: OBJECT_OUTPUT$f,
8276
8353
  resultSchemaVersion: 1,
8277
8354
  access: { mode: "fixed", level: "read" },
8278
8355
  asyncMode: "sync",
@@ -8343,7 +8420,7 @@ function publishCommand() {
8343
8420
  required: ["local_dir", "app_doc"],
8344
8421
  additionalProperties: false
8345
8422
  },
8346
- outputSchema: OBJECT_OUTPUT$d,
8423
+ outputSchema: OBJECT_OUTPUT$f,
8347
8424
  resultSchemaVersion: 1,
8348
8425
  access: { mode: "fixed", level: "write" },
8349
8426
  asyncMode: "sync",
@@ -9489,7 +9566,7 @@ function selectorCommand(options) {
9489
9566
  required: ["app_name"],
9490
9567
  additionalProperties: false
9491
9568
  },
9492
- outputSchema: OBJECT_OUTPUT$d,
9569
+ outputSchema: OBJECT_OUTPUT$f,
9493
9570
  resultSchemaVersion: 1,
9494
9571
  access: { mode: "fixed", level: options.access },
9495
9572
  asyncMode: options.asyncMode,
@@ -9653,7 +9730,7 @@ function toHex(bytes) {
9653
9730
  return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
9654
9731
  }
9655
9732
  const CONTROL_PANEL$4 = "control-panel";
9656
- const OBJECT_OUTPUT$c = { type: "object", additionalProperties: true };
9733
+ const OBJECT_OUTPUT$e = { type: "object", additionalProperties: true };
9657
9734
  function createDiagnosticModule(dependencies = {}) {
9658
9735
  return {
9659
9736
  name: "diagnostic",
@@ -9692,7 +9769,7 @@ function collectCommand() {
9692
9769
  required: ["services"],
9693
9770
  additionalProperties: false
9694
9771
  },
9695
- outputSchema: OBJECT_OUTPUT$c,
9772
+ outputSchema: OBJECT_OUTPUT$e,
9696
9773
  resultSchemaVersion: 1,
9697
9774
  access: { mode: "fixed", level: "privileged" },
9698
9775
  asyncMode: "task",
@@ -9746,7 +9823,7 @@ function exportCommand$2(dependencies) {
9746
9823
  required: ["bundle_id", "path"],
9747
9824
  additionalProperties: false
9748
9825
  },
9749
- outputSchema: OBJECT_OUTPUT$c,
9826
+ outputSchema: OBJECT_OUTPUT$e,
9750
9827
  resultSchemaVersion: 1,
9751
9828
  access: { mode: "fixed", level: "privileged" },
9752
9829
  asyncMode: "sync",
@@ -9788,7 +9865,7 @@ function compact$2(value) {
9788
9865
  return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
9789
9866
  }
9790
9867
  const CONTROL_PANEL$3 = "control-panel";
9791
- const OBJECT_OUTPUT$b = { type: "object", additionalProperties: true };
9868
+ const OBJECT_OUTPUT$d = { type: "object", additionalProperties: true };
9792
9869
  const LOG_LEVELS = ["error", "warning", "info", "debug", "trace"];
9793
9870
  function createLogModule(dependencies = {}) {
9794
9871
  return {
@@ -9796,7 +9873,7 @@ function createLogModule(dependencies = {}) {
9796
9873
  summary: "List services, query, follow, and export redacted system logs",
9797
9874
  commands: [
9798
9875
  servicesCommand(),
9799
- queryCommand$1(),
9876
+ queryCommand(),
9800
9877
  tailCommand(dependencies),
9801
9878
  exportCommand$1(dependencies)
9802
9879
  ]
@@ -9809,7 +9886,7 @@ function servicesCommand() {
9809
9886
  inputSchema: { type: "object", properties: {}, additionalProperties: false },
9810
9887
  outputSchema: {
9811
9888
  type: "object",
9812
- properties: { services: { type: "array", items: OBJECT_OUTPUT$b } },
9889
+ properties: { services: { type: "array", items: OBJECT_OUTPUT$d } },
9813
9890
  required: ["services"],
9814
9891
  additionalProperties: false
9815
9892
  },
@@ -9829,7 +9906,7 @@ function servicesCommand() {
9829
9906
  }
9830
9907
  };
9831
9908
  }
9832
- function queryCommand$1() {
9909
+ function queryCommand() {
9833
9910
  return {
9834
9911
  verb: "query",
9835
9912
  summary: "Query structured redacted log entries",
@@ -9882,7 +9959,7 @@ function tailCommand(dependencies) {
9882
9959
  }
9883
9960
  ],
9884
9961
  inputSchema: filterSchema({ from: { type: "string", enum: ["start", "end"] } }),
9885
- outputSchema: OBJECT_OUTPUT$b,
9962
+ outputSchema: OBJECT_OUTPUT$d,
9886
9963
  resultSchemaVersion: 1,
9887
9964
  access: { mode: "fixed", level: "read" },
9888
9965
  asyncMode: "stream",
@@ -9938,7 +10015,7 @@ function exportCommand$1(dependencies) {
9938
10015
  ...filterSchema({ path: { type: "string", minLength: 1 } }),
9939
10016
  required: ["path"]
9940
10017
  },
9941
- outputSchema: OBJECT_OUTPUT$b,
10018
+ outputSchema: OBJECT_OUTPUT$d,
9942
10019
  resultSchemaVersion: 1,
9943
10020
  access: { mode: "fixed", level: "read" },
9944
10021
  asyncMode: "sync",
@@ -10090,7 +10167,7 @@ function abortableSleep(milliseconds, signal) {
10090
10167
  }
10091
10168
  const TASK_MANAGER = "task-manager";
10092
10169
  const CONTROL_PANEL$2 = "control-panel";
10093
- const OBJECT_OUTPUT$a = { type: "object", additionalProperties: true };
10170
+ const OBJECT_OUTPUT$c = { type: "object", additionalProperties: true };
10094
10171
  function createTaskModule() {
10095
10172
  return {
10096
10173
  name: "task",
@@ -10193,7 +10270,7 @@ function getCommand$2() {
10193
10270
  required: ["task_id"],
10194
10271
  additionalProperties: false
10195
10272
  },
10196
- outputSchema: OBJECT_OUTPUT$a,
10273
+ outputSchema: OBJECT_OUTPUT$c,
10197
10274
  resultSchemaVersion: 1,
10198
10275
  access: { mode: "fixed", level: "read" },
10199
10276
  asyncMode: "sync",
@@ -10234,7 +10311,7 @@ function waitCommand() {
10234
10311
  summary: "Stream changes until a Task becomes terminal",
10235
10312
  positionals: [{ name: "task_id", description: "Opaque Task ID", required: true }],
10236
10313
  inputSchema: taskIdSchema(),
10237
- outputSchema: OBJECT_OUTPUT$a,
10314
+ outputSchema: OBJECT_OUTPUT$c,
10238
10315
  resultSchemaVersion: 1,
10239
10316
  access: { mode: "fixed", level: "read" },
10240
10317
  asyncMode: "stream",
@@ -10285,7 +10362,7 @@ function cancelCommand() {
10285
10362
  required: ["task_id"],
10286
10363
  additionalProperties: false
10287
10364
  },
10288
- outputSchema: OBJECT_OUTPUT$a,
10365
+ outputSchema: OBJECT_OUTPUT$c,
10289
10366
  resultSchemaVersion: 1,
10290
10367
  access: { mode: "fixed", level: "write" },
10291
10368
  asyncMode: "sync",
@@ -10328,7 +10405,7 @@ function retryCommand() {
10328
10405
  required: ["task_id"],
10329
10406
  additionalProperties: false
10330
10407
  },
10331
- outputSchema: OBJECT_OUTPUT$a,
10408
+ outputSchema: OBJECT_OUTPUT$c,
10332
10409
  resultSchemaVersion: 1,
10333
10410
  access: { mode: "fixed", level: "write" },
10334
10411
  asyncMode: "either",
@@ -10402,7 +10479,7 @@ function invalidResponse$1(label) {
10402
10479
  throw new ToolError("INVALID_SERVICE_RESPONSE", `${label} is invalid`, EXIT_INTERNAL);
10403
10480
  }
10404
10481
  const sdk = provisionSdk;
10405
- const OBJECT_OUTPUT$9 = { type: "object", additionalProperties: true };
10482
+ const OBJECT_OUTPUT$b = { type: "object", additionalProperties: true };
10406
10483
  const ROOT_OPTION = {
10407
10484
  name: "root",
10408
10485
  description: "Installed BuckyOS root on this machine (BUCKYOS_ROOT); read by status/check, written by activate",
@@ -10486,7 +10563,7 @@ function statusCommand(deps) {
10486
10563
  additionalProperties: false
10487
10564
  },
10488
10565
  outputSchema: {
10489
- ...OBJECT_OUTPUT$9,
10566
+ ...OBJECT_OUTPUT$b,
10490
10567
  properties: {
10491
10568
  root: { type: "string" },
10492
10569
  state: {
@@ -10524,7 +10601,7 @@ function checkCommand(deps) {
10524
10601
  additionalProperties: false
10525
10602
  },
10526
10603
  outputSchema: {
10527
- ...OBJECT_OUTPUT$9,
10604
+ ...OBJECT_OUTPUT$b,
10528
10605
  properties: {
10529
10606
  ready: { type: "boolean" },
10530
10607
  root: { type: "string" },
@@ -10572,7 +10649,7 @@ function activateCommand(deps) {
10572
10649
  additionalProperties: false
10573
10650
  },
10574
10651
  outputSchema: {
10575
- ...OBJECT_OUTPUT$9,
10652
+ ...OBJECT_OUTPUT$b,
10576
10653
  properties: {
10577
10654
  root: { type: "string" },
10578
10655
  state: { type: "string", enum: ["configured"] },
@@ -10721,9 +10798,9 @@ async function confirmActivation(ctx, precheck) {
10721
10798
  function isSdkError(error) {
10722
10799
  return error instanceof Error && error.name === "ActivationError" && typeof error.code === "string";
10723
10800
  }
10724
- async function runSdk(run) {
10801
+ async function runSdk(run2) {
10725
10802
  try {
10726
- return await run();
10803
+ return await run2();
10727
10804
  } catch (error) {
10728
10805
  if (isSdkError(error)) {
10729
10806
  const exitCode = error.code === "INVALID_ARGUMENT" ? EXIT_USAGE : error.code === "ACTIVATION_COMMIT_FAILED" ? EXIT_PARTIAL : EXIT_OPERATION;
@@ -10854,7 +10931,7 @@ function inputFingerprint(input) {
10854
10931
  hash.update(new TextEncoder().encode(JSON.stringify(material)));
10855
10932
  return hash.digestHex();
10856
10933
  }
10857
- const OBJECT_OUTPUT$8 = { type: "object", additionalProperties: true };
10934
+ const OBJECT_OUTPUT$a = { type: "object", additionalProperties: true };
10858
10935
  const SKILLS_SUB_PKG = "agent_skills";
10859
10936
  const SKILL_SCOPES = ["ui", "work"];
10860
10937
  const IMPORT_SCOPES = ["work", "ui", "plan"];
@@ -10894,7 +10971,7 @@ function command$1(definition) {
10894
10971
  required: ["agent_id", ...required ?? []],
10895
10972
  additionalProperties: false
10896
10973
  },
10897
- outputSchema: OBJECT_OUTPUT$8,
10974
+ outputSchema: OBJECT_OUTPUT$a,
10898
10975
  resultSchemaVersion: 1,
10899
10976
  access: { mode: "fixed", level },
10900
10977
  asyncMode: "sync",
@@ -11458,9 +11535,9 @@ async function confirm$1(ctx, verb, question) {
11458
11535
  }
11459
11536
  }
11460
11537
  async function kindOf(ctx, agentId, name, input) {
11461
- const given = inputString(input, "kind");
11462
- if (given)
11463
- return given;
11538
+ const given2 = inputString(input, "kind");
11539
+ if (given2)
11540
+ return given2;
11464
11541
  const kinds = (await listSkills(ctx, agentId)).filter((skill) => skill.name === name).map((skill) => String(skill.kind));
11465
11542
  if (kinds.length === 0)
11466
11543
  throw new ToolError("RESOURCE_NOT_FOUND", `Agent ${agentId} has no skill named ${name}`);
@@ -11507,8 +11584,8 @@ function base64(bytes) {
11507
11584
  return btoa(binary);
11508
11585
  }
11509
11586
  const CONTROL_PANEL$1 = "control-panel";
11510
- const OBJECT_OUTPUT$7 = { type: "object", additionalProperties: true };
11511
- const ID$1 = { type: "string", minLength: 1 };
11587
+ const OBJECT_OUTPUT$9 = { type: "object", additionalProperties: true };
11588
+ const ID$2 = { type: "string", minLength: 1 };
11512
11589
  const DEVICE_PREFIX = "exec-";
11513
11590
  const AGENT_RUNTIME_ACTIONS = ["list", "enable", "disable", "default"];
11514
11591
  const AGENT_OPTION = {
@@ -11557,7 +11634,7 @@ function splitAgentRuntimes(records) {
11557
11634
  function agentRuntimeRows(records, settings) {
11558
11635
  const { current, history } = splitAgentRuntimes(records);
11559
11636
  return [...current, ...history].map((record) => {
11560
- const caps = record.caps ?? {};
11637
+ const caps2 = record.caps ?? {};
11561
11638
  const grant = record.grant ?? {};
11562
11639
  const usage2 = record.usage ?? {};
11563
11640
  const connector = record.connector ?? {};
@@ -11568,8 +11645,8 @@ function agentRuntimeRows(records, settings) {
11568
11645
  type: String(connector.type ?? ""),
11569
11646
  state: retired ? "retired" : record.enabled === false ? "off" : String(record.availability ?? "on"),
11570
11647
  default: !retired && (record.default === true || record.runtime_id === settings.default_runtime_id) ? "*" : "",
11571
- os: String(caps.os ?? ""),
11572
- allows: allows(grant.roots, strings(grant.ops).join(",") || "-", grant.computer, caps.baseline),
11648
+ os: String(caps2.os ?? ""),
11649
+ allows: allows(grant.roots, strings(grant.ops).join(",") || "-", grant.computer, caps2.baseline),
11573
11650
  expires: time(grant.expires_at_ms),
11574
11651
  sessions: String(usage2.sessions_total ?? 0),
11575
11652
  workspaces: String(usage2.workspaces ?? 0),
@@ -11609,12 +11686,12 @@ function impactText(agentId, impact) {
11609
11686
  return `${lines.join("\n")}
11610
11687
  `;
11611
11688
  }
11612
- function deviceOf(given, runtimes) {
11613
- const runtime = runtimes.find((item) => item.runtime_id === given || item.executor_id && item.executor_id === given);
11614
- if (runtime ? runtime.kind !== "executor" : given === "host" || given === "private" || given.startsWith("node-")) {
11615
- throw new UsageError("INVALID_ARGUMENT", `${given} is not a device: only device runtimes (${DEVICE_PREFIX}<executor_id>) are revoked; a node runtime is closed on its node`);
11689
+ function deviceOf(given2, runtimes) {
11690
+ const runtime = runtimes.find((item) => item.runtime_id === given2 || item.executor_id && item.executor_id === given2);
11691
+ if (runtime ? runtime.kind !== "executor" : given2 === "host" || given2 === "private" || given2.startsWith("node-")) {
11692
+ throw new UsageError("INVALID_ARGUMENT", `${given2} is not a device: only device runtimes (${DEVICE_PREFIX}<executor_id>) are revoked; a node runtime is closed on its node`);
11616
11693
  }
11617
- const executorId = runtime?.executor_id ? String(runtime.executor_id) : given.startsWith(DEVICE_PREFIX) ? given.slice(DEVICE_PREFIX.length) : given;
11694
+ const executorId = runtime?.executor_id ? String(runtime.executor_id) : given2.startsWith(DEVICE_PREFIX) ? given2.slice(DEVICE_PREFIX.length) : given2;
11618
11695
  return { runtime_id: runtime ? String(runtime.runtime_id) : `${DEVICE_PREFIX}${executorId}`, executor_id: executorId, ...runtime ? { runtime } : {} };
11619
11696
  }
11620
11697
  function reasonText(error) {
@@ -11682,7 +11759,7 @@ function command(definition) {
11682
11759
  const { level, properties, required, ...rest } = definition;
11683
11760
  return {
11684
11761
  inputSchema: { type: "object", properties, required: required ?? [], additionalProperties: false },
11685
- outputSchema: OBJECT_OUTPUT$7,
11762
+ outputSchema: OBJECT_OUTPUT$9,
11686
11763
  resultSchemaVersion: 1,
11687
11764
  access: { mode: "fixed", level },
11688
11765
  asyncMode: "sync",
@@ -11714,7 +11791,7 @@ function createRuntimeModule() {
11714
11791
  positionals: [{ name: "runtime_id", description: "Runtime id as `runtime list` prints it" }],
11715
11792
  options: [AGENT_OPTION, { name: "disabled", description: "Assign it switched off", type: "boolean" }],
11716
11793
  level: "write",
11717
- properties: { runtime_id: ID$1, agent_id: ID$1, disabled: { type: "boolean" } },
11794
+ properties: { runtime_id: ID$2, agent_id: ID$2, disabled: { type: "boolean" } },
11718
11795
  required: ["runtime_id", "agent_id"],
11719
11796
  examples: [
11720
11797
  "buckyos runtime assign host --agent jarvis.example.zone",
@@ -11729,7 +11806,7 @@ function createRuntimeModule() {
11729
11806
  positionals: [{ name: "runtime_id", description: "Runtime id" }],
11730
11807
  options: [AGENT_OPTION],
11731
11808
  level: "destructive",
11732
- properties: { runtime_id: ID$1, agent_id: ID$1 },
11809
+ properties: { runtime_id: ID$2, agent_id: ID$2 },
11733
11810
  required: ["runtime_id", "agent_id"],
11734
11811
  examples: ["buckyos runtime unassign host --agent jarvis.example.zone"],
11735
11812
  handler: async (ctx, input) => await unassign(ctx, input)
@@ -11740,7 +11817,7 @@ function createRuntimeModule() {
11740
11817
  description: "Devices only (exec-<executor_id>, or the executor id). Refused while sessions of the Agent using it run there (SESSIONS_IN_PROGRESS); otherwise shows the Agents the device is assigned to and asks; --yes skips the question.",
11741
11818
  positionals: [{ name: "runtime_id", description: "Device runtime id (exec-<executor_id>) or executor id" }],
11742
11819
  level: "destructive",
11743
- properties: { runtime_id: ID$1 },
11820
+ properties: { runtime_id: ID$2 },
11744
11821
  required: ["runtime_id"],
11745
11822
  examples: ["buckyos runtime revoke exec-laptop", "buckyos --yes runtime revoke laptop"],
11746
11823
  handler: async (ctx, input) => await revoke(ctx, input)
@@ -11760,11 +11837,11 @@ function agentRuntimeCommand() {
11760
11837
  options: [AGENT_OPTION],
11761
11838
  inputSchema: {
11762
11839
  type: "object",
11763
- properties: { action: { type: "string", enum: AGENT_RUNTIME_ACTIONS }, runtime_id: ID$1, agent_id: ID$1 },
11840
+ properties: { action: { type: "string", enum: AGENT_RUNTIME_ACTIONS }, runtime_id: ID$2, agent_id: ID$2 },
11764
11841
  required: ["action", "agent_id"],
11765
11842
  additionalProperties: false
11766
11843
  },
11767
- outputSchema: OBJECT_OUTPUT$7,
11844
+ outputSchema: OBJECT_OUTPUT$9,
11768
11845
  resultSchemaVersion: 1,
11769
11846
  access: { mode: "operation", operationIdField: "action", possibleLevels: ["read", "write"] },
11770
11847
  asyncMode: "sync",
@@ -11921,8 +11998,8 @@ async function unassign(ctx, input) {
11921
11998
  return { agent_id: agentId, runtime_id: runtimeId, removed: true, via: "agent", impact, settings };
11922
11999
  }
11923
12000
  async function revoke(ctx, input) {
11924
- const given = requiredInputString(input, "runtime_id");
11925
- const device = deviceOf(given, (await catalog(ctx)).runtimes);
12001
+ const given2 = requiredInputString(input, "runtime_id");
12002
+ const device = deviceOf(given2, (await catalog(ctx)).runtimes);
11926
12003
  const assigned = objects(device.runtime?.assigned_to);
11927
12004
  const lines = [
11928
12005
  device.runtime ? `Device ${device.runtime_id} (${device.runtime.name ?? device.executor_id}) is assigned to ${assigned.length} Agent(s)` : `Device ${device.runtime_id} is not in your runtime directory: nothing is known about its Agents`,
@@ -11953,7 +12030,7 @@ async function revoke(ctx, input) {
11953
12030
  return { runtime_id: device.runtime_id, executor_id: device.executor_id, revoked: true, assigned_to: assigned, impacts, ...revoked };
11954
12031
  }
11955
12032
  const CONTROL_PANEL = "control-panel";
11956
- const OBJECT_OUTPUT$6 = { type: "object", additionalProperties: true };
12033
+ const OBJECT_OUTPUT$8 = { type: "object", additionalProperties: true };
11957
12034
  const AGENT_POSITIONAL = {
11958
12035
  name: "agent_id",
11959
12036
  description: "Agent ID as `agent list` prints it (raw host name, e.g. jarvis.example.zone)"
@@ -11977,7 +12054,7 @@ function createAgentModule() {
11977
12054
  inputSchema: { type: "object", properties: {}, additionalProperties: false },
11978
12055
  outputSchema: {
11979
12056
  type: "object",
11980
- properties: { agents: { type: "array", items: OBJECT_OUTPUT$6 } },
12057
+ properties: { agents: { type: "array", items: OBJECT_OUTPUT$8 } },
11981
12058
  required: ["agents"],
11982
12059
  additionalProperties: false
11983
12060
  },
@@ -12003,7 +12080,7 @@ function createAgentModule() {
12003
12080
  summary: "Get one Agent: profile, settings, install state, template, and runtime",
12004
12081
  positionals: [AGENT_POSITIONAL],
12005
12082
  inputSchema: AGENT_INPUT,
12006
- outputSchema: OBJECT_OUTPUT$6,
12083
+ outputSchema: OBJECT_OUTPUT$8,
12007
12084
  resultSchemaVersion: 1,
12008
12085
  access: { mode: "fixed", level: "read" },
12009
12086
  asyncMode: "sync",
@@ -12016,7 +12093,7 @@ function createAgentModule() {
12016
12093
  summary: "Get the public profile (display name, bio, avatar) of an Agent",
12017
12094
  positionals: [AGENT_POSITIONAL],
12018
12095
  inputSchema: AGENT_INPUT,
12019
- outputSchema: OBJECT_OUTPUT$6,
12096
+ outputSchema: OBJECT_OUTPUT$8,
12020
12097
  resultSchemaVersion: 1,
12021
12098
  access: { mode: "fixed", level: "read" },
12022
12099
  asyncMode: "sync",
@@ -12057,8 +12134,8 @@ function createAgentModule() {
12057
12134
  type: "object",
12058
12135
  properties: {
12059
12136
  agent_id: { type: "string" },
12060
- before: OBJECT_OUTPUT$6,
12061
- profile: OBJECT_OUTPUT$6
12137
+ before: OBJECT_OUTPUT$8,
12138
+ profile: OBJECT_OUTPUT$8
12062
12139
  },
12063
12140
  required: ["agent_id", "before", "profile"],
12064
12141
  additionalProperties: false
@@ -12104,7 +12181,7 @@ async function callAgent(ctx, method, params) {
12104
12181
  }
12105
12182
  }
12106
12183
  const AICC = "aicc";
12107
- const OBJECT_OUTPUT$5 = { type: "object", additionalProperties: true };
12184
+ const OBJECT_OUTPUT$7 = { type: "object", additionalProperties: true };
12108
12185
  const EMPTY_INPUT = { type: "object", properties: {}, additionalProperties: false };
12109
12186
  const RANGES = ["last1d", "last7d", "last30d"];
12110
12187
  const GROUPS = [
@@ -12152,7 +12229,7 @@ function quotaCommand() {
12152
12229
  properties: { app: { type: "string", minLength: 1 } },
12153
12230
  additionalProperties: false
12154
12231
  },
12155
- outputSchema: OBJECT_OUTPUT$5,
12232
+ outputSchema: OBJECT_OUTPUT$7,
12156
12233
  resultSchemaVersion: 1,
12157
12234
  access: { mode: "fixed", level: "read" },
12158
12235
  asyncMode: "sync",
@@ -12170,7 +12247,7 @@ function readCommand$2(options) {
12170
12247
  summary: options.summary,
12171
12248
  description: options.description,
12172
12249
  inputSchema: EMPTY_INPUT,
12173
- outputSchema: OBJECT_OUTPUT$5,
12250
+ outputSchema: OBJECT_OUTPUT$7,
12174
12251
  resultSchemaVersion: 1,
12175
12252
  access: { mode: "fixed", level: "read" },
12176
12253
  asyncMode: "sync",
@@ -12222,7 +12299,7 @@ function usageCommand() {
12222
12299
  },
12223
12300
  additionalProperties: false
12224
12301
  },
12225
- outputSchema: OBJECT_OUTPUT$5,
12302
+ outputSchema: OBJECT_OUTPUT$7,
12226
12303
  resultSchemaVersion: 1,
12227
12304
  access: { mode: "fixed", level: "read" },
12228
12305
  asyncMode: "sync",
@@ -12267,7 +12344,7 @@ function timeRange(input) {
12267
12344
  }
12268
12345
  return { kind: "explicit", start_time_ms: since, end_time_ms: until ?? Date.now() };
12269
12346
  }
12270
- const OBJECT_OUTPUT$4 = { type: "object", additionalProperties: true };
12347
+ const OBJECT_OUTPUT$6 = { type: "object", additionalProperties: true };
12271
12348
  const DAY_MS$1 = 864e5;
12272
12349
  const EXPIRES_HELP = "1d, 7d (default), 30d, none, or an RFC 3339 time";
12273
12350
  function createShareModule() {
@@ -12378,7 +12455,7 @@ function createCommand() {
12378
12455
  required: ["path"],
12379
12456
  additionalProperties: false
12380
12457
  },
12381
- outputSchema: OBJECT_OUTPUT$4,
12458
+ outputSchema: OBJECT_OUTPUT$6,
12382
12459
  resultSchemaVersion: 1,
12383
12460
  access: { mode: "fixed", level: "write" },
12384
12461
  asyncMode: "either",
@@ -12447,7 +12524,7 @@ function listCommand() {
12447
12524
  },
12448
12525
  additionalProperties: false
12449
12526
  },
12450
- outputSchema: OBJECT_OUTPUT$4,
12527
+ outputSchema: OBJECT_OUTPUT$6,
12451
12528
  resultSchemaVersion: 1,
12452
12529
  access: { mode: "fixed", level: "read" },
12453
12530
  asyncMode: "sync",
@@ -12479,7 +12556,7 @@ function getCommand$1() {
12479
12556
  required: ["share_id"],
12480
12557
  additionalProperties: false
12481
12558
  },
12482
- outputSchema: OBJECT_OUTPUT$4,
12559
+ outputSchema: OBJECT_OUTPUT$6,
12483
12560
  resultSchemaVersion: 1,
12484
12561
  access: { mode: "fixed", level: "read" },
12485
12562
  asyncMode: "sync",
@@ -12516,7 +12593,7 @@ function updateCommand() {
12516
12593
  required: ["share_id"],
12517
12594
  additionalProperties: false
12518
12595
  },
12519
- outputSchema: OBJECT_OUTPUT$4,
12596
+ outputSchema: OBJECT_OUTPUT$6,
12520
12597
  resultSchemaVersion: 1,
12521
12598
  access: { mode: "fixed", level: "write" },
12522
12599
  asyncMode: "sync",
@@ -12560,7 +12637,7 @@ function stopCommand() {
12560
12637
  required: ["share_id"],
12561
12638
  additionalProperties: false
12562
12639
  },
12563
- outputSchema: OBJECT_OUTPUT$4,
12640
+ outputSchema: OBJECT_OUTPUT$6,
12564
12641
  resultSchemaVersion: 1,
12565
12642
  access: { mode: "fixed", level: "destructive" },
12566
12643
  asyncMode: "sync",
@@ -12592,7 +12669,7 @@ function statsCommand() {
12592
12669
  },
12593
12670
  additionalProperties: false
12594
12671
  },
12595
- outputSchema: OBJECT_OUTPUT$4,
12672
+ outputSchema: OBJECT_OUTPUT$6,
12596
12673
  resultSchemaVersion: 1,
12597
12674
  access: { mode: "fixed", level: "read" },
12598
12675
  asyncMode: "sync",
@@ -12611,8 +12688,8 @@ function statsCommand() {
12611
12688
  }
12612
12689
  };
12613
12690
  }
12614
- const OBJECT_OUTPUT$3 = { type: "object", additionalProperties: true };
12615
- const SERVICE$1 = "nfs-server";
12691
+ const OBJECT_OUTPUT$5 = { type: "object", additionalProperties: true };
12692
+ const SERVICE$2 = "nfs-server";
12616
12693
  const MAX_PUT_BYTES = 32 * 1024 * 1024;
12617
12694
  const DAY_MS = 864e5;
12618
12695
  const BUCKET_ERROR_CODES = [
@@ -12641,7 +12718,7 @@ function createBucketModule() {
12641
12718
  return {
12642
12719
  name: "bucket",
12643
12720
  summary: "Read and write application object buckets (key -> object, retained by the Zone)",
12644
- commands: [lsCommand(), statCommand(), putCommand(), getCommand(), rmCommand(), linkCommand(), s3KeysCommand(), s3KeyCreateCommand(), s3KeyRevokeCommand()]
12721
+ commands: [lsCommand$1(), statCommand$1(), putCommand(), getCommand(), rmCommand(), linkCommand(), s3KeysCommand(), s3KeyCreateCommand(), s3KeyRevokeCommand()]
12645
12722
  };
12646
12723
  }
12647
12724
  function parseBucketTarget(value, keyRequired) {
@@ -12655,9 +12732,9 @@ function parseBucketTarget(value, keyRequired) {
12655
12732
  throw new UsageError("INVALID_ARGUMENT", `'${value}' names no key`);
12656
12733
  return { bucketId: parts.slice(0, 4).join("/"), key };
12657
12734
  }
12658
- async function call$2(ctx, method, params) {
12735
+ async function call$3(ctx, method, params) {
12659
12736
  try {
12660
- return await callService(ctx, SERVICE$1, method, params);
12737
+ return await callService(ctx, SERVICE$2, method, params);
12661
12738
  } catch (error) {
12662
12739
  const message2 = error instanceof Error ? error.message : String(error);
12663
12740
  const code = BUCKET_ERROR_CODES.find((c) => message2.includes(`${c}: `));
@@ -12694,7 +12771,7 @@ async function failure(response) {
12694
12771
  throw new ToolError(`BUCKET_${String(body.error ?? response.status).toUpperCase()}`, String(body.message ?? `HTTP ${response.status}`));
12695
12772
  }
12696
12773
  const TARGET = { name: "target", description: "obj://bucket/<scope>/<appid>/<owner>/<name>[/<key>]", required: true };
12697
- function lsCommand() {
12774
+ function lsCommand$1() {
12698
12775
  return {
12699
12776
  verb: "ls",
12700
12777
  summary: "List your buckets, or the keys of one bucket",
@@ -12716,7 +12793,7 @@ function lsCommand() {
12716
12793
  },
12717
12794
  additionalProperties: false
12718
12795
  },
12719
- outputSchema: OBJECT_OUTPUT$3,
12796
+ outputSchema: OBJECT_OUTPUT$5,
12720
12797
  resultSchemaVersion: 1,
12721
12798
  access: { mode: "fixed", level: "read" },
12722
12799
  asyncMode: "sync",
@@ -12725,9 +12802,9 @@ function lsCommand() {
12725
12802
  handler: async (ctx, input) => {
12726
12803
  const raw = inputString(input, "target");
12727
12804
  if (!raw)
12728
- return { buckets: await call$2(ctx, "bucket.list", { appid: inputString(input, "appid") }) };
12805
+ return { buckets: await call$3(ctx, "bucket.list", { appid: inputString(input, "appid") }) };
12729
12806
  const target = parseBucketTarget(raw, false);
12730
- return await call$2(ctx, "bucket.list_objects", {
12807
+ return await call$3(ctx, "bucket.list_objects", {
12731
12808
  bucket_id: target.bucketId,
12732
12809
  prefix: target.key,
12733
12810
  delimiter: inputString(input, "delimiter"),
@@ -12737,7 +12814,7 @@ function lsCommand() {
12737
12814
  }
12738
12815
  };
12739
12816
  }
12740
- function statCommand() {
12817
+ function statCommand$1() {
12741
12818
  return {
12742
12819
  verb: "stat",
12743
12820
  summary: "Show a bucket (usage, quota) or a key (binding and where its content is)",
@@ -12749,7 +12826,7 @@ function statCommand() {
12749
12826
  required: ["target"],
12750
12827
  additionalProperties: false
12751
12828
  },
12752
- outputSchema: OBJECT_OUTPUT$3,
12829
+ outputSchema: OBJECT_OUTPUT$5,
12753
12830
  resultSchemaVersion: 1,
12754
12831
  access: { mode: "fixed", level: "read" },
12755
12832
  asyncMode: "sync",
@@ -12759,12 +12836,12 @@ function statCommand() {
12759
12836
  const target = parseBucketTarget(requiredInputString(input, "target"), false);
12760
12837
  if (!target.key) {
12761
12838
  const [bucket, quota] = await Promise.all([
12762
- call$2(ctx, "bucket.stat", { bucket_id: target.bucketId }),
12763
- call$2(ctx, "bucket.get_quota", { bucket_id: target.bucketId })
12839
+ call$3(ctx, "bucket.stat", { bucket_id: target.bucketId }),
12840
+ call$3(ctx, "bucket.get_quota", { bucket_id: target.bucketId })
12764
12841
  ]);
12765
12842
  return { bucket, quota };
12766
12843
  }
12767
- return await call$2(ctx, "bucket.head", { bucket_id: target.bucketId, key: target.key, version: input.version });
12844
+ return await call$3(ctx, "bucket.head", { bucket_id: target.bucketId, key: target.key, version: input.version });
12768
12845
  }
12769
12846
  };
12770
12847
  }
@@ -12790,7 +12867,7 @@ function putCommand() {
12790
12867
  required: ["target", "file"],
12791
12868
  additionalProperties: false
12792
12869
  },
12793
- outputSchema: OBJECT_OUTPUT$3,
12870
+ outputSchema: OBJECT_OUTPUT$5,
12794
12871
  resultSchemaVersion: 1,
12795
12872
  access: { mode: "fixed", level: "write" },
12796
12873
  asyncMode: "sync",
@@ -12839,7 +12916,7 @@ function getCommand() {
12839
12916
  required: ["target", "output"],
12840
12917
  additionalProperties: false
12841
12918
  },
12842
- outputSchema: OBJECT_OUTPUT$3,
12919
+ outputSchema: OBJECT_OUTPUT$5,
12843
12920
  resultSchemaVersion: 1,
12844
12921
  access: { mode: "fixed", level: "read" },
12845
12922
  asyncMode: "sync",
@@ -12877,7 +12954,7 @@ function rmCommand() {
12877
12954
  required: ["target"],
12878
12955
  additionalProperties: false
12879
12956
  },
12880
- outputSchema: OBJECT_OUTPUT$3,
12957
+ outputSchema: OBJECT_OUTPUT$5,
12881
12958
  resultSchemaVersion: 1,
12882
12959
  access: { mode: "fixed", level: "write" },
12883
12960
  asyncMode: "sync",
@@ -12885,7 +12962,7 @@ function rmCommand() {
12885
12962
  examples: ["buckyos bucket rm obj://bucket/user/photos/alice/library/2026/a.jpg"],
12886
12963
  handler: async (ctx, input) => {
12887
12964
  const target = parseBucketTarget(requiredInputString(input, "target"), true);
12888
- return await call$2(ctx, "bucket.delete", { bucket_id: target.bucketId, key: target.key, version: input.version });
12965
+ return await call$3(ctx, "bucket.delete", { bucket_id: target.bucketId, key: target.key, version: input.version });
12889
12966
  }
12890
12967
  };
12891
12968
  }
@@ -12908,7 +12985,7 @@ function linkCommand() {
12908
12985
  required: ["target"],
12909
12986
  additionalProperties: false
12910
12987
  },
12911
- outputSchema: OBJECT_OUTPUT$3,
12988
+ outputSchema: OBJECT_OUTPUT$5,
12912
12989
  resultSchemaVersion: 1,
12913
12990
  access: { mode: "fixed", level: "write" },
12914
12991
  asyncMode: "sync",
@@ -12921,7 +12998,7 @@ function linkCommand() {
12921
12998
  const expiresAt = days ? Date.now() + Number(days[1]) * DAY_MS : parseTimestamp(text2, "expires");
12922
12999
  if (expiresAt === void 0)
12923
13000
  throw new UsageError("INVALID_ARGUMENT", "expires is required");
12924
- const issued = await call$2(ctx, "bucket.create_access_token", {
13001
+ const issued = await call$3(ctx, "bucket.create_access_token", {
12925
13002
  bucket_id: target.bucketId,
12926
13003
  key: target.key,
12927
13004
  actions: ["read"],
@@ -12937,13 +13014,13 @@ function s3KeysCommand() {
12937
13014
  verb: "s3-keys",
12938
13015
  summary: "List your S3 access keys (secrets are shown only when created)",
12939
13016
  inputSchema: { type: "object", properties: {}, additionalProperties: false },
12940
- outputSchema: OBJECT_OUTPUT$3,
13017
+ outputSchema: OBJECT_OUTPUT$5,
12941
13018
  resultSchemaVersion: 1,
12942
13019
  access: { mode: "fixed", level: "read" },
12943
13020
  asyncMode: "sync",
12944
13021
  requiresSession: true,
12945
13022
  examples: ["buckyos bucket s3-keys"],
12946
- handler: async (ctx) => ({ keys: await call$2(ctx, "bucket.list_s3_keys", {}) })
13023
+ handler: async (ctx) => ({ keys: await call$3(ctx, "bucket.list_s3_keys", {}) })
12947
13024
  };
12948
13025
  }
12949
13026
  function s3KeyCreateCommand() {
@@ -12961,7 +13038,7 @@ function s3KeyCreateCommand() {
12961
13038
  required: ["app"],
12962
13039
  additionalProperties: false
12963
13040
  },
12964
- outputSchema: OBJECT_OUTPUT$3,
13041
+ outputSchema: OBJECT_OUTPUT$5,
12965
13042
  resultSchemaVersion: 1,
12966
13043
  access: { mode: "fixed", level: "write" },
12967
13044
  asyncMode: "sync",
@@ -12972,7 +13049,7 @@ function s3KeyCreateCommand() {
12972
13049
  const days = text2?.match(/^(\d+)d$/);
12973
13050
  const expiresAt = !text2 ? void 0 : days ? Date.now() + Number(days[1]) * DAY_MS : parseTimestamp(text2, "expires");
12974
13051
  const prefix = inputString(input, "prefix");
12975
- const key = await call$2(ctx, "bucket.create_s3_key", {
13052
+ const key = await call$3(ctx, "bucket.create_s3_key", {
12976
13053
  appid: requiredInputString(input, "app"),
12977
13054
  scope: prefix ? { prefix } : void 0,
12978
13055
  expires_at: expiresAt
@@ -12992,22 +13069,22 @@ function s3KeyRevokeCommand() {
12992
13069
  required: ["access_key_id"],
12993
13070
  additionalProperties: false
12994
13071
  },
12995
- outputSchema: OBJECT_OUTPUT$3,
13072
+ outputSchema: OBJECT_OUTPUT$5,
12996
13073
  resultSchemaVersion: 1,
12997
13074
  access: { mode: "fixed", level: "write" },
12998
13075
  asyncMode: "sync",
12999
13076
  requiresSession: true,
13000
13077
  examples: ["buckyos bucket s3-key-revoke BKABCDEFGHIJKLMNOPQR"],
13001
- handler: async (ctx, input) => await call$2(ctx, "bucket.revoke_s3_key", { access_key_id: requiredInputString(input, "access_key_id") })
13078
+ handler: async (ctx, input) => await call$3(ctx, "bucket.revoke_s3_key", { access_key_id: requiredInputString(input, "access_key_id") })
13002
13079
  };
13003
13080
  }
13004
- const OBJECT_OUTPUT$2 = { type: "object", additionalProperties: true };
13081
+ const OBJECT_OUTPUT$4 = { type: "object", additionalProperties: true };
13005
13082
  const URL_ARG = { name: "url", description: "obj:// cyfs:// file:// https:// url, or //<service>/... /abs/path shorthand", required: true };
13006
13083
  function createObjModule() {
13007
13084
  return {
13008
13085
  name: "obj",
13009
13086
  summary: "Resolve system URLs and read DID Objects (obj://, cyfs://, file://, https://)",
13010
- commands: [resolveCommand(), readCommand$1()]
13087
+ commands: [resolveCommand$1(), readCommand$1()]
13011
13088
  };
13012
13089
  }
13013
13090
  function gatewayOrigin(endpoint) {
@@ -13046,13 +13123,13 @@ function describe(ctx, url) {
13046
13123
  out.obj_id = url.objId.toString();
13047
13124
  return out;
13048
13125
  }
13049
- function resolveCommand() {
13126
+ function resolveCommand$1() {
13050
13127
  return {
13051
13128
  verb: "resolve",
13052
13129
  summary: "Normalize a URL and show its identity, RBAC key, events and endpoint (no access check)",
13053
13130
  positionals: [URL_ARG],
13054
13131
  inputSchema: { type: "object", properties: { url: { type: "string", minLength: 1 } }, required: ["url"], additionalProperties: false },
13055
- outputSchema: OBJECT_OUTPUT$2,
13132
+ outputSchema: OBJECT_OUTPUT$4,
13056
13133
  resultSchemaVersion: 1,
13057
13134
  access: { mode: "fixed", level: "read" },
13058
13135
  asyncMode: "sync",
@@ -13089,7 +13166,7 @@ function readCommand$1() {
13089
13166
  required: ["url"],
13090
13167
  additionalProperties: false
13091
13168
  },
13092
- outputSchema: OBJECT_OUTPUT$2,
13169
+ outputSchema: OBJECT_OUTPUT$4,
13093
13170
  resultSchemaVersion: 1,
13094
13171
  access: { mode: "fixed", level: "read" },
13095
13172
  asyncMode: "sync",
@@ -13141,7 +13218,7 @@ const targetProperties = {
13141
13218
  store_id: text,
13142
13219
  locator: text
13143
13220
  };
13144
- function call$1(ctx, method, params) {
13221
+ function call$2(ctx, method, params) {
13145
13222
  return ctx.clients.call("control-panel", method, params, {
13146
13223
  traceId: ctx.traceId,
13147
13224
  signal: ctx.signal,
@@ -13165,7 +13242,7 @@ function management(verb, method, properties, required, write = false) {
13165
13242
  type: schema.type === "integer" ? "integer" : "string",
13166
13243
  required: required.includes(name)
13167
13244
  })),
13168
- handler: (ctx, input) => call$1(ctx, method, input)
13245
+ handler: (ctx, input) => call$2(ctx, method, input)
13169
13246
  };
13170
13247
  }
13171
13248
  function createExecutorModule() {
@@ -13221,7 +13298,7 @@ function operation(verb, extra, required) {
13221
13298
  if (!ctx.session)
13222
13299
  throw new ToolError("AUTH_REQUIRED", "An authenticated App session is required");
13223
13300
  const { token } = await ctx.session.ensureValid();
13224
- const route = await call$1(ctx, "executor.stream.open", { executor_id: target.executor_id, generation: target.generation, profile_id: target.profile_id });
13301
+ const route = await call$2(ctx, "executor.stream.open", { executor_id: target.executor_id, generation: target.generation, profile_id: target.profile_id });
13225
13302
  const stream = await ExecutorCommandStream.connect(route, target, token, "buckyos-cli", locator.run_id);
13226
13303
  if (!stream)
13227
13304
  throw new ToolError("INVALID_SERVICE_RESPONSE", "Executor stream did not initialize");
@@ -13249,9 +13326,9 @@ function operation(verb, extra, required) {
13249
13326
  }
13250
13327
  };
13251
13328
  }
13252
- const OBJECT_OUTPUT$1 = { type: "object", additionalProperties: true };
13253
- const ID = { type: "string", minLength: 1 };
13254
- function call(ctx, method, params) {
13329
+ const OBJECT_OUTPUT$3 = { type: "object", additionalProperties: true };
13330
+ const ID$1 = { type: "string", minLength: 1 };
13331
+ function call$1(ctx, method, params) {
13255
13332
  return ctx.clients.call("control-panel", method, params, {
13256
13333
  traceId: ctx.traceId,
13257
13334
  signal: ctx.signal,
@@ -13269,16 +13346,16 @@ function read(verb, summary2, method) {
13269
13346
  verb,
13270
13347
  summary: summary2,
13271
13348
  inputSchema: { type: "object", properties: {}, additionalProperties: false },
13272
- outputSchema: OBJECT_OUTPUT$1,
13349
+ outputSchema: OBJECT_OUTPUT$3,
13273
13350
  resultSchemaVersion: 1,
13274
13351
  access: { mode: "fixed", level: "read" },
13275
13352
  asyncMode: "sync",
13276
13353
  requiresSession: true,
13277
- handler: (ctx) => call(ctx, method, {})
13354
+ handler: (ctx) => call$1(ctx, method, {})
13278
13355
  };
13279
13356
  }
13280
13357
  function desired(verb, summary2, enabled) {
13281
- const properties = { id: ID, ...enabled ? { version: { type: "string", minLength: 1 } } : {}, dry_run: { type: "boolean" } };
13358
+ const properties = { id: ID$1, ...enabled ? { version: { type: "string", minLength: 1 } } : {}, dry_run: { type: "boolean" } };
13282
13359
  return {
13283
13360
  verb,
13284
13361
  summary: summary2,
@@ -13288,12 +13365,12 @@ function desired(verb, summary2, enabled) {
13288
13365
  { name: "dry-run", property: "dry_run", description: "Only show what would change", type: "boolean" }
13289
13366
  ],
13290
13367
  inputSchema: { type: "object", properties, required: ["id"], additionalProperties: false },
13291
- outputSchema: OBJECT_OUTPUT$1,
13368
+ outputSchema: OBJECT_OUTPUT$3,
13292
13369
  resultSchemaVersion: 1,
13293
13370
  access: { mode: "fixed", level: "write" },
13294
13371
  asyncMode: "sync",
13295
13372
  requiresSession: true,
13296
- handler: (ctx, input) => call(ctx, input.dry_run === true ? "ext_tools.plan" : "ext_tools.set_desired", requestOf(input, enabled))
13373
+ handler: (ctx, input) => call$1(ctx, input.dry_run === true ? "ext_tools.plan" : "ext_tools.set_desired", requestOf(input, enabled))
13297
13374
  };
13298
13375
  }
13299
13376
  function createExtToolsModule() {
@@ -13310,108 +13387,1227 @@ function createExtToolsModule() {
13310
13387
  summary: "Put an already built .pikg (an official release asset) into the Repo unchanged",
13311
13388
  positionals: [{ name: "pikg", description: "Local .pikg file" }],
13312
13389
  inputSchema: { type: "object", properties: { pikg: { type: "string", minLength: 1 } }, required: ["pikg"], additionalProperties: false },
13313
- outputSchema: OBJECT_OUTPUT$1,
13390
+ outputSchema: OBJECT_OUTPUT$3,
13314
13391
  resultSchemaVersion: 1,
13315
13392
  access: { mode: "fixed", level: "write" },
13316
13393
  asyncMode: "sync",
13317
13394
  requiresSession: true,
13318
13395
  handler: async (ctx, input) => {
13319
13396
  const staging = await stageLocalPikg(ctx, String(input.pikg));
13320
- return await call(ctx, "ext_tools.import", { handle: staging.handle });
13397
+ return await call$1(ctx, "ext_tools.import", { handle: staging.handle });
13321
13398
  }
13322
13399
  }
13323
13400
  ]
13324
13401
  };
13325
13402
  }
13326
- const SERVICE = "aiworkspace";
13327
- const OBJECT_OUTPUT = { type: "object", additionalProperties: true };
13328
- const WORKSPACE_OPTION = { name: "workspace", property: "workspace_id", description: "Workspace id (ws_…)", type: "string", required: true };
13329
- const RUN_OPTION = { name: "run", property: "run_id", description: "Run id (run_…)", type: "string", required: true };
13330
- const ATTEMPT_OPTION = { name: "attempt", property: "attempt", description: "The attempt number `run-claim` answered", type: "integer", required: true };
13331
- function workspaceInput(extra, required = []) {
13332
- return { type: "object", properties: { workspace_id: { type: "string", minLength: 1 }, ...extra }, required: ["workspace_id", ...required], additionalProperties: false };
13403
+ const OBJECT_OUTPUT$2 = { type: "object", additionalProperties: true };
13404
+ function schedule(ctx) {
13405
+ return new ScheduleClient({
13406
+ call: async (method, params) => {
13407
+ const result = expectObject$4(await callService(ctx, "aiworkspace", method, params), method);
13408
+ if (result.ok === false) {
13409
+ const error = expectObject$4(result.error, `${method}.error`);
13410
+ 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 : void 0, data: error.data });
13411
+ }
13412
+ return result;
13413
+ }
13414
+ }, { locale: /^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale) ? "zh" : "en" });
13333
13415
  }
13334
- async function aiws(ctx, method, params) {
13335
- const result = expectObject$4(await callService(ctx, SERVICE, method, params), method);
13336
- if (result.ok === false) {
13337
- const error = expectObject$4(result.error, `${method}.error`);
13338
- const code = typeof error.code === "string" ? error.code : "AIWS_ERROR";
13339
- const detail = typeof error.detail === "string" ? error.detail : code;
13340
- const details = {};
13341
- if (typeof error.sub_code === "string")
13342
- details.sub_code = error.sub_code;
13343
- if (error.data !== void 0)
13344
- details.data = error.data;
13345
- throw new ToolError(code, `${code}${typeof error.sub_code === "string" ? `/${error.sub_code}` : ""}: ${detail}`, void 0, false, details);
13416
+ async function run(work) {
13417
+ try {
13418
+ return await work();
13419
+ } catch (error) {
13420
+ if (error instanceof AiwsFailure)
13421
+ throw new ToolError(error.code, error.message, void 0, false, { ...error.subCode ? { sub_code: error.subCode } : {}, ...error.data !== void 0 ? { data: error.data } : {} });
13422
+ throw error;
13346
13423
  }
13347
- return result;
13348
- }
13349
- async function jsonInput(input, textKey, fileKey, label) {
13350
- const text2 = inputString(input, textKey);
13351
- const file = inputString(input, fileKey);
13352
- if (text2 && file)
13353
- throw new UsageError("AIWS_USAGE", `${textKey} and ${fileKey} are exclusive`);
13354
- if (file)
13355
- return JSON.parse(await getHost().readTextFile(file));
13356
- if (text2)
13357
- return JSON.parse(text2);
13358
- throw new UsageError("AIWS_USAGE", `${label}: pass --${textKey.replace(/_/g, "-")} or --${fileKey.replace(/_/g, "-")}`);
13359
13424
  }
13360
- const readCommand = {
13361
- verb: "read",
13362
- summary: "Read one entity of a workspace (envelope and content)",
13363
- positionals: [{ name: "entity_id", description: "Entity id", required: true }],
13364
- options: [WORKSPACE_OPTION, { name: "selector", property: "selector", description: 'Selector JSON, e.g. {"kind":"table_record","record_id":"r1"}', type: "string" }],
13365
- inputSchema: workspaceInput({ entity_id: { type: "string", minLength: 1 }, selector: { type: "string" } }, ["entity_id"]),
13366
- outputSchema: OBJECT_OUTPUT,
13425
+ const todoView = (i) => ({ 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 } : {} });
13426
+ const eventView = (o) => ({
13427
+ id: o.id,
13428
+ record_id: o.row.record_id,
13429
+ title: o.title,
13430
+ all_day: o.allDay,
13431
+ ...o.allDay ? { start_date: o.startDate, end_date: o.endDate } : { start: new Date(o.startMs).toISOString(), end: new Date(o.endMs).toISOString() },
13432
+ ...o.recurring ? { recurring: true, original: o.original } : {},
13433
+ ...o.override ? { changed_once: true } : {},
13434
+ ...o.agentWritten ? { agent_written: true } : {},
13435
+ ...o.status ? { status: o.status } : {},
13436
+ ...Object.keys(o.ext).length ? { ext: o.ext } : {}
13437
+ });
13438
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
13439
+ function parseExt(input) {
13440
+ const text2 = inputString(input, "ext");
13441
+ if (!text2)
13442
+ return void 0;
13443
+ const ext = JSON.parse(text2);
13444
+ if (!ext || typeof ext !== "object" || Array.isArray(ext))
13445
+ throw new UsageError("AIWS_USAGE", "--ext must be a JSON object");
13446
+ return ext;
13447
+ }
13448
+ const ID = { name: "id", property: "id", description: "To-do record id (`todo list` shows them)", type: "string" };
13449
+ const todoCommand = {
13450
+ verb: "todo",
13451
+ summary: "Your to-do list (the private schedule Workspace): list | add | done | undone | update | move | rm",
13452
+ 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.",
13453
+ positionals: [{ name: "action", description: "list | add | done | undone | update | move | rm", required: true }, { name: "title", description: "add: the title", required: false }],
13454
+ options: [
13455
+ ID,
13456
+ { name: "all", property: "all", description: "list: completed ones too", type: "boolean" },
13457
+ { name: "title", property: "new_title", description: "update: the new title", type: "string" },
13458
+ { name: "status", property: "status", description: "add / update / move: the status (board column) option id", type: "string" },
13459
+ { name: "due", property: "due", description: 'add / update: due date YYYY-MM-DD (update: "none" clears it)', type: "string" },
13460
+ { name: "priority", property: "priority", description: "add / update: low | normal | high | urgent | none", type: "string", enum: ["low", "normal", "high", "urgent", "none"] },
13461
+ { name: "before", property: "before", description: "add / move: place before this to-do id", type: "string" },
13462
+ { name: "after", property: "after", description: "add / move: place after this to-do id", type: "string" },
13463
+ { name: "ext", property: "ext", description: "add / update: extension fields JSON (merged on update; null removes a key)", type: "string" }
13464
+ ],
13465
+ inputSchema: {
13466
+ type: "object",
13467
+ 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" } },
13468
+ required: ["action"],
13469
+ additionalProperties: false
13470
+ },
13471
+ outputSchema: OBJECT_OUTPUT$2,
13367
13472
  resultSchemaVersion: 1,
13368
- access: { mode: "fixed", level: "read" },
13473
+ access: { mode: "fixed", level: "write" },
13369
13474
  asyncMode: "sync",
13370
13475
  requiresSession: true,
13371
- examples: ["buckyos aiws read orders --workspace ws_abc"],
13372
- handler: (ctx, input) => {
13373
- const selector = inputString(input, "selector");
13374
- return aiws(ctx, "doc.read", { workspace_id: requiredInputString(input, "workspace_id"), entity_id: requiredInputString(input, "entity_id"), ...selector ? { selector: JSON.parse(selector) } : {} });
13375
- }
13476
+ examples: [
13477
+ "buckyos aiws todo list",
13478
+ 'buckyos aiws todo add "Renew the passport" --due 2026-12-01 --priority high',
13479
+ "buckyos aiws todo done --id t…",
13480
+ "buckyos aiws todo move --id t… --status doing --before t…"
13481
+ ],
13482
+ handler: (ctx, input) => run(async () => {
13483
+ const s = schedule(ctx);
13484
+ const action = requiredInputString(input, "action");
13485
+ const id = () => requiredInputString(input, "id");
13486
+ const due = inputString(input, "due");
13487
+ if (due && due !== "none" && !DATE.test(due))
13488
+ throw new UsageError("AIWS_USAGE", "--due must be YYYY-MM-DD");
13489
+ const priority = inputString(input, "priority");
13490
+ switch (action) {
13491
+ case "list": {
13492
+ const handle = await s.ensure();
13493
+ const items = await s.todos({ includeDone: input.all === true });
13494
+ return { workspace_id: handle.workspace_id, table: handle.todo, items: items.map(todoView) };
13495
+ }
13496
+ case "add": {
13497
+ const title = requiredInputString(input, "title");
13498
+ const ext = { ...parseExt(input) ?? {}, ...priority && priority !== "none" ? { priority } : {} };
13499
+ const item = await s.addTodo({ title, status: inputString(input, "status") ?? void 0, due: due && due !== "none" ? due : void 0, ext }, { before: inputString(input, "before") ?? void 0, after: inputString(input, "after") ?? void 0 });
13500
+ return { item: todoView(item) };
13501
+ }
13502
+ case "done":
13503
+ case "undone":
13504
+ await s.completeTodo(id(), action === "done");
13505
+ return { ok: true, id: id(), done: action === "done" };
13506
+ case "update": {
13507
+ const ext = parseExt(input);
13508
+ const merge = { ...ext ?? {} };
13509
+ if (priority)
13510
+ merge.priority = priority === "none" ? null : priority;
13511
+ 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 } : {} });
13512
+ return { ok: true, id: id() };
13513
+ }
13514
+ case "move":
13515
+ await s.moveTodo(id(), { status: inputString(input, "status") ?? void 0, before: inputString(input, "before") ?? void 0, after: inputString(input, "after") ?? void 0 });
13516
+ return { ok: true, id: id() };
13517
+ case "rm": {
13518
+ const ids2 = id().split(",").map((x) => x.trim()).filter(Boolean);
13519
+ await s.removeTodos(ids2);
13520
+ return { ok: true, removed: ids2 };
13521
+ }
13522
+ default:
13523
+ throw new UsageError("AIWS_USAGE", `todo: unknown action ${action}`);
13524
+ }
13525
+ })
13376
13526
  };
13377
- const queryCommand = {
13378
- verb: "query",
13379
- summary: "Query the rows of a table (or through a saved view)",
13527
+ const SCOPE = { name: "scope", property: "scope", description: "A repeating event: one (only this occurrence, default) | following (this and later) | all", type: "string", enum: ["one", "following", "all"] };
13528
+ const calCommand = {
13529
+ verb: "cal",
13530
+ summary: "Your calendar (the private schedule Workspace): list | add | update | rm | skip | postpone",
13531
+ 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.",
13532
+ positionals: [{ name: "action", description: "list | add | update | rm | skip | postpone", required: true }, { name: "title", description: "add: the title", required: false }],
13380
13533
  options: [
13381
- WORKSPACE_OPTION,
13382
- { name: "source", property: "source_id", description: "Table entity id", type: "string" },
13383
- { name: "view", property: "view_id", description: "Table view (Block) id", type: "string" },
13384
- { name: "filter", property: "filter", description: "Filter JSON (README: doc.query)", type: "string" },
13385
- { name: "limit", property: "limit", description: "Rows per page (≤ 1000)", type: "integer" },
13386
- { name: "cursor", property: "cursor", description: "Continue from a previous page", type: "string" }
13534
+ { name: "id", property: "id", description: "Event id or occurrence id (`cal list` shows them)", type: "string" },
13535
+ { name: "from", property: "from", description: "list: first day YYYY-MM-DD (default today)", type: "string" },
13536
+ { name: "days", property: "days", description: "list: how many days (default 7, ≤ 366)", type: "integer" },
13537
+ { name: "start", property: "start", description: "add / update: start, RFC 3339 instant (timed) or YYYY-MM-DD (all-day)", type: "string" },
13538
+ { name: "end", property: "end", description: "add / update: end, same form as --start (all-day: the last day, inclusive)", type: "string" },
13539
+ { name: "title", property: "new_title", description: "update: the new title", type: "string" },
13540
+ { name: "rrule", property: "rrule", description: 'add / update: repeat rule, e.g. FREQ=WEEKLY;BYDAY=MO,WE ("none" stops repeating)', type: "string" },
13541
+ { name: "tz", property: "tz", description: "add: the IANA time zone a series repeats in (default this machine’s)", type: "string" },
13542
+ { name: "location", property: "location", description: "add / update: where", type: "string" },
13543
+ { name: "reminder", property: "reminder", description: "add: minutes before to remind, comma separated (e.g. 10,1440)", type: "string" },
13544
+ { name: "minutes", property: "minutes", description: "postpone: by how many minutes", type: "integer" },
13545
+ { name: "ext", property: "ext", description: "add / update: extension fields JSON (merged on update; null removes a key)", type: "string" },
13546
+ SCOPE
13387
13547
  ],
13388
- inputSchema: workspaceInput({ source_id: { type: "string" }, view_id: { type: "string" }, filter: { type: "string" }, limit: { type: "integer" }, cursor: { type: "string" } }),
13389
- outputSchema: OBJECT_OUTPUT,
13548
+ inputSchema: {
13549
+ type: "object",
13550
+ properties: {
13551
+ action: { type: "string", enum: ["list", "add", "update", "rm", "skip", "postpone"] },
13552
+ title: { type: "string" },
13553
+ id: { type: "string" },
13554
+ from: { type: "string" },
13555
+ days: { type: "integer" },
13556
+ start: { type: "string" },
13557
+ end: { type: "string" },
13558
+ new_title: { type: "string" },
13559
+ rrule: { type: "string" },
13560
+ tz: { type: "string" },
13561
+ location: { type: "string" },
13562
+ reminder: { type: "string" },
13563
+ minutes: { type: "integer" },
13564
+ ext: { type: "string" },
13565
+ scope: { type: "string", enum: ["one", "following", "all"] }
13566
+ },
13567
+ required: ["action"],
13568
+ additionalProperties: false
13569
+ },
13570
+ outputSchema: OBJECT_OUTPUT$2,
13390
13571
  resultSchemaVersion: 1,
13391
- access: { mode: "fixed", level: "read" },
13572
+ access: { mode: "fixed", level: "write" },
13392
13573
  asyncMode: "sync",
13393
13574
  requiresSession: true,
13394
- examples: ["buckyos aiws query --workspace ws_abc --source orders --limit 100"],
13395
- handler: (ctx, input) => {
13396
- const params = { workspace_id: requiredInputString(input, "workspace_id") };
13397
- for (const key of ["source_id", "view_id", "cursor"]) {
13398
- const value = inputString(input, key);
13399
- if (value)
13400
- params[key] = value;
13401
- }
13402
- const filter = inputString(input, "filter");
13403
- if (filter)
13404
- params.filter = JSON.parse(filter);
13405
- if (typeof input.limit === "number")
13406
- params.limit = input.limit;
13407
- if (!params.source_id && !params.view_id)
13408
- throw new UsageError("AIWS_USAGE", "pass --source or --view");
13409
- return aiws(ctx, "doc.query", params);
13410
- }
13575
+ examples: [
13576
+ "buckyos aiws cal list --days 14",
13577
+ '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"',
13578
+ 'buckyos aiws cal add "Trip" --start 2026-11-20 --end 2026-11-22',
13579
+ "buckyos aiws cal skip --id e…@2026-11-18T01:00:00.000Z",
13580
+ "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"
13581
+ ],
13582
+ handler: (ctx, input) => run(async () => {
13583
+ const s = schedule(ctx);
13584
+ const action = requiredInputString(input, "action");
13585
+ const tz = viewerTimeZone();
13586
+ const scope = inputString(input, "scope") ?? "one";
13587
+ const times = () => {
13588
+ const start = inputString(input, "start"), end = inputString(input, "end");
13589
+ if (!start && !end)
13590
+ return void 0;
13591
+ if (!start)
13592
+ throw new UsageError("AIWS_USAGE", "--end needs --start");
13593
+ if (DATE.test(start)) {
13594
+ const last = end ?? start;
13595
+ if (!DATE.test(last))
13596
+ throw new UsageError("AIWS_USAGE", "an all-day event takes dates for --start and --end");
13597
+ return { allDay: true, startDate: start, endDate: last };
13598
+ }
13599
+ const s0 = Date.parse(start);
13600
+ const e0 = end ? Date.parse(end) : s0 + 36e5;
13601
+ if (!Number.isFinite(s0) || !Number.isFinite(e0))
13602
+ throw new UsageError("AIWS_USAGE", "--start / --end must be RFC 3339 instants with an offset (or dates for all-day)");
13603
+ return { allDay: false, start: new Date(s0).toISOString(), end: new Date(e0).toISOString() };
13604
+ };
13605
+ switch (action) {
13606
+ case "list": {
13607
+ const handle = await s.ensure();
13608
+ const from = inputString(input, "from") ?? localDate(Date.now(), tz);
13609
+ if (!DATE.test(from))
13610
+ throw new UsageError("AIWS_USAGE", "--from must be YYYY-MM-DD");
13611
+ const days = typeof input.days === "number" ? Math.max(1, Math.min(366, input.days)) : 7;
13612
+ const fromMs = Date.parse(`${from}T00:00:00Z`) - 14 * 36e5;
13613
+ const window = { fromMs, toMs: fromMs + days * 864e5 + 28 * 36e5 };
13614
+ const rows = await s.rows(handle.calendar);
13615
+ const last = localDate(Date.parse(`${from}T12:00:00Z`) + (days - 1) * 864e5, "UTC");
13616
+ 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);
13617
+ return { workspace_id: handle.workspace_id, table: handle.calendar, from, days, time_zone: tz, events: occ.map(eventView) };
13618
+ }
13619
+ case "add": {
13620
+ const title = requiredInputString(input, "title");
13621
+ const t = times();
13622
+ if (!t)
13623
+ throw new UsageError("AIWS_USAGE", "add needs --start");
13624
+ const ext = { ...parseExt(input) ?? {} };
13625
+ const rrule = inputString(input, "rrule");
13626
+ if (rrule && rrule !== "none") {
13627
+ ext.rrule = rrule;
13628
+ ext.tz = inputString(input, "tz") ?? tz;
13629
+ }
13630
+ const location = inputString(input, "location");
13631
+ if (location)
13632
+ ext.location = location;
13633
+ const reminder = inputString(input, "reminder");
13634
+ if (reminder)
13635
+ ext.reminders = reminder.split(",").map((m) => ({ before_min: Number(m.trim()) })).filter((r) => Number.isFinite(r.before_min));
13636
+ const id = await s.addEvent(t.allDay ? { title, all_day: true, start_date: t.startDate, end_date: t.endDate, ext } : { title, start: t.start, end: t.end, ext });
13637
+ return { ok: true, id };
13638
+ }
13639
+ case "update": {
13640
+ const change = {};
13641
+ const t = times();
13642
+ if (t)
13643
+ change.times = t;
13644
+ const title = inputString(input, "new_title");
13645
+ if (title)
13646
+ change.values = { title };
13647
+ const merge = { ...parseExt(input) ?? {} };
13648
+ const location = inputString(input, "location");
13649
+ if (location !== void 0 && location !== null)
13650
+ merge.location = location || null;
13651
+ if (Object.keys(merge).length)
13652
+ change.ext_merge = merge;
13653
+ const rrule = inputString(input, "rrule");
13654
+ if (rrule)
13655
+ change.rrule = rrule === "none" ? null : rrule;
13656
+ const id = await s.editEvent(requiredInputString(input, "id"), change, scope);
13657
+ return { ok: true, id };
13658
+ }
13659
+ case "rm":
13660
+ await s.deleteEvent(requiredInputString(input, "id"), scope);
13661
+ return { ok: true };
13662
+ case "skip":
13663
+ await s.deleteEvent(requiredInputString(input, "id"), "one");
13664
+ return { ok: true };
13665
+ case "postpone": {
13666
+ const minutes = typeof input.minutes === "number" ? input.minutes : 0;
13667
+ if (minutes <= 0)
13668
+ throw new UsageError("AIWS_USAGE", "postpone needs --minutes");
13669
+ const { occ } = await s.occurrence(requiredInputString(input, "id"));
13670
+ const change = occ.allDay ? { 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))) } } : { times: { allDay: false, start: new Date(occ.startMs + minutes * 6e4).toISOString(), end: new Date(occ.endMs + minutes * 6e4).toISOString() } };
13671
+ const id = await s.editEvent(requiredInputString(input, "id"), change, "one");
13672
+ return { ok: true, id };
13673
+ }
13674
+ default:
13675
+ throw new UsageError("AIWS_USAGE", `cal: unknown action ${action}`);
13676
+ }
13677
+ })
13411
13678
  };
13412
- const infoCommand = {
13413
- verb: "info",
13414
- summary: "Workspace info: versions, capabilities of the caller, usage, hosted execution configuration",
13679
+ function shiftDate(date, days) {
13680
+ return new Date(Date.parse(`${date}T00:00:00Z`) + days * 864e5).toISOString().slice(0, 10);
13681
+ }
13682
+ const OBJECT_OUTPUT$1 = { type: "object", additionalProperties: true };
13683
+ const SERVICE$1 = "aiworkspace";
13684
+ const NOT_DATA = /* @__PURE__ */ new Set([
13685
+ "buckyos.cell",
13686
+ "buckyos.container",
13687
+ "buckyos.block-def",
13688
+ "buckyos.viewport",
13689
+ "buckyos.show-path"
13690
+ ]);
13691
+ const BUILTIN_SIZE = {
13692
+ todo: { w: 420, h: 520 },
13693
+ calendar: { w: 860, h: 620 }
13694
+ };
13695
+ function givenOnly(title) {
13696
+ return (ctx) => {
13697
+ const missing = Object.entries(ctx.decls).filter(
13698
+ ([name, d]) => d.required && ctx.given[name] === void 0
13699
+ ).map(([name]) => name);
13700
+ if (missing.length > 0) {
13701
+ throw new BindFailure(
13702
+ `${title} decides its data in its own script, which runs in a person's browser only: give ${missing.join(", ")} with --bind`,
13703
+ "NEEDS_UI",
13704
+ ctx.node,
13705
+ missing[0]
13706
+ );
13707
+ }
13708
+ return Promise.resolve({ bindings: ctx.given, create: [] });
13709
+ };
13710
+ }
13711
+ async function call(ctx, method, params) {
13712
+ const result = expectObject$4(await callService(ctx, SERVICE$1, method, params), method);
13713
+ if (result.ok === false) {
13714
+ const error = expectObject$4(result.error, `${method}.error`);
13715
+ const code = typeof error.code === "string" ? error.code : "AIWS_ERROR";
13716
+ throw new ToolError(code, `${code}: ${String(error.detail ?? code)}`, void 0, false, {
13717
+ ...error.sub_code ? { sub_code: error.sub_code } : {},
13718
+ ...error.data !== void 0 ? { data: error.data } : {}
13719
+ });
13720
+ }
13721
+ return result;
13722
+ }
13723
+ function parseBind(text2) {
13724
+ const out = {};
13725
+ for (const part of (text2 ?? "").split(";").map((s) => s.trim()).filter(Boolean)) {
13726
+ const at = part.indexOf("=");
13727
+ if (at <= 0)
13728
+ throw new UsageError("AIWS_USAGE", `--bind ${part}: name=id[,id]`);
13729
+ const ids2 = part.slice(at + 1).split(",").map((s) => s.trim()).filter(Boolean);
13730
+ out[part.slice(0, at).trim()] = ids2.length === 1 ? ids2[0] : ids2;
13731
+ }
13732
+ return out;
13733
+ }
13734
+ function freeName(taken, base) {
13735
+ let name = base;
13736
+ for (let n = 2; taken.has(name); n++)
13737
+ name = `${base} (${n})`;
13738
+ taken.add(name);
13739
+ return name;
13740
+ }
13741
+ const placeCommand = {
13742
+ verb: "place",
13743
+ summary: "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",
13744
+ description: "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.",
13745
+ positionals: [{
13746
+ name: "control",
13747
+ description: "todo | calendar | a definition id | <author_did>#<name>",
13748
+ required: true
13749
+ }],
13750
+ options: [
13751
+ {
13752
+ name: "workspace",
13753
+ property: "workspace_id",
13754
+ description: "Workspace id (ws_…)",
13755
+ type: "string",
13756
+ required: true
13757
+ },
13758
+ {
13759
+ name: "surface",
13760
+ property: "surface",
13761
+ description: "Canvas (Surface) id",
13762
+ type: "string",
13763
+ required: true
13764
+ },
13765
+ {
13766
+ name: "bind",
13767
+ property: "bind",
13768
+ description: 'Bindings you give: "name=id[,id];name=id"',
13769
+ type: "string"
13770
+ },
13771
+ { name: "title", property: "title", description: "Title of the control", type: "string" },
13772
+ {
13773
+ name: "at",
13774
+ property: "at",
13775
+ description: "Position x,y on a free canvas (default: right of what is on it)",
13776
+ type: "string"
13777
+ },
13778
+ {
13779
+ name: "config",
13780
+ property: "config",
13781
+ description: "Instance properties, a JSON object",
13782
+ type: "string"
13783
+ }
13784
+ ],
13785
+ inputSchema: {
13786
+ type: "object",
13787
+ properties: {
13788
+ control: { type: "string", minLength: 1 },
13789
+ workspace_id: { type: "string", minLength: 1 },
13790
+ surface: { type: "string", minLength: 1 },
13791
+ bind: { type: "string" },
13792
+ title: { type: "string" },
13793
+ at: { type: "string" },
13794
+ config: { type: "string" }
13795
+ },
13796
+ required: ["control", "workspace_id", "surface"],
13797
+ additionalProperties: false
13798
+ },
13799
+ outputSchema: OBJECT_OUTPUT$1,
13800
+ resultSchemaVersion: 1,
13801
+ access: { mode: "fixed", level: "write" },
13802
+ asyncMode: "sync",
13803
+ requiresSession: true,
13804
+ examples: [
13805
+ "buckyos aiws place todo --workspace ws_… --surface sf_…",
13806
+ 'buckyos aiws place calendar --workspace ws_… --surface sf_… --bind "events=t_cal"',
13807
+ 'buckyos aiws place did:bns:buckyos#photo-vote --workspace ws_… --surface sf_… --bind "photos=d_trip"'
13808
+ ],
13809
+ handler: async (ctx, input) => {
13810
+ const ws = requiredInputString(input, "workspace_id");
13811
+ const surfaceId = requiredInputString(input, "surface");
13812
+ const control = requiredInputString(input, "control");
13813
+ const info = await call(ctx, "ws.get_info", { workspace_id: ws });
13814
+ const entities = (await call(ctx, "doc.outline", { workspace_id: ws })).entities;
13815
+ const byId = new Map(entities.map((e) => [e.entity_id, e]));
13816
+ const surface = byId.get(surfaceId);
13817
+ if (!surface || surface.kind !== "surface") {
13818
+ throw new UsageError("AIWS_USAGE", `${surfaceId} is not a canvas of this workspace`);
13819
+ }
13820
+ const folderId = String(surface.content_folder_id ?? "");
13821
+ const config = inputString(input, "config") ? JSON.parse(inputString(input, "config")) : void 0;
13822
+ const right = entities.filter((e) => e.parent_id === surfaceId && !e.deleted).reduce(
13823
+ (max, e) => {
13824
+ const p = e.placement;
13825
+ return typeof p?.x === "number" ? Math.max(max, p.x + (typeof p.w === "number" ? p.w : 320)) : max;
13826
+ },
13827
+ 0
13828
+ );
13829
+ const at = inputString(input, "at") ? inputString(input, "at").split(",").map(Number) : [right > 0 ? right + 40 : 40, 40];
13830
+ let decls;
13831
+ let node = {};
13832
+ let op;
13833
+ let title = inputString(input, "title") ?? void 0;
13834
+ const id = `c${Math.random().toString(36).slice(2, 14)}`;
13835
+ if (control === "todo" || control === "calendar") {
13836
+ const contract = expectObject$4(
13837
+ (await call(ctx, "control.describe", { kind: control })).control,
13838
+ "control"
13839
+ ).contract;
13840
+ decls = contract.bindings ?? {};
13841
+ title ??= String(contract.title ?? control);
13842
+ const size = BUILTIN_SIZE[control];
13843
+ op = {
13844
+ op: "entity.create",
13845
+ entity_id: id,
13846
+ type_id: "buckyos.container",
13847
+ parent_id: surfaceId,
13848
+ placement: { x: at[0] || 40, y: at[1] || 40, ...size },
13849
+ payload: { kind: control, layout: { mode: "data" }, title }
13850
+ };
13851
+ } else {
13852
+ const def = entities.find(
13853
+ (e) => e.type_id === "buckyos.block-def" && !e.deleted && (e.entity_id === control || e.ident === control)
13854
+ );
13855
+ if (!def) {
13856
+ throw new UsageError(
13857
+ "AIWS_USAGE",
13858
+ `no control ${control} in this workspace (build or import it first)`
13859
+ );
13860
+ }
13861
+ const payload = (await call(ctx, "doc.read", { workspace_id: ws, entity_id: def.entity_id })).content.payload;
13862
+ decls = payload.bindings ?? {};
13863
+ title ??= String(payload.title ?? def.entity_id);
13864
+ node = payload.on_bind === "script" ? { onBind: givenOnly(title) } : payload.kind === "composite" ? { onBind: payload.on_bind, onInit: payload.on_init_control } : {};
13865
+ const size = payload.default_size ?? { w: 320, h: 240 };
13866
+ op = payload.kind === "composite" ? {
13867
+ op: "entity.create",
13868
+ entity_id: id,
13869
+ type_id: "buckyos.container",
13870
+ parent_id: surfaceId,
13871
+ placement: { x: at[0] || 40, y: at[1] || 40, w: "auto", h: "auto" },
13872
+ payload: {
13873
+ kind: "composite",
13874
+ def_ref: { entity_id: def.entity_id },
13875
+ ...config ? { config } : {}
13876
+ }
13877
+ } : {
13878
+ op: "entity.create",
13879
+ entity_id: id,
13880
+ type_id: "buckyos.cell",
13881
+ parent_id: surfaceId,
13882
+ placement: { x: at[0] || 40, y: at[1] || 40, ...size },
13883
+ payload: {
13884
+ view: { type: String(payload.kind) },
13885
+ def_ref: { entity_id: def.entity_id },
13886
+ ...config ? { config } : {}
13887
+ }
13888
+ };
13889
+ }
13890
+ const data = entities.filter((e) => !e.deleted && !NOT_DATA.has(e.type_id)).map((e) => ({
13891
+ entity_id: e.entity_id,
13892
+ type_id: e.type_id,
13893
+ schema_id: e.schema_id ?? null,
13894
+ title: e.title ?? e.name ?? null
13895
+ }));
13896
+ const outcome = await resolveBindings(
13897
+ {
13898
+ id,
13899
+ title,
13900
+ decls,
13901
+ given: parseBind(inputString(input, "bind") ?? void 0),
13902
+ children: [],
13903
+ ...node
13904
+ },
13905
+ {
13906
+ reason: "insert",
13907
+ no_ui: true,
13908
+ dialogs: noUiDialogs(),
13909
+ find: (q) => data.filter(
13910
+ (d) => (!q.accepts?.length || q.accepts.includes(d.type_id)) && (!q.schema_id || d.schema_id === q.schema_id) && (!q.ids || q.ids.includes(d.entity_id))
13911
+ )
13912
+ }
13913
+ );
13914
+ if (!outcome.ok) {
13915
+ throw new ToolError(
13916
+ outcome.error.code,
13917
+ `${outcome.error.code}: ${outcome.error.message}`,
13918
+ void 0,
13919
+ false,
13920
+ { ...outcome.error.binding ? { binding: outcome.error.binding } : {} }
13921
+ );
13922
+ }
13923
+ const children = entities.filter((e) => e.parent_id === folderId && !e.deleted);
13924
+ const taken = new Set(children.map((e) => String(e.name ?? "")).filter(Boolean));
13925
+ let last = children.map((e) => e.order_key ?? "").filter(Boolean).sort().at(-1) ?? null;
13926
+ const made = createOps(outcome.results, {
13927
+ folderId,
13928
+ newId: () => `d${Math.random().toString(36).slice(2, 14)}`,
13929
+ orderKey: () => {
13930
+ last = orderKeyBetween(last, null);
13931
+ return last;
13932
+ },
13933
+ freeName: (name) => freeName(taken, name),
13934
+ locale: /^zh/i.test(Intl.DateTimeFormat().resolvedOptions().locale) ? "zh" : "en"
13935
+ });
13936
+ const bindings = bindingsPayload(outcome.results.get(id).bindings, decls, made.ids);
13937
+ const lastOnCanvas = entities.filter((e) => e.parent_id === surfaceId && !e.deleted).map((e) => e.order_key ?? "").filter(Boolean).sort().at(-1) ?? null;
13938
+ op.order_key = orderKeyBetween(lastOnCanvas, null);
13939
+ if (Object.keys(bindings).length > 0) {
13940
+ op.payload.bindings = bindings;
13941
+ }
13942
+ const commit2 = await call(ctx, "doc.commit", {
13943
+ protocol_version: AIWS_PROTOCOL_VERSION,
13944
+ workspace_id: ws,
13945
+ epoch: info.epoch,
13946
+ idempotency_key: `place-${id}`,
13947
+ origin: "agent",
13948
+ message: `place ${title}`,
13949
+ operations: [...made.ops, op]
13950
+ });
13951
+ if (commit2.status !== "accepted") {
13952
+ throw new ToolError(
13953
+ "AIWS_COMMIT_REFUSED",
13954
+ `the placement was not accepted: ${JSON.stringify(commit2).slice(0, 500)}`
13955
+ );
13956
+ }
13957
+ return {
13958
+ entity_id: id,
13959
+ bindings,
13960
+ created: Object.values(made.ids),
13961
+ then: outcome.then.map((t) => t.action),
13962
+ commit_seq: commit2.seq ?? null
13963
+ };
13964
+ }
13965
+ };
13966
+ const SERVICE = "aiworkspace";
13967
+ const OBJECT_OUTPUT = { type: "object", additionalProperties: true };
13968
+ const WORKSPACE_OPTION = { name: "workspace", property: "workspace_id", description: "Workspace id (ws_…)", type: "string", required: true };
13969
+ const RUN_OPTION = { name: "run", property: "run_id", description: "Run id (run_…)", type: "string", required: true };
13970
+ const ATTEMPT_OPTION = { name: "attempt", property: "attempt", description: "The attempt number `run-claim` answered", type: "integer", required: true };
13971
+ function workspaceInput(extra, required = []) {
13972
+ return { type: "object", properties: { workspace_id: { type: "string", minLength: 1 }, ...extra }, required: ["workspace_id", ...required], additionalProperties: false };
13973
+ }
13974
+ async function aiws(ctx, method, params) {
13975
+ const result = expectObject$4(await callService(ctx, SERVICE, method, params), method);
13976
+ if (result.ok === false) {
13977
+ const error = expectObject$4(result.error, `${method}.error`);
13978
+ const code = typeof error.code === "string" ? error.code : "AIWS_ERROR";
13979
+ const detail = typeof error.detail === "string" ? error.detail : code;
13980
+ const details = {};
13981
+ if (typeof error.sub_code === "string")
13982
+ details.sub_code = error.sub_code;
13983
+ if (error.data !== void 0)
13984
+ details.data = error.data;
13985
+ throw new ToolError(code, `${code}${typeof error.sub_code === "string" ? `/${error.sub_code}` : ""}: ${detail}`, void 0, false, details);
13986
+ }
13987
+ return result;
13988
+ }
13989
+ async function jsonInput(input, textKey, fileKey, label) {
13990
+ const text2 = inputString(input, textKey);
13991
+ const file = inputString(input, fileKey);
13992
+ if (text2 && file)
13993
+ throw new UsageError("AIWS_USAGE", `${textKey} and ${fileKey} are exclusive`);
13994
+ if (file)
13995
+ return JSON.parse(await getHost().readTextFile(file));
13996
+ if (text2)
13997
+ return JSON.parse(text2);
13998
+ throw new UsageError("AIWS_USAGE", `${label}: pass --${textKey.replace(/_/g, "-")} or --${fileKey.replace(/_/g, "-")}`);
13999
+ }
14000
+ const PATH_HELP = "Path (/data/销售, ~<entity_id>/…) or entity id";
14001
+ const TYPE_OPTIONS = [
14002
+ { name: "type", property: "type", description: "Only these types, comma-separated: table, richtext, record, annotation, block, container (container:<kind>), asset, dir, wish, def, …", type: "string" },
14003
+ { name: "not-type", property: "not_type", description: "Leave these types out, comma-separated", type: "string" }
14004
+ ];
14005
+ const CURSOR_OPTION = { name: "cursor", property: "cursor", description: "Continue from the next_cursor of a previous page", type: "string" };
14006
+ const READ_ACCESS = { mode: "fixed", level: "read" };
14007
+ const WRITE_ACCESS = { mode: "fixed", level: "write" };
14008
+ function given(input, names) {
14009
+ const out = {};
14010
+ for (const [key, param] of Object.entries(names)) {
14011
+ const v = input[key];
14012
+ if (typeof v === "string" ? v.trim() !== "" : v !== void 0 && v !== false)
14013
+ out[param] = typeof v === "string" ? v.trim() : v;
14014
+ }
14015
+ return out;
14016
+ }
14017
+ function jsonArg(text2, label) {
14018
+ try {
14019
+ return JSON.parse(text2);
14020
+ } catch (error) {
14021
+ throw new UsageError("AIWS_USAGE", `${label}: ${error instanceof Error ? error.message : String(error)}`);
14022
+ }
14023
+ }
14024
+ const readCommand = {
14025
+ verb: "read",
14026
+ summary: "Read one entity of a workspace: envelope and native content",
14027
+ positionals: [{ name: "entity_id", description: PATH_HELP, required: true }],
14028
+ options: [WORKSPACE_OPTION, { name: "selector", property: "selector", description: 'Selector JSON, e.g. {"kind":"table_record","record_id":"r1"}', type: "string" }],
14029
+ inputSchema: workspaceInput({ entity_id: { type: "string", minLength: 1 }, selector: { type: "string" } }, ["entity_id"]),
14030
+ outputSchema: OBJECT_OUTPUT,
14031
+ resultSchemaVersion: 1,
14032
+ access: READ_ACCESS,
14033
+ asyncMode: "sync",
14034
+ requiresSession: true,
14035
+ examples: ["buckyos aiws read orders --workspace ws_abc", `buckyos aiws read /data/订单 --workspace ws_abc --selector '{"kind":"table_record","record_id":"r1"}'`],
14036
+ handler: (ctx, input) => {
14037
+ const selector = inputString(input, "selector");
14038
+ return aiws(ctx, "doc.read", { workspace_id: requiredInputString(input, "workspace_id"), ...aiwsTarget(requiredInputString(input, "entity_id")), ...selector ? { selector: jsonArg(selector, "--selector") } : {} });
14039
+ }
14040
+ };
14041
+ const lsCommand = {
14042
+ verb: "ls",
14043
+ summary: "The direct children of a path (default /), in tree order: name, path, type, title, children, body state",
14044
+ positionals: [{ name: "path", description: `${PATH_HELP} (default /)`, required: false }],
14045
+ 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],
14046
+ inputSchema: workspaceInput({ path: { type: "string" }, type: { type: "string" }, not_type: { type: "string" }, schema: { type: "string" }, limit: { type: "integer", minimum: 1 }, cursor: { type: "string" } }),
14047
+ outputSchema: OBJECT_OUTPUT,
14048
+ resultSchemaVersion: 1,
14049
+ access: READ_ACCESS,
14050
+ asyncMode: "sync",
14051
+ requiresSession: true,
14052
+ examples: ["buckyos aiws ls --workspace ws_abc", "buckyos aiws ls /data --workspace ws_abc --type table"],
14053
+ 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" }) })
14054
+ };
14055
+ const findCommand = {
14056
+ verb: "find",
14057
+ summary: "Entities whose name or title holds a literal (case-insensitive), by type and schema, walking down from a path",
14058
+ 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.",
14059
+ positionals: [{ name: "text", description: "Literal looked for in names and titles", required: false }],
14060
+ 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],
14061
+ 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" } }),
14062
+ outputSchema: OBJECT_OUTPUT,
14063
+ resultSchemaVersion: 1,
14064
+ access: READ_ACCESS,
14065
+ asyncMode: "sync",
14066
+ requiresSession: true,
14067
+ examples: ["buckyos aiws find 销售 --workspace ws_abc", "buckyos aiws find --workspace ws_abc --type table --at /data"],
14068
+ 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" }) })
14069
+ };
14070
+ const grepCommand = {
14071
+ verb: "grep",
14072
+ 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",
14073
+ 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.",
14074
+ positionals: [{ name: "text", description: "Literal to look for", required: true }],
14075
+ 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],
14076
+ 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"]),
14077
+ outputSchema: OBJECT_OUTPUT,
14078
+ resultSchemaVersion: 1,
14079
+ access: READ_ACCESS,
14080
+ asyncMode: "sync",
14081
+ requiresSession: true,
14082
+ examples: ["buckyos aiws grep 华东 --workspace ws_abc", 'buckyos aiws grep "Q4 plan" --workspace ws_abc --at /docs --type richtext'],
14083
+ 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" }) })
14084
+ };
14085
+ const SUBJECT_HELP = "A principal (user id, DID), @<group>, @all, @guest or @creator";
14086
+ const caps = (text2) => text2 ? ids(text2) : [];
14087
+ const aclCommand = {
14088
+ verb: "acl",
14089
+ 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)",
14090
+ 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.",
14091
+ positionals: [
14092
+ { name: "action", description: "ls | show | who | explain | groups | entries | audit", required: true },
14093
+ { name: "target", description: `show / explain: ${PATH_HELP} (default /); who: ${SUBJECT_HELP}`, required: false }
14094
+ ],
14095
+ options: [
14096
+ WORKSPACE_OPTION,
14097
+ { name: "principal", property: "principal", description: "explain: whose permissions (default: yours; another's needs manage)", type: "string" },
14098
+ { name: "expand", property: "expand", description: "show: list the members of each group", type: "boolean" },
14099
+ { name: "after", property: "after", description: "audit: records after this sequence number", type: "integer" },
14100
+ { name: "limit", property: "limit", description: "audit: at most this many records (≤ 1000)", type: "integer" }
14101
+ ],
14102
+ inputSchema: workspaceInput({
14103
+ action: { type: "string", enum: ["ls", "show", "who", "explain", "groups", "entries", "audit"] },
14104
+ target: { type: "string" },
14105
+ principal: { type: "string" },
14106
+ expand: { type: "boolean" },
14107
+ after: { type: "integer" },
14108
+ limit: { type: "integer", minimum: 1 }
14109
+ }, ["action"]),
14110
+ outputSchema: OBJECT_OUTPUT,
14111
+ resultSchemaVersion: 1,
14112
+ access: READ_ACCESS,
14113
+ asyncMode: "sync",
14114
+ requiresSession: true,
14115
+ examples: [
14116
+ "buckyos aiws acl show /data/成绩 --workspace ws_abc",
14117
+ "buckyos aiws acl explain /data/成绩 --principal bob --workspace ws_abc",
14118
+ "buckyos aiws acl who @teachers --workspace ws_abc",
14119
+ "buckyos aiws acl groups --workspace ws_abc"
14120
+ ],
14121
+ handler: (ctx, input) => {
14122
+ const workspace_id = requiredInputString(input, "workspace_id");
14123
+ const target = inputString(input, "target");
14124
+ switch (requiredInputString(input, "action")) {
14125
+ case "ls":
14126
+ return aiws(ctx, "acl.query", { workspace_id, by: "all" });
14127
+ case "show":
14128
+ return aiws(ctx, "acl.query", { workspace_id, by: "entity", resource: target ?? "/", ...given(input, { expand: "expand" }) });
14129
+ case "who":
14130
+ return aiws(ctx, "acl.query", { workspace_id, by: "subject", ...target ? { subject: target } : {} });
14131
+ case "explain":
14132
+ return aiws(ctx, "acl.query", { workspace_id, by: "explain", resource: target ?? "/", ...given(input, { principal: "principal" }) });
14133
+ case "groups":
14134
+ return aiws(ctx, "acl.groups", { workspace_id });
14135
+ case "entries":
14136
+ return aiws(ctx, "ws.list_entries", { workspace_id });
14137
+ case "audit":
14138
+ return aiws(ctx, "acl.audit", { workspace_id, ...given(input, { after: "after", limit: "limit" }) });
14139
+ default:
14140
+ throw new UsageError("AIWS_USAGE", "acl: ls, show, who, explain, groups, entries or audit");
14141
+ }
14142
+ }
14143
+ };
14144
+ const aclEditCommand = {
14145
+ verb: "acl-edit",
14146
+ 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>`",
14147
+ 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.",
14148
+ positionals: [
14149
+ { name: "action", description: "set | rm | group-add | group-rm | member-add | member-rm | anonymous | bind | entry-add | entry-close | publish | unpublish", required: true },
14150
+ { 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 },
14151
+ { name: "arg", description: `set / rm: ${PATH_HELP} (default /); member-*: members, comma-separated; bind: group id or none`, required: false }
14152
+ ],
14153
+ options: [
14154
+ WORKSPACE_OPTION,
14155
+ { name: "allow", property: "allow", description: "set: capabilities, comma-separated (read, append, update, delete, structure, comment, export, manage, run)", type: "string" },
14156
+ { name: "deny", property: "deny", description: "set: capabilities refused, comma-separated", type: "string" },
14157
+ { name: "title", property: "title", description: "group-add: the group's title", type: "string" },
14158
+ { name: "description", property: "description", description: "group-add: what the group is for", type: "string" },
14159
+ { name: "mode", property: "mode", description: "bind: union (default) or intersection with the triggerer's permissions", type: "string", enum: ["union", "intersection"] },
14160
+ { name: "methods", property: "methods", description: "entry-add: ways in, comma-separated: guest, password, self_register, did_login", type: "string" },
14161
+ { name: "expires-at", property: "expires_at", description: "entry-add: unix seconds", type: "integer" },
14162
+ { name: "max-joins", property: "max_joins", description: "entry-add: how many may join at most", type: "integer" },
14163
+ { name: "remove-members", property: "remove_members", description: "entry-close: those who joined through it leave the group too", type: "boolean" },
14164
+ { name: "name", property: "name", description: "publish: the last segment of the link", type: "string" }
14165
+ ],
14166
+ inputSchema: workspaceInput({
14167
+ action: { type: "string", enum: ["set", "rm", "group-add", "group-rm", "member-add", "member-rm", "anonymous", "bind", "entry-add", "entry-close", "publish", "unpublish"] },
14168
+ target: { type: "string" },
14169
+ arg: { type: "string" },
14170
+ allow: { type: "string" },
14171
+ deny: { type: "string" },
14172
+ title: { type: "string" },
14173
+ description: { type: "string" },
14174
+ mode: { type: "string", enum: ["union", "intersection"] },
14175
+ methods: { type: "string" },
14176
+ expires_at: { type: "integer" },
14177
+ max_joins: { type: "integer", minimum: 1 },
14178
+ remove_members: { type: "boolean" },
14179
+ name: { type: "string" }
14180
+ }, ["action"]),
14181
+ outputSchema: OBJECT_OUTPUT,
14182
+ resultSchemaVersion: 1,
14183
+ access: WRITE_ACCESS,
14184
+ asyncMode: "sync",
14185
+ requiresSession: true,
14186
+ examples: [
14187
+ "buckyos aiws acl-edit group-add teachers --title 老师 --workspace ws_abc",
14188
+ "buckyos aiws acl-edit member-add teachers group:staff,bob --workspace ws_abc",
14189
+ "buckyos aiws acl-edit set @teachers /data/成绩 --allow read,update --workspace ws_abc",
14190
+ "buckyos aiws acl-edit set @all /data/工资 --deny read --workspace ws_abc",
14191
+ "buckyos aiws acl-edit anonymous on --workspace ws_abc",
14192
+ "buckyos aiws acl-edit entry-add visitors --methods guest,password --workspace ws_abc"
14193
+ ],
14194
+ handler: async (ctx, input) => {
14195
+ const workspace_id = requiredInputString(input, "workspace_id");
14196
+ const target = () => requiredInputString(input, "target");
14197
+ const arg = inputString(input, "arg");
14198
+ const entityId = async (path) => String((await aiws(ctx, "doc.resolve", { workspace_id, ...path.startsWith("/") || path.startsWith("~") ? { path } : { reference: { entity_id: path, mode: "live" } } })).entity_id);
14199
+ switch (requiredInputString(input, "action")) {
14200
+ case "set":
14201
+ return aiws(ctx, "acl.set", { workspace_id, changes: [{ subject: target(), resource: arg ?? "/", allow: caps(inputString(input, "allow")), deny: caps(inputString(input, "deny")) }] });
14202
+ case "rm":
14203
+ return aiws(ctx, "acl.set", { workspace_id, changes: [{ subject: target(), resource: arg ?? "/" }] });
14204
+ case "group-add":
14205
+ return aiws(ctx, "acl.set_group", { workspace_id, group_id: target(), ...given(input, { title: "title", description: "description" }) });
14206
+ case "group-rm":
14207
+ return aiws(ctx, "acl.delete_group", { workspace_id, group_id: target() });
14208
+ case "member-add":
14209
+ return aiws(ctx, "acl.members", { workspace_id, group_id: target(), add: ids(arg ?? "") });
14210
+ case "member-rm":
14211
+ return aiws(ctx, "acl.members", { workspace_id, group_id: target(), remove: ids(arg ?? "") });
14212
+ case "anonymous": {
14213
+ const on = target();
14214
+ if (on !== "on" && on !== "off")
14215
+ throw new UsageError("AIWS_USAGE", "anonymous on | off");
14216
+ return aiws(ctx, "acl.set_anonymous", { workspace_id, enabled: on === "on" });
14217
+ }
14218
+ case "bind":
14219
+ return aiws(ctx, "acl.bind_macro", { workspace_id, wish: target(), group_id: !arg || arg === "none" ? null : arg, ...given(input, { mode: "mode" }) });
14220
+ case "entry-add": {
14221
+ const methods = Object.fromEntries(ids(requiredInputString(input, "methods")).map((m) => [m, true]));
14222
+ return aiws(ctx, "ws.create_entry", { workspace_id, group_id: target(), methods, ...given(input, { expires_at: "expires_at", max_joins: "max_joins" }) });
14223
+ }
14224
+ case "entry-close":
14225
+ return aiws(ctx, "ws.close_entry", { workspace_id, entry_id: target(), ...given(input, { remove_members: "remove_members" }) });
14226
+ case "publish":
14227
+ return aiws(ctx, "ws.publish", { workspace_id, entity_id: await entityId(target()), ...given(input, { name: "name" }) });
14228
+ case "unpublish":
14229
+ return aiws(ctx, "ws.unpublish", { workspace_id, entity_id: await entityId(target()) });
14230
+ default:
14231
+ 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");
14232
+ }
14233
+ }
14234
+ };
14235
+ const statCommand = {
14236
+ verb: "stat",
14237
+ 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",
14238
+ positionals: [{ name: "path", description: PATH_HELP, required: true }],
14239
+ options: [WORKSPACE_OPTION],
14240
+ inputSchema: workspaceInput({ path: { type: "string", minLength: 1 } }, ["path"]),
14241
+ outputSchema: OBJECT_OUTPUT,
14242
+ resultSchemaVersion: 1,
14243
+ access: READ_ACCESS,
14244
+ asyncMode: "sync",
14245
+ requiresSession: true,
14246
+ examples: ["buckyos aiws stat /data/销售 --workspace ws_abc"],
14247
+ handler: (ctx, input) => aiws(ctx, "doc.read", { workspace_id: requiredInputString(input, "workspace_id"), ...aiwsTarget(requiredInputString(input, "path")), as: "meta" })
14248
+ };
14249
+ const CAT_MAX_PAGES = 512;
14250
+ const catCommand = {
14251
+ verb: "cat",
14252
+ 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",
14253
+ 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.",
14254
+ positionals: [{ name: "path", description: PATH_HELP, required: true }],
14255
+ options: [
14256
+ WORKSPACE_OPTION,
14257
+ { name: "selector", property: "selector", description: 'Only this part, selector JSON, e.g. {"kind":"richtext_block","block_id":"b3"}', type: "string" },
14258
+ { name: "max-bytes", property: "max_bytes", description: "One page of at most this many bytes (64…262144)", type: "integer" },
14259
+ CURSOR_OPTION
14260
+ ],
14261
+ inputSchema: workspaceInput({ path: { type: "string", minLength: 1 }, selector: { type: "string" }, max_bytes: { type: "integer", minimum: 64 }, cursor: { type: "string" } }, ["path"]),
14262
+ outputSchema: OBJECT_OUTPUT,
14263
+ resultSchemaVersion: 1,
14264
+ access: READ_ACCESS,
14265
+ asyncMode: "sync",
14266
+ requiresSession: true,
14267
+ examples: ["buckyos aiws cat /docs/周报 --workspace ws_abc --output text", "buckyos aiws cat /data/销售 --workspace ws_abc --max-bytes 4096"],
14268
+ handler: async (ctx, input) => {
14269
+ const selector = inputString(input, "selector");
14270
+ const request = {
14271
+ workspace_id: requiredInputString(input, "workspace_id"),
14272
+ ...aiwsTarget(requiredInputString(input, "path")),
14273
+ as: "body",
14274
+ ...selector ? { selector: jsonArg(selector, "--selector") } : {},
14275
+ ...given(input, { max_bytes: "max_bytes" })
14276
+ };
14277
+ let page = await aiws(ctx, "doc.read", { ...request, ...given(input, { cursor: "cursor" }) });
14278
+ if (input.max_bytes !== void 0 || inputString(input, "cursor"))
14279
+ return page;
14280
+ let text2 = String(page.text ?? "");
14281
+ for (let n = 1; page.complete === false && typeof page.next_cursor === "string" && n < CAT_MAX_PAGES; n++) {
14282
+ page = await aiws(ctx, "doc.read", { ...request, cursor: page.next_cursor });
14283
+ text2 += String(page.text ?? "");
14284
+ }
14285
+ const { parts: _parts, ...last } = page;
14286
+ return { ...last, text: text2 };
14287
+ }
14288
+ };
14289
+ const resolveCommand = {
14290
+ verb: "resolve",
14291
+ summary: "A path (or entity id) as a reference: entity id, canonical reference, path and name",
14292
+ positionals: [{ name: "path", description: PATH_HELP, required: true }],
14293
+ options: [WORKSPACE_OPTION],
14294
+ inputSchema: workspaceInput({ path: { type: "string", minLength: 1 } }, ["path"]),
14295
+ outputSchema: OBJECT_OUTPUT,
14296
+ resultSchemaVersion: 1,
14297
+ access: READ_ACCESS,
14298
+ asyncMode: "sync",
14299
+ requiresSession: true,
14300
+ examples: ["buckyos aiws resolve /data/销售 --workspace ws_abc"],
14301
+ handler: (ctx, input) => {
14302
+ const target = aiwsTarget(requiredInputString(input, "path"));
14303
+ return aiws(ctx, "doc.resolve", { workspace_id: requiredInputString(input, "workspace_id"), ..."path" in target ? target : { reference: { entity_id: target.entity_id, mode: "live" } } });
14304
+ }
14305
+ };
14306
+ function tableAliases(text2) {
14307
+ const out = {};
14308
+ for (const pair of text2.split(/,(?=\s*[A-Za-z_][A-Za-z0-9_]*=)/)) {
14309
+ const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)=(.+?)\s*$/.exec(pair);
14310
+ if (!m)
14311
+ throw new UsageError("AIWS_USAGE", `--table ${pair}: <alias>=<path or entity id>`);
14312
+ out[m[1]] = m[2];
14313
+ }
14314
+ return out;
14315
+ }
14316
+ const sqlCommand = {
14317
+ verb: "sql",
14318
+ 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',
14319
+ 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).',
14320
+ positionals: [{ name: "sql", description: "The SELECT statement", required: true }],
14321
+ options: [
14322
+ WORKSPACE_OPTION,
14323
+ { name: "table", property: "table", description: "Aliases: alias=<path or entity id>[,alias=…]; only these tables are visible then", type: "string" },
14324
+ { name: "params", property: "params", description: "Positional parameters (?) as a JSON array", type: "string" },
14325
+ { name: "max-rows", property: "max_rows", description: "Rows at most (≤ 5000, default 1000)", type: "integer" }
14326
+ ],
14327
+ inputSchema: workspaceInput({ sql: { type: "string", minLength: 1 }, table: { type: "string" }, params: { type: "string" }, max_rows: { type: "integer", minimum: 1 } }, ["sql"]),
14328
+ outputSchema: OBJECT_OUTPUT,
14329
+ resultSchemaVersion: 1,
14330
+ access: READ_ACCESS,
14331
+ asyncMode: "sync",
14332
+ requiresSession: true,
14333
+ examples: [
14334
+ `buckyos aiws sql 'SELECT "客户", SUM("金额") AS total FROM "/data/销售" GROUP BY "客户" ORDER BY total DESC LIMIT 10' --workspace ws_abc`,
14335
+ `buckyos aiws sql 'SELECT "_id", "客户", "金额" FROM t WHERE "状态" = ? LIMIT 20' --table t=/data/销售 --params '["已完成"]' --workspace ws_abc`
14336
+ ],
14337
+ handler: (ctx, input) => {
14338
+ const table = inputString(input, "table");
14339
+ const params = inputString(input, "params");
14340
+ const values = params ? jsonArg(params, "--params") : void 0;
14341
+ if (values !== void 0 && !Array.isArray(values))
14342
+ throw new UsageError("AIWS_USAGE", "--params is a JSON array");
14343
+ return aiws(ctx, "doc.query", {
14344
+ workspace_id: requiredInputString(input, "workspace_id"),
14345
+ sql: requiredInputString(input, "sql"),
14346
+ ...table ? { tables: tableAliases(table) } : {},
14347
+ ...values ? { params: values } : {},
14348
+ ...given(input, { max_rows: "max_rows" })
14349
+ });
14350
+ }
14351
+ };
14352
+ function writeTransport(ctx) {
14353
+ return {
14354
+ call: async (method, params) => {
14355
+ const result = expectObject$4(await callService(ctx, SERVICE, method, params), method);
14356
+ if (result.ok === false) {
14357
+ const error = expectObject$4(result.error, `${method}.error`);
14358
+ 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 : void 0, data: error.data });
14359
+ }
14360
+ return result;
14361
+ }
14362
+ };
14363
+ }
14364
+ async function writing(work) {
14365
+ try {
14366
+ return await work();
14367
+ } catch (error) {
14368
+ if (error instanceof AiwsFailure)
14369
+ throw new ToolError(error.code, error.message, void 0, false, { ...error.subCode ? { sub_code: error.subCode } : {}, ...error.data !== void 0 ? { data: error.data } : {} });
14370
+ throw error;
14371
+ }
14372
+ }
14373
+ async function commit(ctx, ws, ops, message2) {
14374
+ const result = await commitOps(writeTransport(ctx), ws, ops, { message: message2, ...ctx.idempotencyKey ? { idempotencyKey: ctx.idempotencyKey } : {} });
14375
+ return { ok: true, status: result.status, commit_id: result.commit_id, seq: result.seq };
14376
+ }
14377
+ function envelopeOf(ctx, ws, target) {
14378
+ return aiws(ctx, "doc.read", { workspace_id: ws, ...aiwsTarget(target), selector: { kind: "doc_key", key: "title" } });
14379
+ }
14380
+ const ids = (text2) => text2.split(",").map((s) => s.trim()).filter(Boolean);
14381
+ async function markdownInput(input) {
14382
+ const text2 = typeof input.text === "string" ? input.text : void 0;
14383
+ const file = inputString(input, "file");
14384
+ if (text2 !== void 0 === (file !== void 0))
14385
+ throw new UsageError("AIWS_USAGE", "pass --file <md> or --text <markdown>");
14386
+ return file ? await getHost().readTextFile(file) : text2;
14387
+ }
14388
+ const tableCommand = {
14389
+ verb: "table",
14390
+ 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>`",
14391
+ 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.',
14392
+ positionals: [
14393
+ { name: "action", description: "add | set | rm | field-add | option-add", required: true },
14394
+ { name: "table", description: `The table: ${PATH_HELP}`, required: true },
14395
+ { name: "target", description: "set: record id; rm: record ids, comma-separated; option-add: field name", required: false },
14396
+ { name: "label", description: "option-add: the new option label", required: false }
14397
+ ],
14398
+ options: [
14399
+ WORKSPACE_OPTION,
14400
+ { name: "values", property: "values", description: "add / set: JSON keyed by field name", type: "string" },
14401
+ { name: "name", property: "name", description: "field-add: the field name", type: "string" },
14402
+ { 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"] },
14403
+ { name: "options", property: "options", description: "field-add: option labels of a select, a JSON array or comma-separated", type: "string" }
14404
+ ],
14405
+ inputSchema: workspaceInput({
14406
+ action: { type: "string", enum: ["add", "set", "rm", "field-add", "option-add"] },
14407
+ table: { type: "string", minLength: 1 },
14408
+ target: { type: "string" },
14409
+ label: { type: "string" },
14410
+ values: { type: "string" },
14411
+ name: { type: "string" },
14412
+ type: { type: "string" },
14413
+ options: { type: "string" }
14414
+ }, ["action", "table"]),
14415
+ outputSchema: OBJECT_OUTPUT,
14416
+ resultSchemaVersion: 1,
14417
+ access: WRITE_ACCESS,
14418
+ asyncMode: "sync",
14419
+ requiresSession: true,
14420
+ examples: [
14421
+ `buckyos aiws table add /data/销售 --values '{"客户":"ACME","金额":"1200.50","状态":"进行中"}' --workspace ws_abc`,
14422
+ `buckyos aiws table set /data/销售 r123 --values '{"状态":"已完成"}' --workspace ws_abc`,
14423
+ "buckyos aiws table rm /data/销售 r123,r124 --workspace ws_abc",
14424
+ "buckyos aiws table field-add /data/销售 --name 负责人 --type text --workspace ws_abc",
14425
+ "buckyos aiws table option-add /data/销售 状态 已取消 --workspace ws_abc"
14426
+ ],
14427
+ handler: (ctx, input) => writing(async () => {
14428
+ const ws = requiredInputString(input, "workspace_id");
14429
+ const action = requiredInputString(input, "action");
14430
+ const tablePath = requiredInputString(input, "table");
14431
+ const values = () => {
14432
+ const v = jsonArg(requiredInputString(input, "values"), "--values");
14433
+ if (!v || typeof v !== "object")
14434
+ throw new UsageError("AIWS_USAGE", "--values is a JSON object keyed by field name");
14435
+ return v;
14436
+ };
14437
+ if (action === "rm") {
14438
+ const records = ids(requiredInputString(input, "target"));
14439
+ const reads = await Promise.all(records.map((record_id) => aiws(ctx, "doc.read", { workspace_id: ws, ...aiwsTarget(tablePath), selector: { kind: "table_record", record_id } })));
14440
+ const table2 = String(reads[0].entity_id);
14441
+ return { ...await commit(ctx, ws, tableDelete(table2, records, reads), `delete ${records.length} record(s)`), table: table2, removed: records };
14442
+ }
14443
+ const table = await aiws(ctx, "doc.read", { workspace_id: ws, ...aiwsTarget(tablePath) });
14444
+ switch (action) {
14445
+ case "add": {
14446
+ const rows = values();
14447
+ const ops = tableInsert(table, Array.isArray(rows) ? rows : [rows]);
14448
+ const record_ids = (ops[0]?.records ?? []).map((r) => r.record_id);
14449
+ return { ...await commit(ctx, ws, ops, `add ${record_ids.length} record(s)`), table: table.entity_id, record_ids };
14450
+ }
14451
+ case "set": {
14452
+ const record_id = requiredInputString(input, "target");
14453
+ const v = values();
14454
+ if (Array.isArray(v))
14455
+ throw new UsageError("AIWS_USAGE", "set takes one --values object");
14456
+ const read2 = await aiws(ctx, "doc.read", { workspace_id: ws, entity_id: table.entity_id, selector: { kind: "table_record", record_id } });
14457
+ const ops = tableSet(table, record_id, v, read2);
14458
+ if (ops.length === 0)
14459
+ return { ok: true, status: "unchanged", table: table.entity_id, record_id };
14460
+ return { ...await commit(ctx, ws, ops, `update record ${record_id}`), table: table.entity_id, record_id };
14461
+ }
14462
+ case "field-add": {
14463
+ const options = inputString(input, "options");
14464
+ const labels = options === void 0 ? void 0 : options.startsWith("[") ? jsonArg(options, "--options") : ids(options);
14465
+ const op = fieldAdd(table, { name: requiredInputString(input, "name"), type: requiredInputString(input, "type"), ...labels ? { options: labels } : {} });
14466
+ const field = op.field;
14467
+ 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 } : {} };
14468
+ }
14469
+ case "option-add": {
14470
+ const op = optionAdd(table, requiredInputString(input, "target"), requiredInputString(input, "label"));
14471
+ return { ...await commit(ctx, ws, [op], `add option ${requiredInputString(input, "label")}`), table: table.entity_id, field_id: op.field_id, option: op.option };
14472
+ }
14473
+ default:
14474
+ throw new UsageError("AIWS_USAGE", `table: add, set, rm, field-add or option-add, not ${action}`);
14475
+ }
14476
+ })
14477
+ };
14478
+ const textCommand = {
14479
+ verb: "text",
14480
+ summary: "Write a rich text by blocks from Markdown: `append <doc> --file <md>`, `replace <doc> <block_id> --file <md>`, `rm <doc> <block_id>[,…]`",
14481
+ 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.",
14482
+ positionals: [
14483
+ { name: "action", description: "append | replace | rm", required: true },
14484
+ { name: "doc", description: `The rich text: ${PATH_HELP}`, required: true },
14485
+ { name: "block", description: "replace: block id; rm: block ids, comma-separated", required: false }
14486
+ ],
14487
+ options: [
14488
+ WORKSPACE_OPTION,
14489
+ { name: "file", property: "file", description: "append / replace: a local Markdown file", type: "string" },
14490
+ { name: "text", property: "text", description: "append / replace: the Markdown itself", type: "string" }
14491
+ ],
14492
+ 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"]),
14493
+ outputSchema: OBJECT_OUTPUT,
14494
+ resultSchemaVersion: 1,
14495
+ access: WRITE_ACCESS,
14496
+ asyncMode: "sync",
14497
+ requiresSession: true,
14498
+ examples: [
14499
+ "buckyos aiws text append /docs/周报 --file notes.md --workspace ws_abc",
14500
+ 'buckyos aiws text replace /docs/周报 b12 --text "## 下周计划" --workspace ws_abc',
14501
+ "buckyos aiws text rm /docs/周报 b12,b13 --workspace ws_abc"
14502
+ ],
14503
+ handler: (ctx, input) => writing(async () => {
14504
+ const ws = requiredInputString(input, "workspace_id");
14505
+ const action = requiredInputString(input, "action");
14506
+ const target = requiredInputString(input, "doc");
14507
+ if (action === "append") {
14508
+ const markdown2 = await markdownInput(input);
14509
+ const doc2 = String((await aiws(ctx, "doc.read", { workspace_id: ws, ...aiwsTarget(target), as: "meta" })).entity_id);
14510
+ const ops2 = textAppend(doc2, markdown2);
14511
+ const blocks = ops2[0].blocks.map((b) => b.attrs.block_id);
14512
+ return { ...await commit(ctx, ws, ops2, "append text"), doc: doc2, blocks };
14513
+ }
14514
+ if (action !== "replace" && action !== "rm")
14515
+ throw new UsageError("AIWS_USAGE", `text: append, replace or rm, not ${action}`);
14516
+ const markdown = action === "replace" ? await markdownInput(input) : "";
14517
+ const doc = await aiws(ctx, "doc.read", { workspace_id: ws, ...aiwsTarget(target) });
14518
+ if (action === "rm") {
14519
+ const blocks = ids(requiredInputString(input, "block"));
14520
+ return { ...await commit(ctx, ws, textDeleteBlocks(doc, blocks), `delete ${blocks.length} block(s)`), doc: doc.entity_id, removed: blocks };
14521
+ }
14522
+ const block = requiredInputString(input, "block");
14523
+ const ops = textReplaceBlock(doc, block, markdown);
14524
+ const added = ops.length > 1 ? ops[1].blocks.map((b) => b.attrs.block_id) : [];
14525
+ return { ...await commit(ctx, ws, ops, `replace block ${block}`), doc: doc.entity_id, blocks: [block, ...added] };
14526
+ })
14527
+ };
14528
+ const mvCommand = {
14529
+ verb: "mv",
14530
+ summary: "Move an entity under another parent, after its last child (a following name moves aside if taken there)",
14531
+ positionals: [{ name: "path", description: PATH_HELP, required: true }, { name: "parent", description: `The new parent: ${PATH_HELP}`, required: true }],
14532
+ options: [WORKSPACE_OPTION],
14533
+ inputSchema: workspaceInput({ path: { type: "string", minLength: 1 }, parent: { type: "string", minLength: 1 } }, ["path", "parent"]),
14534
+ outputSchema: OBJECT_OUTPUT,
14535
+ resultSchemaVersion: 1,
14536
+ access: WRITE_ACCESS,
14537
+ asyncMode: "sync",
14538
+ requiresSession: true,
14539
+ examples: ["buckyos aiws mv /data/草稿 /archive --workspace ws_abc"],
14540
+ handler: (ctx, input) => writing(async () => {
14541
+ const ws = requiredInputString(input, "workspace_id");
14542
+ const entity = await envelopeOf(ctx, ws, requiredInputString(input, "path"));
14543
+ const parent = String((await aiws(ctx, "doc.read", { workspace_id: ws, ...aiwsTarget(requiredInputString(input, "parent")), as: "meta" })).entity_id);
14544
+ let last;
14545
+ let cursor;
14546
+ for (let page = 0; page < 100; page++) {
14547
+ const listed = await aiws(ctx, "doc.list", { workspace_id: ws, at: parent, limit: 1e3, ...cursor ? { cursor } : {} });
14548
+ const items = Array.isArray(listed.items) ? listed.items : [];
14549
+ last = items.map((i) => i.entity_id).filter((id) => id !== entity.entity_id).at(-1) ?? last;
14550
+ if (typeof listed.next_cursor !== "string" || items.length === 0)
14551
+ break;
14552
+ cursor = listed.next_cursor;
14553
+ }
14554
+ const after = last ? (await envelopeOf(ctx, ws, last)).order_key : void 0;
14555
+ const op = move(entity, parent, typeof after === "string" ? after : null);
14556
+ return { ...await commit(ctx, ws, [op], `move ${entity.entity_id}`), entity_id: entity.entity_id, parent };
14557
+ })
14558
+ };
14559
+ const renameCommand = {
14560
+ verb: "rename",
14561
+ summary: "Give an entity a name of its own (its path segment), or --auto to let it follow its title again",
14562
+ positionals: [{ name: "path", description: PATH_HELP, required: true }, { name: "name", description: "The new name (1–128 characters, no /, not starting with ~)", required: false }],
14563
+ options: [WORKSPACE_OPTION, { name: "auto", property: "auto", description: "Name it after its title again (or a counter)", type: "boolean" }],
14564
+ inputSchema: workspaceInput({ path: { type: "string", minLength: 1 }, name: { type: "string" }, auto: { type: "boolean" } }, ["path"]),
14565
+ outputSchema: OBJECT_OUTPUT,
14566
+ resultSchemaVersion: 1,
14567
+ access: WRITE_ACCESS,
14568
+ asyncMode: "sync",
14569
+ requiresSession: true,
14570
+ examples: ["buckyos aiws rename /data/销售 销售-2026 --workspace ws_abc", "buckyos aiws rename ~sales --auto --workspace ws_abc"],
14571
+ handler: (ctx, input) => writing(async () => {
14572
+ const ws = requiredInputString(input, "workspace_id");
14573
+ const name = inputString(input, "name");
14574
+ if (name === void 0 === (input.auto !== true))
14575
+ throw new UsageError("AIWS_USAGE", "rename: pass a new name or --auto");
14576
+ const entity = await envelopeOf(ctx, ws, requiredInputString(input, "path"));
14577
+ return { ...await commit(ctx, ws, [rename(entity, name ?? null)], `rename ${entity.entity_id}`), entity_id: entity.entity_id, ...name ? { name } : {} };
14578
+ })
14579
+ };
14580
+ const setPropCommand = {
14581
+ verb: "set-prop",
14582
+ 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",
14583
+ positionals: [
14584
+ { name: "path", description: `The Block or container: ${PATH_HELP}`, required: true },
14585
+ { name: "key", description: "config | bindings | on", required: true },
14586
+ { name: "props", description: "JSON object { <name>: value | null }", required: true }
14587
+ ],
14588
+ options: [WORKSPACE_OPTION],
14589
+ inputSchema: workspaceInput({ path: { type: "string", minLength: 1 }, key: { type: "string", enum: ["config", "bindings", "on"] }, props: { type: "string", minLength: 1 } }, ["path", "key", "props"]),
14590
+ outputSchema: OBJECT_OUTPUT,
14591
+ resultSchemaVersion: 1,
14592
+ access: WRITE_ACCESS,
14593
+ asyncMode: "sync",
14594
+ requiresSession: true,
14595
+ examples: [`buckyos aiws set-prop /surfaces/看板/kpi config '{"label":"本月销售"}' --workspace ws_abc`],
14596
+ handler: (ctx, input) => writing(async () => {
14597
+ const ws = requiredInputString(input, "workspace_id");
14598
+ const key = requiredInputString(input, "key");
14599
+ if (key !== "config" && key !== "bindings" && key !== "on")
14600
+ throw new UsageError("AIWS_USAGE", "set-prop: the key is config, bindings or on");
14601
+ const props = jsonArg(requiredInputString(input, "props"), "props");
14602
+ if (!props || typeof props !== "object" || Array.isArray(props))
14603
+ throw new UsageError("AIWS_USAGE", "props is a JSON object { <name>: value | null }");
14604
+ const entity = await aiws(ctx, "doc.read", { workspace_id: ws, ...aiwsTarget(requiredInputString(input, "path")) });
14605
+ return { ...await commit(ctx, ws, [setProps(entity, key, props)], `set ${key} of ${entity.entity_id}`), entity_id: entity.entity_id };
14606
+ })
14607
+ };
14608
+ const infoCommand = {
14609
+ verb: "info",
14610
+ summary: "Workspace info: versions, capabilities of the caller, usage, hosted execution configuration",
13415
14611
  options: [WORKSPACE_OPTION],
13416
14612
  inputSchema: workspaceInput({}),
13417
14613
  outputSchema: OBJECT_OUTPUT,
@@ -13471,8 +14667,8 @@ const runHeartbeatCommand = {
13471
14667
  };
13472
14668
  const runFilesCommand = {
13473
14669
  verb: "run-files",
13474
- summary: "Write the stage of a claimed run into a directory: the snapshot (context/), request.json, the Renderer catalog and the program host (lib/)",
13475
- description: "Run the program there the way the service does: `deno run -A lib/run.js` reads program/main.js and writes output/.aiws/results.json.",
14670
+ 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",
14671
+ 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.",
13476
14672
  options: [WORKSPACE_OPTION, RUN_OPTION, ATTEMPT_OPTION, { name: "dir", property: "dir", description: "Directory to write into (created)", type: "string", required: true }],
13477
14673
  inputSchema: workspaceInput({ run_id: { type: "string", minLength: 1 }, attempt: { type: "integer", minimum: 1 }, dir: { type: "string", minLength: 1 } }, ["run_id", "attempt", "dir"]),
13478
14674
  outputSchema: { type: "object", properties: { dir: { type: "string" }, files: { type: "array", items: { type: "string" } } }, required: ["dir", "files"], additionalProperties: true },
@@ -13500,12 +14696,14 @@ const runFilesCommand = {
13500
14696
  }
13501
14697
  await host2.mkdir(`${dir}/output`, { recursive: true });
13502
14698
  await host2.mkdir(`${dir}/program`, { recursive: true });
14699
+ await host2.mkdir(`${dir}/lib`, { recursive: true });
14700
+ await host2.writeTextFile(`${dir}/lib/stage.json`, JSON.stringify(result.stage ?? {}));
13503
14701
  return { dir, files: written };
13504
14702
  }
13505
14703
  };
13506
14704
  const runToolCommand = {
13507
14705
  verb: "run-tool",
13508
- summary: "Call one stage tool of a claimed run (ws_profile, ws_read, ws_query, submit_analysis, put_result, check_results, finish, …): the service answers as it answers the model",
14706
+ 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",
13509
14707
  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" }],
13510
14708
  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"]),
13511
14709
  outputSchema: OBJECT_OUTPUT,
@@ -13519,35 +14717,179 @@ const runToolCommand = {
13519
14717
  return aiws(ctx, "proc.tool", { workspace_id: requiredInputString(input, "workspace_id"), run_id: requiredInputString(input, "run_id"), attempt: input.attempt, name: requiredInputString(input, "name"), args });
13520
14718
  }
13521
14719
  };
14720
+ const BRIDGE_PREFIX = "aiws ";
14721
+ const REFUSALS = {
14722
+ quota_exhausted: "AI_QUOTA_EXHAUSTED",
14723
+ quota_budget_exceeded: "AI_QUOTA_BUDGET_EXCEEDED",
14724
+ resource_not_permitted: "AI_RESOURCE_NOT_PERMITTED",
14725
+ attribution_unavailable: "AI_ATTRIBUTION_UNAVAILABLE",
14726
+ credentials: "AI_UNAVAILABLE"
14727
+ };
14728
+ function sessionInfer(ctx) {
14729
+ const call2 = async (method, params) => {
14730
+ try {
14731
+ return await ctx.clients.call("aicc", method, params, rpcOptions$2(ctx));
14732
+ } catch (error) {
14733
+ throw providerErrorFromRpc(`aicc ${method} failed`, error);
14734
+ }
14735
+ };
14736
+ const client = new AiccLlmClient({ chatCompletionsCreate: (r) => call2("chat.completions.create", r), helperLlmChat: (r) => call2("helper.llm_chat", r) });
14737
+ return async (req) => {
14738
+ try {
14739
+ const r = await client.infer({
14740
+ messages: req.messages.map((m) => ({ role: m.role, content: [{ type: "text", text: m.text }] })),
14741
+ model_alias: req.model,
14742
+ fallbacks: [],
14743
+ temperature: 0,
14744
+ max_completion_tokens: req.max_tokens,
14745
+ force_json: req.schema !== null,
14746
+ ...req.schema !== null ? { json_schema: req.schema } : {},
14747
+ disable_capabilities: [],
14748
+ tool_specs: [],
14749
+ allow_tool_calls: false,
14750
+ signal: ctx.signal
14751
+ });
14752
+ return { text: r.message.content.map((c) => c.type === "text" ? c.text ?? "" : "").join(""), tokens: r.usage?.output_tokens };
14753
+ } catch (error) {
14754
+ if (error instanceof LLMComputeException && error.error.kind === "provider" && typeof error.error.failure === "object" && "refused" in error.error.failure) {
14755
+ const e = new Error(error.message);
14756
+ e.code = REFUSALS[error.error.failure.refused.code] ?? "AI_QUOTA_EXHAUSTED";
14757
+ throw e;
14758
+ }
14759
+ throw error;
14760
+ }
14761
+ };
14762
+ }
14763
+ async function execMacro(ctx, input) {
14764
+ const host2 = getHost();
14765
+ const dir = await host2.realPath(host2.path.resolve(ctx.cwd, requiredInputString(input, "dir")));
14766
+ const ids2 = { workspace_id: requiredInputString(input, "workspace_id"), run_id: requiredInputString(input, "run_id"), attempt: input.attempt };
14767
+ const source = await host2.readTextFile(`${dir}/program/main.js`);
14768
+ let stage = {};
14769
+ try {
14770
+ stage = JSON.parse(await host2.readTextFile(`${dir}/lib/stage.json`));
14771
+ } catch {
14772
+ stage = {};
14773
+ }
14774
+ const budget = stage.budget ?? {};
14775
+ const manifest = stage.manifest && typeof stage.manifest === "object" ? stage.manifest : null;
14776
+ const { createBridgeHost } = await import(new URL(`file://${dir}/lib/host.js`).href);
14777
+ const origin = gatewayOrigin$2(ctx.connection.endpoint);
14778
+ const zoneHost = new URL(origin).hostname;
14779
+ const bridge = createBridgeHost({
14780
+ tool: async (name, args) => {
14781
+ try {
14782
+ return await aiws(ctx, "proc.tool", { ...ids2, name, args });
14783
+ } catch (error) {
14784
+ return { status: "error", text: error instanceof Error ? error.message : String(error) };
14785
+ }
14786
+ },
14787
+ infer: sessionInfer(ctx),
14788
+ zoneFetch: async (url, init) => {
14789
+ const res = await fetch(url, { method: init.method, headers: { ...init.headers, Authorization: `Bearer ${await sessionToken(ctx)}` }, body: init.body ?? void 0, signal: ctx.signal });
14790
+ const bytes = new Uint8Array(await res.arrayBuffer());
14791
+ const headers = {};
14792
+ res.headers.forEach((v, k) => {
14793
+ headers[k] = v;
14794
+ });
14795
+ try {
14796
+ return { status: res.status, headers, text: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
14797
+ } catch {
14798
+ return { status: res.status, headers, base64: btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join("")) };
14799
+ }
14800
+ },
14801
+ zoneHosts: [zoneHost],
14802
+ zoneOrigin: origin,
14803
+ budget,
14804
+ manifest
14805
+ });
14806
+ await host2.remove(`${dir}/output/.aiws/results.json`).catch(() => void 0);
14807
+ await host2.mkdir(`${dir}/output`, { recursive: true });
14808
+ const child = host2.spawn(host2.kind === "deno" ? host2.runtimeExecutable : "deno", [
14809
+ "run",
14810
+ "--no-prompt",
14811
+ "--quiet",
14812
+ "--no-remote",
14813
+ `--allow-read=${dir}`,
14814
+ `--allow-write=${dir}/output`,
14815
+ `--allow-net=${zoneHost}`,
14816
+ "lib/run.js",
14817
+ "--bridge"
14818
+ ], { cwd: dir, env: { NO_COLOR: "1", DENO_NO_UPDATE_CHECK: "1", DENO_DIR: `${dir}/.deno` } });
14819
+ const cap = Number(budget.program_timeout_secs) || 120;
14820
+ const limit = Math.min(cap, Number(manifest?.resources?.timeout_secs) || cap);
14821
+ let timedOut = false;
14822
+ const timer = setTimeout(() => {
14823
+ timedOut = true;
14824
+ child.kill();
14825
+ }, limit * 1e3);
14826
+ const out = [];
14827
+ try {
14828
+ for await (const line of child.lines()) {
14829
+ if (!line.startsWith(BRIDGE_PREFIX)) {
14830
+ out.push(line);
14831
+ continue;
14832
+ }
14833
+ const msg = JSON.parse(line.slice(BRIDGE_PREFIX.length));
14834
+ await child.writeLine(JSON.stringify({ id: msg.id, body: await bridge.handle(msg.op, msg.req) }));
14835
+ }
14836
+ } finally {
14837
+ clearTimeout(timer);
14838
+ await child.closeInput();
14839
+ }
14840
+ const code = await child.status;
14841
+ const log = [...out, await child.stderr, ...timedOut ? [`The macro timed out (${limit} s)`] : []].filter(Boolean).join("\n");
14842
+ let results = null;
14843
+ try {
14844
+ results = JSON.parse(await host2.readTextFile(`${dir}/output/.aiws/results.json`));
14845
+ } catch {
14846
+ results = null;
14847
+ }
14848
+ if (timedOut)
14849
+ results = { error: `The macro timed out (${limit} s)` };
14850
+ return { source, results, log, code };
14851
+ }
14852
+ const RUN_EXEC_OPTIONS = [
14853
+ WORKSPACE_OPTION,
14854
+ RUN_OPTION,
14855
+ ATTEMPT_OPTION,
14856
+ { 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 }
14857
+ ];
14858
+ 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"]);
14859
+ const runExecCommand = {
14860
+ verb: "run-exec",
14861
+ 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",
14862
+ 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).",
14863
+ options: RUN_EXEC_OPTIONS,
14864
+ inputSchema: RUN_EXEC_INPUT,
14865
+ outputSchema: OBJECT_OUTPUT,
14866
+ resultSchemaVersion: 1,
14867
+ access: { mode: "fixed", level: "write" },
14868
+ asyncMode: "sync",
14869
+ requiresSession: true,
14870
+ examples: ["buckyos aiws run-exec --workspace ws_abc --run run_xyz --attempt 1 --dir work"],
14871
+ handler: async (ctx, input) => {
14872
+ const run2 = await execMacro(ctx, input);
14873
+ const r = run2.results ?? {};
14874
+ return { exit_code: run2.code, error: r.error ?? null, error_code: r.error_code ?? null, ai: r.ai ?? null, declare: r.declare ?? null, log: run2.log };
14875
+ }
14876
+ };
13522
14877
  const runProgramCommand = {
13523
14878
  verb: "run-program",
13524
- summary: "Hand in a program run: the program source, what lib/run.js wrote to output/.aiws/results.json, the files under output/ and the log; the service validates it like its own run_program",
13525
- options: [
13526
- WORKSPACE_OPTION,
13527
- RUN_OPTION,
13528
- ATTEMPT_OPTION,
13529
- { name: "dir", property: "dir", description: "The stage directory written by run-files (program/main.js, output/)", type: "string", required: true },
13530
- { name: "log-file", property: "log_file", description: "Path of the program log to attach (stdout/stderr of deno run)", type: "string" }
13531
- ],
13532
- 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"]),
14879
+ 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",
14880
+ 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`.",
14881
+ options: RUN_EXEC_OPTIONS,
14882
+ inputSchema: RUN_EXEC_INPUT,
13533
14883
  outputSchema: OBJECT_OUTPUT,
13534
14884
  resultSchemaVersion: 1,
13535
14885
  access: { mode: "fixed", level: "write" },
13536
14886
  asyncMode: "sync",
13537
14887
  requiresSession: true,
13538
- examples: ["buckyos aiws run-program --workspace ws_abc --run run_xyz --attempt 1 --dir work --log-file work/run.log"],
14888
+ examples: ["buckyos aiws run-program --workspace ws_abc --run run_xyz --attempt 1 --dir work"],
13539
14889
  handler: async (ctx, input) => {
13540
- const dir = requiredInputString(input, "dir");
13541
14890
  const host2 = getHost();
13542
- const source = await host2.readTextFile(`${dir}/program/main.js`);
13543
- let results = null;
13544
- try {
13545
- results = JSON.parse(await host2.readTextFile(`${dir}/output/.aiws/results.json`));
13546
- } catch {
13547
- results = null;
13548
- }
13549
- const logFile = inputString(input, "log_file");
13550
- const log = logFile ? await host2.readTextFile(logFile).catch(() => "") : "";
14891
+ const dir = host2.path.resolve(ctx.cwd, requiredInputString(input, "dir"));
14892
+ const run2 = await execMacro(ctx, input);
13551
14893
  const files = {};
13552
14894
  const walk = async (rel) => {
13553
14895
  for (const entry of await host2.readDir(`${dir}/output${rel ? `/${rel}` : ""}`)) {
@@ -13569,27 +14911,48 @@ const runProgramCommand = {
13569
14911
  }
13570
14912
  };
13571
14913
  await walk("");
13572
- return aiws(ctx, "proc.program", { workspace_id: requiredInputString(input, "workspace_id"), run_id: requiredInputString(input, "run_id"), attempt: input.attempt, source, results, log, files });
14914
+ return aiws(ctx, "proc.program", { workspace_id: requiredInputString(input, "workspace_id"), run_id: requiredInputString(input, "run_id"), attempt: input.attempt, source: run2.source, results: run2.results, log: run2.log, files });
13573
14915
  }
13574
14916
  };
14917
+ const runStartCommand = {
14918
+ verb: "run-start",
14919
+ 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",
14920
+ 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.",
14921
+ options: [
14922
+ WORKSPACE_OPTION,
14923
+ { name: "wish", property: "wish_id", description: "The wish (its entity id)", type: "string", required: true },
14924
+ { name: "stage", property: "stage", description: "analyze | code | run (default analyze)", type: "string" }
14925
+ ],
14926
+ inputSchema: workspaceInput({ wish_id: { type: "string", minLength: 1 }, stage: { type: "string", enum: ["analyze", "code", "run"] } }, ["wish_id"]),
14927
+ outputSchema: OBJECT_OUTPUT,
14928
+ resultSchemaVersion: 1,
14929
+ access: { mode: "fixed", level: "write" },
14930
+ asyncMode: "sync",
14931
+ requiresSession: true,
14932
+ examples: ["buckyos aiws run-start --workspace ws_abc --wish wish_q3 --stage analyze"],
14933
+ handler: (ctx, input) => aiws(ctx, "proc.start", {
14934
+ workspace_id: requiredInputString(input, "workspace_id"),
14935
+ program: "wish.xllm@1",
14936
+ idempotency_key: ctx.idempotencyKey ?? `cli-${ctx.traceId}`,
14937
+ params: { wish_id: requiredInputString(input, "wish_id"), stage: inputString(input, "stage") || "analyze", execution: { mode: "local" } }
14938
+ })
14939
+ };
13575
14940
  const runReportCommand = {
13576
14941
  verb: "run-report",
13577
- summary: "End a claimed run: --finished after the stage tools accepted the work (submit_analysis / finish), or the candidate itself (results / analysis), or a failure",
13578
- description: "The service validates and plans what is reported; the user confirms it in the workspace. A superseded attempt or a cancelled run gets RUN_REVOKED.",
14942
+ 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",
14943
+ 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.",
13579
14944
  options: [
13580
14945
  WORKSPACE_OPTION,
13581
14946
  RUN_OPTION,
13582
14947
  ATTEMPT_OPTION,
13583
- { name: "finished", property: "finished", description: "The stage is done: what the tools collected becomes the candidate", type: "boolean" },
13584
- { name: "results", property: "results", description: "Results JSON array (execute runs): [{ name, type, title?, content, config? }]", type: "string" },
13585
- { name: "results-file", property: "results_file", description: "Path of a JSON file holding the results array", type: "string" },
13586
- { name: "analysis", property: "analysis", description: "Analysis JSON (analyze runs, wish.analysis.v2)", type: "string" },
14948
+ { name: "finished", property: "finished", description: "The stage is done: what it collected becomes the candidate", type: "boolean" },
14949
+ { name: "analysis", property: "analysis", description: "Analysis JSON (analyze runs, wish.analysis.v3)", type: "string" },
13587
14950
  { name: "analysis-file", property: "analysis_file", description: "Path of a JSON file holding the analysis", type: "string" },
13588
14951
  { name: "summary", property: "summary", description: "One paragraph on what was done", type: "string" },
13589
14952
  { name: "warning", property: "warnings", description: "A warning for the user (repeatable)", type: "string" },
13590
14953
  { name: "error", property: "error", description: "Report a failure instead: its reason", type: "string" }
13591
14954
  ],
13592
- inputSchema: workspaceInput({ run_id: { type: "string", minLength: 1 }, attempt: { type: "integer", minimum: 1 }, finished: { type: "boolean" }, results: { type: "string" }, results_file: { type: "string" }, analysis: { type: "string" }, analysis_file: { type: "string" }, summary: { type: "string" }, warnings: { type: "string" }, error: { type: "string" } }, ["run_id", "attempt"]),
14955
+ 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"]),
13593
14956
  outputSchema: OBJECT_OUTPUT,
13594
14957
  resultSchemaVersion: 1,
13595
14958
  access: { mode: "fixed", level: "write" },
@@ -13597,7 +14960,6 @@ const runReportCommand = {
13597
14960
  requiresSession: true,
13598
14961
  examples: [
13599
14962
  "buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --finished",
13600
- 'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --results-file out/results.json --summary "monthly totals and a commentary"',
13601
14963
  "buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --analysis-file out/analysis.json",
13602
14964
  'buckyos aiws run-report --workspace ws_abc --run run_xyz --attempt 1 --error "the input table is empty"'
13603
14965
  ],
@@ -13608,11 +14970,8 @@ const runReportCommand = {
13608
14970
  params.error = { code: "EXECUTOR_FAILED", detail: error };
13609
14971
  } else if (input.finished === true) {
13610
14972
  params.finished = true;
13611
- } else if (inputString(input, "analysis") || inputString(input, "analysis_file")) {
13612
- params.analysis = await jsonInput(input, "analysis", "analysis_file", "an analysis");
13613
14973
  } else {
13614
- params.results = await jsonInput(input, "results", "results_file", "results");
13615
- params.read_set = [];
14974
+ params.analysis = await jsonInput(input, "analysis", "analysis_file", "an analysis");
13616
14975
  }
13617
14976
  const summary2 = inputString(input, "summary");
13618
14977
  if (summary2)
@@ -13746,9 +15105,9 @@ function assetFetcher(ctx) {
13746
15105
  return new Uint8Array(await response.arrayBuffer());
13747
15106
  };
13748
15107
  }
13749
- async function sourceErrors(run) {
15108
+ async function sourceErrors(run2) {
13750
15109
  try {
13751
- return await run();
15110
+ return await run2();
13752
15111
  } catch (error) {
13753
15112
  if (error instanceof AiwsSourceError)
13754
15113
  throw new ToolError("BUILD_FAILED", `BUILD_FAILED: ${error.message}`, void 0, false, { data: { diagnostics: error.diagnostics } });
@@ -14337,8 +15696,8 @@ const templateCommand = {
14337
15696
  function createAiwsModule() {
14338
15697
  return {
14339
15698
  name: "aiws",
14340
- 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)",
14341
- commands: [infoCommand, readCommand, queryCommand, controlsCommand, importCommand, exportCommand, buildCommand, pullCommand, extExportCommand, libraryCommand, extImportCommand, extUpgradeCommand, templateCommand, runGetCommand, runClaimCommand, runHeartbeatCommand, runFilesCommand, runToolCommand, runProgramCommand, runReportCommand]
15699
+ 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)",
15700
+ 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]
14342
15701
  };
14343
15702
  }
14344
15703
  const VERSION = TOOL_VERSION;
@@ -14819,6 +16178,24 @@ async function runCli(host2, argv) {
14819
16178
  installHost(host2);
14820
16179
  return await new BuckyOSToolApplication().run(argv);
14821
16180
  }
16181
+ async function retryWindowsLock(windows, operation2, retryable, wait = defaultWait) {
16182
+ let attempt = 0;
16183
+ while (true) {
16184
+ try {
16185
+ return await operation2();
16186
+ } catch (error) {
16187
+ const delay = windows && retryable(error) ? wait(attempt) : 0;
16188
+ if (delay <= 0)
16189
+ throw error;
16190
+ attempt++;
16191
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
16192
+ }
16193
+ }
16194
+ }
16195
+ function defaultWait(attempt) {
16196
+ const waits = [50, 100, 150, 250, 400, 600, 800];
16197
+ return waits[attempt] ?? 0;
16198
+ }
14822
16199
  async function assertPathAccess(policy2, path, realPath, candidate, operation2, resolveLinks = true) {
14823
16200
  const roots = operation2 === "read" ? policy2.readPaths : policy2.writePaths;
14824
16201
  const absolute = path.resolve(candidate);
@@ -14985,7 +16362,11 @@ class NodeHost {
14985
16362
  await this.assertPath(from, "write");
14986
16363
  await this.assertPath(to, "write");
14987
16364
  try {
14988
- await rename(from, to);
16365
+ await retryWindowsLock(
16366
+ this.platform === "windows",
16367
+ () => rename$1(from, to),
16368
+ nodeSharingViolation
16369
+ );
14989
16370
  } catch (error) {
14990
16371
  throw translateNodeError(error, `${from} -> ${to}`);
14991
16372
  }
@@ -14993,7 +16374,11 @@ class NodeHost {
14993
16374
  async remove(path, options = {}) {
14994
16375
  await this.assertPath(path, "write", false);
14995
16376
  try {
14996
- await rm(path, { recursive: options.recursive ?? false });
16377
+ await retryWindowsLock(
16378
+ this.platform === "windows",
16379
+ () => rm(path, { recursive: options.recursive ?? false }),
16380
+ nodeSharingViolation
16381
+ );
14997
16382
  } catch (error) {
14998
16383
  throw translateNodeError(error, path);
14999
16384
  }
@@ -15072,6 +16457,40 @@ class NodeHost {
15072
16457
  this.assertCommand(command2);
15073
16458
  return await capture(command2, args);
15074
16459
  }
16460
+ spawn(command2, args, options) {
16461
+ this.assertCommand(command2);
16462
+ const resolved = command2.includes(nodePath.sep) ? command2 : (process.env.PATH ?? "").split(nodePath.delimiter).map((dir) => nodePath.join(dir, command2)).find((p) => existsSync(p)) ?? command2;
16463
+ const child = spawn(resolved, args, { cwd: options.cwd, env: options.env, stdio: ["pipe", "pipe", "pipe"], shell: false });
16464
+ const errChunks = [];
16465
+ child.stderr.on("data", (chunk) => errChunks.push(new Uint8Array(chunk)));
16466
+ const status = childStatus(child);
16467
+ return {
16468
+ async *lines() {
16469
+ let buf = "";
16470
+ for await (const chunk of child.stdout) {
16471
+ buf += new TextDecoder().decode(chunk, { stream: true });
16472
+ let i;
16473
+ while ((i = buf.indexOf("\n")) >= 0) {
16474
+ yield buf.slice(0, i);
16475
+ buf = buf.slice(i + 1);
16476
+ }
16477
+ }
16478
+ if (buf)
16479
+ yield buf;
16480
+ },
16481
+ writeLine: (line) => new Promise((resolve2) => {
16482
+ child.stdin.write(line + "\n", () => resolve2());
16483
+ }),
16484
+ closeInput: () => new Promise((resolve2) => {
16485
+ child.stdin.end(() => resolve2());
16486
+ }),
16487
+ stderr: status.then(() => new TextDecoder().decode(concat(errChunks))),
16488
+ status,
16489
+ kill: () => {
16490
+ child.kill("SIGKILL");
16491
+ }
16492
+ };
16493
+ }
15075
16494
  async runGzip(command2, args, destination) {
15076
16495
  this.assertCommand(command2);
15077
16496
  await this.assertPath(destination, "write", false);
@@ -15311,6 +16730,10 @@ async function readInputChunk() {
15311
16730
  process.stdin.once("error", onError);
15312
16731
  });
15313
16732
  }
16733
+ function nodeSharingViolation(error) {
16734
+ const code = error.code;
16735
+ return code === "EPERM" || code === "EACCES" || code === "EBUSY";
16736
+ }
15314
16737
  function translateNodeError(error, path) {
15315
16738
  if (error instanceof HostError)
15316
16739
  return error;
@@ -15329,6 +16752,7 @@ const environment = Object.fromEntries(
15329
16752
  TOOL_ENVIRONMENT_NAMES.map((name) => [name, process.env[name]])
15330
16753
  );
15331
16754
  const policy = buildDistributionPolicy({
16755
+ runtimeExecutable: "deno",
15332
16756
  distribution: "developer",
15333
16757
  argv: process.argv.slice(2),
15334
16758
  cwd: process.cwd(),