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
@@ -1,9 +1,20 @@
1
1
  import type { CommandContext } from '../core/context.ts'
2
2
  import type { CommandModule } from '../core/command.ts'
3
3
  import { EXIT_PERMISSION, EXIT_UNAVAILABLE, ToolError, UsageError } from '../core/errors.ts'
4
- import { AIWS_MANIFEST_FILE, AIWS_MANIFEST_VERSION, aiwsContentDigest, controlSkeleton } from 'buckyos/node'
4
+ import {
5
+ AIWS_MANIFEST_FILE,
6
+ AIWS_MANIFEST_VERSION,
7
+ aiwsContentDigest,
8
+ controlSkeleton,
9
+ } from 'buckyos/node'
5
10
  import { createDeterministicTarGz, digestFile, readTarGz, sha256Bytes } from './pikg_archive.ts'
6
- import { lintSkillPackage, readSkillDirectory, SKILL_DIRS, skillContentDigest, type SkillPackageFile } from './skill_lint.ts'
11
+ import {
12
+ lintSkillPackage,
13
+ readSkillDirectory,
14
+ SKILL_DIRS,
15
+ skillContentDigest,
16
+ type SkillPackageFile,
17
+ } from './skill_lint.ts'
7
18
  import {
8
19
  APPDOC_ENTRY,
9
20
  appDocObjectId,
@@ -18,11 +29,11 @@ import {
18
29
  EXT_TOOLS_MANIFEST_FILE,
19
30
  EXT_TOOLS_MANIFEST_SCHEMA,
20
31
  EXT_TOOLS_PLATFORMS,
32
+ type ExtToolsManifest,
21
33
  extToolsManifestErrors,
22
34
  extToolsPayloadErrors,
23
- extToolsPlatformOfKey,
24
- type ExtToolsManifest,
25
35
  type ExtToolsPayloadTree,
36
+ extToolsPlatformOfKey,
26
37
  inspectPikg,
27
38
  normalizeArch,
28
39
  PACKAGE_META_ENTRY,
@@ -32,9 +43,9 @@ import {
32
43
  parsePackageMeta,
33
44
  rejectUnknown,
34
45
  stableJsonDigest,
35
- validatePermissions,
36
46
  validateAppPresentation,
37
47
  validateContentHandlers,
48
+ validatePermissions,
38
49
  validateServiceConfigTips,
39
50
  validateSnapshot,
40
51
  validateSubpackageName,
@@ -198,7 +209,8 @@ export function createPikgModule(dependencies: PikgModuleDependencies = {}): Com
198
209
  options: [
199
210
  {
200
211
  name: 'catalog',
201
- description: 'ext-tools: a directory of other packages (<id>/ext-manifest.json) to check requires and same-named commands against',
212
+ description:
213
+ 'ext-tools: a directory of other packages (<id>/ext-manifest.json) to check requires and same-named commands against',
202
214
  type: 'string',
203
215
  },
204
216
  ],
@@ -249,7 +261,8 @@ export function createPikgModule(dependencies: PikgModuleDependencies = {}): Com
249
261
  { name: 'app-did', property: 'app_did', description: 'Explicit App DID', type: 'string' },
250
262
  {
251
263
  name: 'composite',
252
- description: 'aiws-controls: start the package with a composite control (a panel of Blocks) instead of a declarative one',
264
+ description:
265
+ 'aiws-controls: start the package with a composite control (a panel of Blocks) instead of a declarative one',
253
266
  type: 'boolean',
254
267
  },
255
268
  ],
@@ -441,12 +454,22 @@ async function doctorCommand(
441
454
  missing: missingSources,
442
455
  })
443
456
  const skills = pikg.sub_pkgs[PATH_KINDS['agent-skills'].key]
444
- if (skills?.source.type === 'path' && !missingSources.includes(resolve(metaDir, skills.source.path))) {
457
+ if (
458
+ skills?.source.type === 'path' &&
459
+ !missingSources.includes(resolve(metaDir, skills.source.path))
460
+ ) {
445
461
  checks.push(await skillLintCheck(app.name, resolve(metaDir, skills.source.path)))
446
462
  }
447
463
  if (app.categories[0] === PATH_KINDS['ext-tools'].category) {
448
464
  const catalog = optionalInputString(input, 'catalog')
449
- checks.push(...await extToolsChecks(app, pikg, metaDir, catalog ? resolveFromCwd(ctx, catalog) : undefined))
465
+ checks.push(
466
+ ...await extToolsChecks(
467
+ app,
468
+ pikg,
469
+ metaDir,
470
+ catalog ? resolveFromCwd(ctx, catalog) : undefined,
471
+ ),
472
+ )
450
473
  }
451
474
  } catch (error) {
452
475
  checks.push({
@@ -522,9 +545,15 @@ async function initCommand(
522
545
  selector = platform.selector
523
546
  sourceValue = {
524
547
  type: 'path',
525
- path: toPortablePath(relative(join(projectDir, 'dapp_meta'), join(absoluteSource, 'payload', platform.name))),
548
+ path: toPortablePath(
549
+ relative(join(projectDir, 'dapp_meta'), join(absoluteSource, 'payload', platform.name)),
550
+ ),
551
+ }
552
+ sourceSummary = {
553
+ type: 'path',
554
+ path: displaySource(projectDir, absoluteSource),
555
+ platform: platform.name,
526
556
  }
527
- sourceSummary = { type: 'path', path: displaySource(projectDir, absoluteSource), platform: platform.name }
528
557
  try {
529
558
  await getHost().lstat(join(absoluteSource, EXT_TOOLS_MANIFEST_FILE))
530
559
  } catch (error) {
@@ -631,7 +660,10 @@ const MAX_SKILL_SOURCE_BYTES = 64 * 1024 * 1024
631
660
 
632
661
  /** `pikg doctor` of an `agent_skills` source (a directory or a `.tar.gz`): the checks the Agent makes when the package is
633
662
  * installed. What makes it uninstallable fails the check; the rest are warnings. */
634
- async function skillLintCheck(packageName: string, source: string): Promise<Record<string, unknown>> {
663
+ async function skillLintCheck(
664
+ packageName: string,
665
+ source: string,
666
+ ): Promise<Record<string, unknown>> {
635
667
  const check = { name: 'skill_lint', path: source }
636
668
  let files: Map<string, SkillPackageFile>
637
669
  let ignored: string[] = []
@@ -640,13 +672,20 @@ async function skillLintCheck(packageName: string, source: string): Promise<Reco
640
672
  ;({ files, ignored } = await readSkillDirectory(source, MAX_SKILL_SOURCE_BYTES))
641
673
  } else {
642
674
  files = new Map()
643
- for (const entry of await readTarGz(await getHost().readFile(source), MAX_SKILL_SOURCE_BYTES)) {
644
- if (SKILL_DIRS.includes(entry.path.split('/')[0])) files.set(entry.path, { bytes: entry.bytes })
645
- else ignored.push(entry.path)
675
+ for (
676
+ const entry of await readTarGz(await getHost().readFile(source), MAX_SKILL_SOURCE_BYTES)
677
+ ) {
678
+ if (SKILL_DIRS.includes(entry.path.split('/')[0])) {
679
+ files.set(entry.path, { bytes: entry.bytes })
680
+ } else ignored.push(entry.path)
646
681
  }
647
682
  }
648
683
  } catch (error) {
649
- return { ...check, status: 'error', detail: error instanceof Error ? error.message : String(error) }
684
+ return {
685
+ ...check,
686
+ status: 'error',
687
+ detail: error instanceof Error ? error.message : String(error),
688
+ }
650
689
  }
651
690
  const { skills, findings } = lintSkillPackage(packageName, files)
652
691
  const errors = findings.filter((finding) => finding.level === 'error')
@@ -655,7 +694,13 @@ async function skillLintCheck(packageName: string, source: string): Promise<Reco
655
694
  status: errors.length ? 'error' : 'ok',
656
695
  ...(errors.length ? { detail: errors.map((finding) => finding.note).join('; '), errors } : {}),
657
696
  ...(errors.length ? {} : { digest: skillContentDigest(files) }),
658
- skills: skills.map(({ kind, name, scope, size, commands }) => ({ kind, name, scope, size, commands })),
697
+ skills: skills.map(({ kind, name, scope, size, commands }) => ({
698
+ kind,
699
+ name,
700
+ scope,
701
+ size,
702
+ commands,
703
+ })),
659
704
  warnings: findings.filter((finding) => finding.level !== 'error'),
660
705
  ...(ignored.length ? { ignored_files: ignored } : {}),
661
706
  }
@@ -690,19 +735,38 @@ async function writeSkillsSkeleton(dir: string, name: string): Promise<void> {
690
735
 
691
736
  /** A control package skeleton: one declarative control (or a composite one) under controls/<name>/ and its manifest
692
737
  * (digest included). */
693
- async function writeAiwsSkeleton(dir: string, ownerDid: string, name: string, composite: boolean): Promise<void> {
738
+ async function writeAiwsSkeleton(
739
+ dir: string,
740
+ ownerDid: string,
741
+ name: string,
742
+ composite: boolean,
743
+ ): Promise<void> {
694
744
  const kind = composite ? 'composite' : 'declarative'
695
745
  const files = controlSkeleton({ authorDid: ownerDid, name, title: name, kind })
696
746
  const encoder = new TextEncoder()
697
747
  const host = getHost()
698
748
  await host.mkdir(join(dir, 'controls', name), { recursive: true })
699
- for (const [file, text] of Object.entries(files)) await host.writeTextFile(join(dir, 'controls', name, file), text)
700
- const digest = await aiwsContentDigest(Object.entries(files).map(([file, text]) => [file, encoder.encode(text)] as [string, Uint8Array]))
749
+ for (const [file, text] of Object.entries(files)) {
750
+ await host.writeTextFile(join(dir, 'controls', name, file), text)
751
+ }
752
+ const digest = await aiwsContentDigest(
753
+ Object.entries(files).map(([file, text]) =>
754
+ [file, encoder.encode(text)] as [string, Uint8Array]
755
+ ),
756
+ )
701
757
  const manifest = {
702
758
  manifest_version: AIWS_MANIFEST_VERSION,
703
759
  purpose: 'aiws',
704
760
  host_api: composite ? {} : { declarative: 1 },
705
- controls: [{ ident: `${ownerDid}#${name}`, name, kind, version: 1, digest, dir: `controls/${name}/`, title: name }],
761
+ controls: [{
762
+ ident: `${ownerDid}#${name}`,
763
+ name,
764
+ kind,
765
+ version: 1,
766
+ digest,
767
+ dir: `controls/${name}/`,
768
+ title: name,
769
+ }],
706
770
  workspace_templates: [],
707
771
  }
708
772
  await host.writeTextFile(join(dir, AIWS_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\n`)
@@ -710,18 +774,32 @@ async function writeAiwsSkeleton(dir: string, ownerDid: string, name: string, co
710
774
 
711
775
  function hostExtToolsPlatform(): (typeof EXT_TOOLS_PLATFORMS)[number] {
712
776
  const host = getHost()
713
- const os = host.platform === 'darwin' ? 'macos' : host.platform === 'win32' ? 'windows' : host.platform
777
+ const os = host.platform === 'darwin'
778
+ ? 'macos'
779
+ : host.platform === 'win32'
780
+ ? 'windows'
781
+ : host.platform
714
782
  const arch = normalizeArch(host.arch)
715
- const platform = EXT_TOOLS_PLATFORMS.find((known) => known.selector.os === os && known.selector.arch === arch)
783
+ const platform = EXT_TOOLS_PLATFORMS.find((known) =>
784
+ known.selector.os === os && known.selector.arch === arch
785
+ )
716
786
  if (!platform) {
717
- throw new UsageError('UNSUPPORTED_PLATFORM', `extension packages have no payload for ${os}/${arch}`)
787
+ throw new UsageError(
788
+ 'UNSUPPORTED_PLATFORM',
789
+ `extension packages have no payload for ${os}/${arch}`,
790
+ )
718
791
  }
719
792
  return platform
720
793
  }
721
794
 
722
795
  /** An extension package skeleton for this machine's platform: `ext-manifest.json` and one command that runs and has a
723
796
  * smoke script, so the package builds from the first minute. Other platforms are added beside it. */
724
- async function writeExtToolsSkeleton(dir: string, id: string, version: string, platform: string): Promise<void> {
797
+ async function writeExtToolsSkeleton(
798
+ dir: string,
799
+ id: string,
800
+ version: string,
801
+ platform: string,
802
+ ): Promise<void> {
725
803
  const host = getHost()
726
804
  const manifest = {
727
805
  schema: EXT_TOOLS_MANIFEST_SCHEMA,
@@ -736,7 +814,9 @@ async function writeExtToolsSkeleton(dir: string, id: string, version: string, p
736
814
  }
737
815
  const text = `${JSON.stringify(manifest, null, 2)}\n`
738
816
  const payload = join(dir, 'payload', platform)
739
- for (const sub of ['bin', 'smoke', join('store', id)]) await host.mkdir(join(payload, sub), { recursive: true })
817
+ for (const sub of ['bin', 'smoke', join('store', id)]) {
818
+ await host.mkdir(join(payload, sub), { recursive: true })
819
+ }
740
820
  await host.writeTextFile(join(dir, EXT_TOOLS_MANIFEST_FILE), text)
741
821
  await host.writeTextFile(join(payload, EXT_TOOLS_MANIFEST_FILE), text)
742
822
  const windows = platform.startsWith('windows-')
@@ -754,7 +834,9 @@ async function writeExtToolsSkeleton(dir: string, id: string, version: string, p
754
834
  )
755
835
  }
756
836
 
757
- async function readExtToolsManifestFile(path: string): Promise<{ text: string; manifest?: ExtToolsManifest; errors: string[] }> {
837
+ async function readExtToolsManifestFile(
838
+ path: string,
839
+ ): Promise<{ text: string; manifest?: ExtToolsManifest; errors: string[] }> {
758
840
  let text: string
759
841
  try {
760
842
  text = await getHost().readTextFile(path)
@@ -777,9 +859,15 @@ async function readExtToolsManifestFile(path: string): Promise<{ text: string; m
777
859
  }
778
860
 
779
861
  /** A payload directory as `pikg build` would archive it: symlinks read through, and refused when they leave the tree. */
780
- async function readExtToolsPayloadTree(root: string): Promise<{ tree: ExtToolsPayloadTree; errors: string[] }> {
862
+ async function readExtToolsPayloadTree(
863
+ root: string,
864
+ ): Promise<{ tree: ExtToolsPayloadTree; errors: string[] }> {
781
865
  const host = getHost()
782
- const tree: ExtToolsPayloadTree = { files: new Map(), directories: new Set(), launchers: new Map() }
866
+ const tree: ExtToolsPayloadTree = {
867
+ files: new Map(),
868
+ directories: new Set(),
869
+ launchers: new Map(),
870
+ }
783
871
  const errors: string[] = []
784
872
  const realRoot = await host.realPath(root)
785
873
  const walk = async (directory: string, prefix: string): Promise<void> => {
@@ -793,7 +881,11 @@ async function readExtToolsPayloadTree(root: string): Promise<{ tree: ExtToolsPa
793
881
  try {
794
882
  physical = await host.realPath(path)
795
883
  } catch (error) {
796
- errors.push(`${archivePath}: ${isHostError(error, 'NotFound') ? 'a dangling symlink' : 'a symlink out of the payload'}`)
884
+ errors.push(
885
+ `${archivePath}: ${
886
+ isHostError(error, 'NotFound') ? 'a dangling symlink' : 'a symlink out of the payload'
887
+ }`,
888
+ )
797
889
  continue
798
890
  }
799
891
  const inside = relative(realRoot, physical)
@@ -822,7 +914,12 @@ async function readExtToolsPayloadTree(root: string): Promise<{ tree: ExtToolsPa
822
914
 
823
915
  /** `pikg doctor` of an extension package: the manifest against the App, every platform's payload, and, given a catalog
824
916
  * of the other packages, `requires` and same-named commands. */
825
- async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, catalogDir: string | undefined): Promise<Array<Record<string, unknown>>> {
917
+ async function extToolsChecks(
918
+ app: AppMeta,
919
+ pikg: PikgMeta,
920
+ metaDir: string,
921
+ catalogDir: string | undefined,
922
+ ): Promise<Array<Record<string, unknown>>> {
826
923
  const checks: Array<Record<string, unknown>> = []
827
924
  const platforms = new Map<string, string>()
828
925
  const stray: string[] = []
@@ -839,15 +936,27 @@ async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, cat
839
936
  const source = sources.length > 0 ? dirname(dirname(sources[0])) : dirname(metaDir)
840
937
  const master = await readExtToolsManifestFile(join(source, EXT_TOOLS_MANIFEST_FILE))
841
938
  const manifestErrors = [...master.errors]
842
- if (stray.length > 0) manifestErrors.push(`sub packages must be ext_tools_<os>_<arch> from a directory: ${stray.join(', ')}`)
939
+ if (stray.length > 0) {
940
+ manifestErrors.push(
941
+ `sub packages must be ext_tools_<os>_<arch> from a directory: ${stray.join(', ')}`,
942
+ )
943
+ }
843
944
  const manifest = master.manifest
844
945
  if (manifest) {
845
- if (manifest.id !== app.name) manifestErrors.push(`id ${manifest.id} is not the App name ${app.name}`)
846
- if (manifest.version !== app.version) manifestErrors.push(`version ${manifest.version} is not the App version ${app.version}`)
946
+ if (manifest.id !== app.name) {
947
+ manifestErrors.push(`id ${manifest.id} is not the App name ${app.name}`)
948
+ }
949
+ if (manifest.version !== app.version) {
950
+ manifestErrors.push(`version ${manifest.version} is not the App version ${app.version}`)
951
+ }
847
952
  const without = manifest.platforms.filter((name) => !platforms.has(name))
848
- if (without.length > 0) manifestErrors.push(`platforms without a sub package: ${without.join(', ')}`)
953
+ if (without.length > 0) {
954
+ manifestErrors.push(`platforms without a sub package: ${without.join(', ')}`)
955
+ }
849
956
  const unlisted = [...platforms.keys()].filter((name) => !manifest.platforms.includes(name))
850
- if (unlisted.length > 0) manifestErrors.push(`sub packages of platforms it does not list: ${unlisted.join(', ')}`)
957
+ if (unlisted.length > 0) {
958
+ manifestErrors.push(`sub packages of platforms it does not list: ${unlisted.join(', ')}`)
959
+ }
851
960
  }
852
961
  checks.push({
853
962
  name: 'ext_tools_manifest',
@@ -862,8 +971,11 @@ async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, cat
862
971
  const { tree, errors: walkErrors } = await readExtToolsPayloadTree(dir)
863
972
  errors.push(...walkErrors)
864
973
  const copy = await readExtToolsManifestFile(join(dir, EXT_TOOLS_MANIFEST_FILE))
865
- if (copy.errors.length > 0) errors.push(`${EXT_TOOLS_MANIFEST_FILE}: ${copy.errors.join('; ')}`)
866
- else if (copy.text !== master.text) errors.push(`${EXT_TOOLS_MANIFEST_FILE}: differs from the package's manifest`)
974
+ if (copy.errors.length > 0) {
975
+ errors.push(`${EXT_TOOLS_MANIFEST_FILE}: ${copy.errors.join('; ')}`)
976
+ } else if (copy.text !== master.text) {
977
+ errors.push(`${EXT_TOOLS_MANIFEST_FILE}: differs from the package's manifest`)
978
+ }
867
979
  errors.push(...extToolsPayloadErrors(manifest, platform, tree, [source, metaDir]))
868
980
  } catch (error) {
869
981
  if (!isHostError(error, 'NotFound')) throw error
@@ -889,10 +1001,14 @@ async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, cat
889
1001
  const catalogErrors: string[] = []
890
1002
  for (const entry of await getHost().readDir(catalogDir)) {
891
1003
  if (entry.isFile) continue
892
- const candidate = await readExtToolsManifestFile(join(catalogDir, entry.name, EXT_TOOLS_MANIFEST_FILE))
1004
+ const candidate = await readExtToolsManifestFile(
1005
+ join(catalogDir, entry.name, EXT_TOOLS_MANIFEST_FILE),
1006
+ )
893
1007
  if (candidate.errors.includes('not found')) continue
894
1008
  if (!candidate.manifest) catalogErrors.push(`${entry.name}: ${candidate.errors.join('; ')}`)
895
- else if (candidate.manifest.id !== manifest.id) others.set(candidate.manifest.id, candidate.manifest)
1009
+ else if (candidate.manifest.id !== manifest.id) {
1010
+ others.set(candidate.manifest.id, candidate.manifest)
1011
+ }
896
1012
  }
897
1013
  for (const required of manifest.requires) {
898
1014
  if (!others.has(required.id)) catalogErrors.push(`requires ${required.id}: not in the catalog`)
@@ -900,8 +1016,16 @@ async function extToolsChecks(app: AppMeta, pikg: PikgMeta, metaDir: string, cat
900
1016
  const commands = new Set(manifest.provides.map((provided) => provided.command))
901
1017
  for (const other of others.values()) {
902
1018
  if (manifest.conflicts.includes(other.id) || other.conflicts.includes(manifest.id)) continue
903
- const shared = other.provides.map((provided) => provided.command).filter((command) => commands.has(command))
904
- if (shared.length > 0) catalogErrors.push(`${other.id} also provides ${shared.join(', ')}: one of the two must list the other in conflicts`)
1019
+ const shared = other.provides.map((provided) => provided.command).filter((command) =>
1020
+ commands.has(command)
1021
+ )
1022
+ if (shared.length > 0) {
1023
+ catalogErrors.push(
1024
+ `${other.id} also provides ${
1025
+ shared.join(', ')
1026
+ }: one of the two must list the other in conflicts`,
1027
+ )
1028
+ }
905
1029
  }
906
1030
  checks.push({
907
1031
  name: 'ext_tools_catalog',
@@ -1305,7 +1429,11 @@ function parseAppMeta(value: Record<string, unknown>): AppMeta {
1305
1429
  }),
1306
1430
  categories: categories as string[],
1307
1431
  permissions,
1308
- ...(value.content_handlers === undefined ? {} : { content_handlers: developmentValidation(() => validateContentHandlers(value.content_handlers, permissions)) }),
1432
+ ...(value.content_handlers === undefined ? {} : {
1433
+ content_handlers: developmentValidation(() =>
1434
+ validateContentHandlers(value.content_handlers, permissions)
1435
+ ),
1436
+ }),
1309
1437
  selector_type: developmentString(value.selector_type, 'app.json.selector_type'),
1310
1438
  service_config_tips: serviceConfig,
1311
1439
  }
@@ -1560,17 +1688,31 @@ function assertSafeCleanTarget(
1560
1688
  }
1561
1689
  }
1562
1690
 
1563
- async function replaceDirectory(temporary: string, destination: string): Promise<void> {
1564
- let exists = false
1691
+ async function pathExists(path: string): Promise<boolean> {
1565
1692
  try {
1566
- await getHost().lstat(destination)
1567
- exists = true
1693
+ await getHost().lstat(path)
1694
+ return true
1568
1695
  } catch (error) {
1569
- if (!isHostError(error, 'NotFound')) throw error
1696
+ if (isHostError(error, 'NotFound')) return false
1697
+ throw error
1570
1698
  }
1571
- if (!exists) {
1572
- await getHost().rename(temporary, destination)
1573
- return
1699
+ }
1700
+
1701
+ async function replaceDirectory(temporary: string, destination: string): Promise<void> {
1702
+ if (!(await pathExists(destination))) {
1703
+ try {
1704
+ await getHost().rename(temporary, destination)
1705
+ return
1706
+ } catch (error) {
1707
+ // Windows reports EPERM, not EEXIST, when the destination directory is
1708
+ // already there. Fall through and replace it when that is the case.
1709
+ if (
1710
+ getHost().platform !== 'windows' || !isHostError(error, 'PermissionDenied') ||
1711
+ !(await pathExists(destination))
1712
+ ) {
1713
+ throw error
1714
+ }
1715
+ }
1574
1716
  }
1575
1717
  const backup = `${destination}.previous-${crypto.randomUUID()}`
1576
1718
  await getHost().rename(destination, backup)
@@ -0,0 +1,26 @@
1
+ // Windows MoveFileEx returns EPERM or EBUSY while a scanner still has a new
2
+ // file open, and also when a directory rename lands on an existing directory.
3
+ // A short retry covers the transient lock. The caller decides when to stop.
4
+ export async function retryWindowsLock<T>(
5
+ windows: boolean,
6
+ operation: () => Promise<T>,
7
+ retryable: (error: unknown) => boolean,
8
+ wait: (attempt: number) => number = defaultWait,
9
+ ): Promise<T> {
10
+ let attempt = 0
11
+ while (true) {
12
+ try {
13
+ return await operation()
14
+ } catch (error) {
15
+ const delay = windows && retryable(error) ? wait(attempt) : 0
16
+ if (delay <= 0) throw error
17
+ attempt++
18
+ await new Promise((resolve) => setTimeout(resolve, delay))
19
+ }
20
+ }
21
+ }
22
+
23
+ function defaultWait(attempt: number): number {
24
+ const waits = [50, 100, 150, 250, 400, 600, 800]
25
+ return waits[attempt] ?? 0
26
+ }
@@ -62,6 +62,18 @@ export interface HostCommandOutput {
62
62
  stderr: Uint8Array
63
63
  }
64
64
 
65
+ /** A child process the tool talks to line by line (a wish macro's stdio bridge). */
66
+ export interface HostChild {
67
+ /** Lines the child writes to stdout, without the newline. */
68
+ lines(): AsyncIterable<string>
69
+ writeLine(line: string): Promise<void>
70
+ closeInput(): Promise<void>
71
+ /** Everything the child wrote to stderr, once it exits. */
72
+ readonly stderr: Promise<string>
73
+ readonly status: Promise<number>
74
+ kill(): void
75
+ }
76
+
65
77
  export interface HostPath {
66
78
  readonly sep: string
67
79
  basename(path: string): string
@@ -140,6 +152,8 @@ export interface ToolHost {
140
152
  gzipFile(source: string, destination: string): Promise<void>
141
153
  run(command: string, args: string[]): Promise<HostCommandOutput>
142
154
  runGzip(command: string, args: string[], destination: string): Promise<HostCommandOutput>
155
+ /** Start `command` in `cwd` with exactly `env` (nothing inherited), stdin and stdout piped line by line. */
156
+ spawn(command: string, args: string[], options: { cwd: string; env: Record<string, string> }): HostChild
143
157
 
144
158
  stdout(value: string | Uint8Array): Promise<void>
145
159
  stderr(value: string | Uint8Array): Promise<void>
@@ -194,6 +208,8 @@ export const TOOL_ENVIRONMENT_NAMES = [
194
208
  ] as const
195
209
 
196
210
  interface PolicyOptions {
211
+ /** The runtime running the tool (Deno): `aiws run-exec` / `run-program` run a wish macro with it. */
212
+ runtimeExecutable?: string
197
213
  distribution: DistributionKind
198
214
  argv: string[]
199
215
  cwd: string
@@ -239,6 +255,8 @@ export function buildDistributionPolicy(options: PolicyOptions): DistributionPol
239
255
  }
240
256
  const subprocesses = parsed.module === 'pikg' && ['init', 'build'].includes(parsed.verb ?? '')
241
257
  ? ['docker']
258
+ : parsed.module === 'aiws' && ['run-exec', 'run-program'].includes(parsed.verb ?? '') && options.runtimeExecutable
259
+ ? [options.runtimeExecutable]
242
260
  : []
243
261
  const network = parsed.module !== undefined &&
244
262
  !['pikg', 'command', 'completion', 'config', 'provision'].includes(parsed.module)
@@ -7,10 +7,12 @@ import { fileURLToPath } from 'node:url'
7
7
  import { Readable, Writable } from 'node:stream'
8
8
  import { pipeline } from 'node:stream/promises'
9
9
  import { constants as zlibConstants, createGzip } from 'node:zlib'
10
+ import { retryWindowsLock } from './fs_retry.ts'
10
11
  import { assertPathAccess } from './path_policy.ts'
11
12
  import {
12
13
  type DistributionPolicy,
13
14
  HostError,
15
+ type HostChild,
14
16
  type HostFile,
15
17
  type HostFileInfo,
16
18
  type HostLineReader,
@@ -173,7 +175,11 @@ export class DenoHost implements ToolHost {
173
175
  await this.assertPath(from, 'write')
174
176
  await this.assertPath(to, 'write', false)
175
177
  try {
176
- await Deno.rename(from, to)
178
+ await retryWindowsLock(
179
+ this.platform === 'windows',
180
+ () => Deno.rename(from, to),
181
+ denoSharingViolation,
182
+ )
177
183
  } catch (error) {
178
184
  throw translateDenoError(error, `${from} -> ${to}`)
179
185
  }
@@ -182,7 +188,11 @@ export class DenoHost implements ToolHost {
182
188
  async remove(path: string, options: { recursive?: boolean } = {}): Promise<void> {
183
189
  await this.assertPath(path, 'write', false)
184
190
  try {
185
- await Deno.remove(path, options)
191
+ await retryWindowsLock(
192
+ this.platform === 'windows',
193
+ () => Deno.remove(path, options),
194
+ denoSharingViolation,
195
+ )
186
196
  } catch (error) {
187
197
  throw translateDenoError(error, path)
188
198
  }
@@ -280,6 +290,39 @@ export class DenoHost implements ToolHost {
280
290
  }
281
291
  }
282
292
 
293
+ spawn(command: string, args: string[], options: { cwd: string; env: Record<string, string> }): HostChild {
294
+ this.assertCommand(command)
295
+ let child: Deno.ChildProcess
296
+ try {
297
+ child = new Deno.Command(command, { args, cwd: options.cwd, env: options.env, clearEnv: true, stdin: 'piped', stdout: 'piped', stderr: 'piped' }).spawn()
298
+ } catch (error) {
299
+ throw translateDenoError(error, command)
300
+ }
301
+ const writer = child.stdin.getWriter()
302
+ const enc = new TextEncoder()
303
+ const stdout = child.stdout
304
+ return {
305
+ async *lines() {
306
+ const dec = new TextDecoder()
307
+ let buf = ''
308
+ for await (const chunk of stdout) {
309
+ buf += dec.decode(chunk, { stream: true })
310
+ let i
311
+ while ((i = buf.indexOf('\n')) >= 0) {
312
+ yield buf.slice(0, i)
313
+ buf = buf.slice(i + 1)
314
+ }
315
+ }
316
+ if (buf) yield buf
317
+ },
318
+ writeLine: async (line: string) => { await writer.write(enc.encode(line + '\n')).catch(() => {}) },
319
+ closeInput: async () => { await writer.close().catch(() => {}) },
320
+ stderr: new Response(child.stderr).text(),
321
+ status: child.status.then((s) => s.code),
322
+ kill: () => { try { child.kill('SIGKILL') } catch { /* already gone */ } },
323
+ }
324
+ }
325
+
283
326
  async runGzip(command: string, args: string[], destination: string) {
284
327
  this.assertCommand(command)
285
328
  await this.assertPath(destination, 'write', false)
@@ -479,6 +522,12 @@ function fileInfo(value: Deno.FileInfo): HostFileInfo {
479
522
  }
480
523
  }
481
524
 
525
+ function denoSharingViolation(error: unknown): boolean {
526
+ if (error instanceof Deno.errors.PermissionDenied) return true
527
+ const busy = (Deno.errors as { Busy?: new (...args: never[]) => Error }).Busy
528
+ return typeof busy === 'function' && error instanceof busy
529
+ }
530
+
482
531
  function translateDenoError(error: unknown, path?: string): HostError {
483
532
  if (error instanceof HostError) return error
484
533
  const kind = error instanceof Deno.errors.NotFound