buckyos 0.7.169 → 0.7.175

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 (233) hide show
  1. package/cli/core/app.ts +2 -0
  2. package/cli/core/argv.ts +45 -239
  3. package/cli/core/command.ts +3 -35
  4. package/cli/dist/cli.mjs +2151 -673
  5. package/cli/dist/cli.mjs.map +1 -1
  6. package/cli/modules/agent.ts +3 -1
  7. package/cli/modules/app.ts +13 -2
  8. package/cli/modules/pikg.ts +70 -1
  9. package/cli/modules/runtime.ts +497 -0
  10. package/cli/modules/skill.ts +583 -161
  11. package/cli/modules/skill_lint.ts +462 -0
  12. package/cli/version.ts +1 -1
  13. package/dist/account-7a7bde6f.mjs +105 -0
  14. package/dist/account-7a7bde6f.mjs.map +1 -0
  15. package/dist/account-b12ac6b9.js +2 -0
  16. package/dist/account-b12ac6b9.js.map +1 -0
  17. package/dist/aicc-67851c41.mjs +582 -0
  18. package/dist/aicc-67851c41.mjs.map +1 -0
  19. package/dist/aicc-ccb36ef7.js +2 -0
  20. package/dist/aicc-ccb36ef7.js.map +1 -0
  21. package/dist/app-frame.cjs +1 -1
  22. package/dist/app-frame.cjs.map +1 -1
  23. package/dist/app-frame.mjs +1 -0
  24. package/dist/app-frame.mjs.map +1 -1
  25. package/dist/browser.cjs +1 -1
  26. package/dist/browser.cjs.map +1 -1
  27. package/dist/browser.d.ts +3 -1
  28. package/dist/browser.d.ts.map +1 -1
  29. package/dist/browser.mjs +223 -212
  30. package/dist/browser.mjs.map +1 -1
  31. package/dist/content.cjs +1 -1
  32. package/dist/content.cjs.map +1 -1
  33. package/dist/content.d.ts +2 -1
  34. package/dist/content.d.ts.map +1 -1
  35. package/dist/content.mjs +32 -167
  36. package/dist/content.mjs.map +1 -1
  37. package/dist/content_mime-dc80d960.js +2 -0
  38. package/dist/content_mime-dc80d960.js.map +1 -0
  39. package/dist/content_mime-e42d5f8d.mjs +335 -0
  40. package/dist/content_mime-e42d5f8d.mjs.map +1 -0
  41. package/dist/content_mime.d.ts +18 -0
  42. package/dist/content_mime.d.ts.map +1 -1
  43. package/dist/did_object_client-6a1b108a.js +2 -0
  44. package/dist/did_object_client-6a1b108a.js.map +1 -0
  45. package/dist/did_object_client-7fa36f90.mjs +87 -0
  46. package/dist/did_object_client-7fa36f90.mjs.map +1 -0
  47. package/dist/did_object_client.d.ts +39 -0
  48. package/dist/did_object_client.d.ts.map +1 -0
  49. package/dist/{executor_client-a32bc377.mjs → executor_client-c620d25c.mjs} +1794 -844
  50. package/dist/executor_client-c620d25c.mjs.map +1 -0
  51. package/dist/executor_client-d4439d54.js +13 -0
  52. package/dist/executor_client-d4439d54.js.map +1 -0
  53. package/dist/executor_client.d.ts +129 -0
  54. package/dist/executor_client.d.ts.map +1 -1
  55. package/dist/file_meta.d.ts +26 -0
  56. package/dist/file_meta.d.ts.map +1 -0
  57. package/dist/index.cjs +1 -1
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.d.ts +3 -1
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.mjs +228 -217
  62. package/dist/index.mjs.map +1 -1
  63. package/dist/internal/command_args.d.ts +67 -0
  64. package/dist/internal/command_args.d.ts.map +1 -0
  65. package/dist/krpc_client-26c2dc8b.js +2 -0
  66. package/dist/krpc_client-26c2dc8b.js.map +1 -0
  67. package/dist/krpc_client-673448e5.mjs +173 -0
  68. package/dist/krpc_client-673448e5.mjs.map +1 -0
  69. package/dist/krpc_client.d.ts +5 -1
  70. package/dist/krpc_client.d.ts.map +1 -1
  71. package/dist/msg_center_client.d.ts +2 -1
  72. package/dist/msg_center_client.d.ts.map +1 -1
  73. package/dist/namelib.d.ts.map +1 -1
  74. package/dist/ndm_client.d.ts +7 -0
  75. package/dist/ndm_client.d.ts.map +1 -1
  76. package/dist/ndn.d.ts +3 -0
  77. package/dist/ndn.d.ts.map +1 -0
  78. package/dist/{namelib-b41b10cc.mjs → ndn_types-0fac2499.mjs} +3096 -2816
  79. package/dist/ndn_types-0fac2499.mjs.map +1 -0
  80. package/dist/ndn_types-5b138882.js +2 -0
  81. package/dist/ndn_types-5b138882.js.map +1 -0
  82. package/dist/ndn_types.d.ts +268 -16
  83. package/dist/ndn_types.d.ts.map +1 -1
  84. package/dist/node.cjs +1 -1
  85. package/dist/node.cjs.map +1 -1
  86. package/dist/node.d.ts +1 -1
  87. package/dist/node.d.ts.map +1 -1
  88. package/dist/node.mjs +220 -212
  89. package/dist/node.mjs.map +1 -1
  90. package/dist/object_url-8fb5a7bf.js +2 -0
  91. package/dist/object_url-8fb5a7bf.js.map +1 -0
  92. package/dist/object_url-f72c1704.mjs +412 -0
  93. package/dist/object_url-f72c1704.mjs.map +1 -0
  94. package/dist/openai-ae2978de.mjs +163 -0
  95. package/dist/openai-ae2978de.mjs.map +1 -0
  96. package/dist/openai-f560d518.js +2 -0
  97. package/dist/openai-f560d518.js.map +1 -0
  98. package/dist/provision.cjs +6 -6
  99. package/dist/provision.cjs.map +1 -1
  100. package/dist/provision.d.ts +1 -2
  101. package/dist/provision.d.ts.map +1 -1
  102. package/dist/provision.mjs +4 -31
  103. package/dist/provision.mjs.map +1 -1
  104. package/dist/repo_client.d.ts +2 -1
  105. package/dist/repo_client.d.ts.map +1 -1
  106. package/dist/site_manager-11a7a468.mjs +6410 -0
  107. package/dist/site_manager-11a7a468.mjs.map +1 -0
  108. package/dist/site_manager-334b1a51.js +2 -0
  109. package/dist/site_manager-334b1a51.js.map +1 -0
  110. package/dist/{tus_client-4f7254e9.js → tus_client-809c90ab.js} +2 -2
  111. package/dist/{tus_client-4f7254e9.js.map → tus_client-809c90ab.js.map} +1 -1
  112. package/dist/{tus_client-04080b1e.mjs → tus_client-893a3287.mjs} +2 -2
  113. package/dist/{tus_client-04080b1e.mjs.map → tus_client-893a3287.mjs.map} +1 -1
  114. package/dist/xllm/core/action_parser.d.ts +15 -0
  115. package/dist/xllm/core/action_parser.d.ts.map +1 -0
  116. package/dist/xllm/core/behavior_loop.d.ts +20 -0
  117. package/dist/xllm/core/behavior_loop.d.ts.map +1 -0
  118. package/dist/xllm/core/behavior_result.d.ts +11 -0
  119. package/dist/xllm/core/behavior_result.d.ts.map +1 -0
  120. package/dist/xllm/core/config.d.ts +62 -0
  121. package/dist/xllm/core/config.d.ts.map +1 -0
  122. package/dist/xllm/core/context_window.d.ts +15 -0
  123. package/dist/xllm/core/context_window.d.ts.map +1 -0
  124. package/dist/xllm/core/deps.d.ts +97 -0
  125. package/dist/xllm/core/deps.d.ts.map +1 -0
  126. package/dist/xllm/core/errors.d.ts +94 -0
  127. package/dist/xllm/core/errors.d.ts.map +1 -0
  128. package/dist/xllm/core/interrupt.d.ts +31 -0
  129. package/dist/xllm/core/interrupt.d.ts.map +1 -0
  130. package/dist/xllm/core/json.d.ts +11 -0
  131. package/dist/xllm/core/json.d.ts.map +1 -0
  132. package/dist/xllm/core/json_check.d.ts +17 -0
  133. package/dist/xllm/core/json_check.d.ts.map +1 -0
  134. package/dist/xllm/core/loop.d.ts +135 -0
  135. package/dist/xllm/core/loop.d.ts.map +1 -0
  136. package/dist/xllm/core/messages.d.ts +18 -0
  137. package/dist/xllm/core/messages.d.ts.map +1 -0
  138. package/dist/xllm/core/observer.d.ts +14 -0
  139. package/dist/xllm/core/observer.d.ts.map +1 -0
  140. package/dist/xllm/core/open_runtime.d.ts +22 -0
  141. package/dist/xllm/core/open_runtime.d.ts.map +1 -0
  142. package/dist/xllm/core/prepare.d.ts +54 -0
  143. package/dist/xllm/core/prepare.d.ts.map +1 -0
  144. package/dist/xllm/core/prompt.d.ts +40 -0
  145. package/dist/xllm/core/prompt.d.ts.map +1 -0
  146. package/dist/xllm/core/protocol.d.ts +15 -0
  147. package/dist/xllm/core/protocol.d.ts.map +1 -0
  148. package/dist/xllm/core/result.d.ts +12 -0
  149. package/dist/xllm/core/result.d.ts.map +1 -0
  150. package/dist/xllm/core/run.d.ts +198 -0
  151. package/dist/xllm/core/run.d.ts.map +1 -0
  152. package/dist/xllm/core/rust_text.d.ts +20 -0
  153. package/dist/xllm/core/rust_text.d.ts.map +1 -0
  154. package/dist/xllm/core/site_policy.d.ts +5 -0
  155. package/dist/xllm/core/site_policy.d.ts.map +1 -0
  156. package/dist/xllm/core/store.d.ts +60 -0
  157. package/dist/xllm/core/store.d.ts.map +1 -0
  158. package/dist/xllm/core/suspension.d.ts +13 -0
  159. package/dist/xllm/core/suspension.d.ts.map +1 -0
  160. package/dist/xllm/core/tokenizer.d.ts +8 -0
  161. package/dist/xllm/core/tokenizer.d.ts.map +1 -0
  162. package/dist/xllm/core/types.d.ts +826 -0
  163. package/dist/xllm/core/types.d.ts.map +1 -0
  164. package/dist/xllm/core/xml.d.ts +19 -0
  165. package/dist/xllm/core/xml.d.ts.map +1 -0
  166. package/dist/xllm/dev/openai.d.ts +17 -0
  167. package/dist/xllm/dev/openai.d.ts.map +1 -0
  168. package/dist/xllm/dev/scripted.d.ts +46 -0
  169. package/dist/xllm/dev/scripted.d.ts.map +1 -0
  170. package/dist/xllm/dev.d.ts +5 -0
  171. package/dist/xllm/dev.d.ts.map +1 -0
  172. package/dist/xllm/hosts/browser/store.d.ts +41 -0
  173. package/dist/xllm/hosts/browser/store.d.ts.map +1 -0
  174. package/dist/xllm/hosts/deno/deno_api.d.ts +103 -0
  175. package/dist/xllm/hosts/deno/deno_api.d.ts.map +1 -0
  176. package/dist/xllm/hosts/deno/identity.d.ts +29 -0
  177. package/dist/xllm/hosts/deno/identity.d.ts.map +1 -0
  178. package/dist/xllm/hosts/deno/index.d.ts +47 -0
  179. package/dist/xllm/hosts/deno/index.d.ts.map +1 -0
  180. package/dist/xllm/hosts/deno/native_runtime.d.ts +93 -0
  181. package/dist/xllm/hosts/deno/native_runtime.d.ts.map +1 -0
  182. package/dist/xllm/hosts/deno/native_tools.d.ts +105 -0
  183. package/dist/xllm/hosts/deno/native_tools.d.ts.map +1 -0
  184. package/dist/xllm/hosts/deno/provider.d.ts +13 -0
  185. package/dist/xllm/hosts/deno/provider.d.ts.map +1 -0
  186. package/dist/xllm/hosts/deno/store.d.ts +60 -0
  187. package/dist/xllm/hosts/deno/store.d.ts.map +1 -0
  188. package/dist/xllm/index.d.ts +48 -0
  189. package/dist/xllm/index.d.ts.map +1 -0
  190. package/dist/xllm/providers/aicc.d.ts +22 -0
  191. package/dist/xllm/providers/aicc.d.ts.map +1 -0
  192. package/dist/xllm/providers/timeout.d.ts +12 -0
  193. package/dist/xllm/providers/timeout.d.ts.map +1 -0
  194. package/dist/xllm/runtime/compress.d.ts +149 -0
  195. package/dist/xllm/runtime/compress.d.ts.map +1 -0
  196. package/dist/xllm/runtime/did_object_resources.d.ts +21 -0
  197. package/dist/xllm/runtime/did_object_resources.d.ts.map +1 -0
  198. package/dist/xllm/runtime/hints.d.ts +23 -0
  199. package/dist/xllm/runtime/hints.d.ts.map +1 -0
  200. package/dist/xllm/runtime/site.d.ts +22 -0
  201. package/dist/xllm/runtime/site.d.ts.map +1 -0
  202. package/dist/xllm/runtime/site_manager.d.ts +38 -0
  203. package/dist/xllm/runtime/site_manager.d.ts.map +1 -0
  204. package/dist/xllm/runtime/site_tools.d.ts +76 -0
  205. package/dist/xllm/runtime/site_tools.d.ts.map +1 -0
  206. package/dist/xllm/runtime/step_renderer.d.ts +54 -0
  207. package/dist/xllm/runtime/step_renderer.d.ts.map +1 -0
  208. package/dist/xllm/runtime/task_model.d.ts +64 -0
  209. package/dist/xllm/runtime/task_model.d.ts.map +1 -0
  210. package/dist/xllm/runtime/tool_result.d.ts +39 -0
  211. package/dist/xllm/runtime/tool_result.d.ts.map +1 -0
  212. package/dist/xllm/runtime/types.d.ts +99 -0
  213. package/dist/xllm/runtime/types.d.ts.map +1 -0
  214. package/dist/xllm.cjs +2 -0
  215. package/dist/xllm.cjs.map +1 -0
  216. package/dist/xllm.mjs +1167 -0
  217. package/dist/xllm.mjs.map +1 -0
  218. package/dist/xllm_deno.cjs +2 -0
  219. package/dist/xllm_deno.cjs.map +1 -0
  220. package/dist/xllm_deno.mjs +2487 -0
  221. package/dist/xllm_deno.mjs.map +1 -0
  222. package/dist/xllm_dev.cjs +2 -0
  223. package/dist/xllm_dev.cjs.map +1 -0
  224. package/dist/xllm_dev.mjs +70 -0
  225. package/dist/xllm_dev.mjs.map +1 -0
  226. package/package.json +22 -1
  227. package/src/internal/command_args.ts +268 -0
  228. package/dist/executor_client-a32bc377.mjs.map +0 -1
  229. package/dist/executor_client-e026942b.js +0 -13
  230. package/dist/executor_client-e026942b.js.map +0 -1
  231. package/dist/namelib-b41b10cc.mjs.map +0 -1
  232. package/dist/namelib-f8ff0045.js +0 -2
  233. package/dist/namelib-f8ff0045.js.map +0 -1
@@ -0,0 +1,462 @@
1
+ // The checks of a skill package before it reaches an Agent: a port of `package_skills`, `commands_in_manual` and the
2
+ // content rules of `plan()` in buckyos `src/frame/lib_opendan/src/skills.rs`, with the front matter rules of
3
+ // `protocol/behavior.rs`. The Agent runs the Rust ones again at install; keep the two in step.
4
+ import { getHost } from '../runtime/host.ts'
5
+ import { sha256Bytes } from './pikg_archive.ts'
6
+ import { EXT_TOOLS_RESERVED_COMMANDS } from './pikg_protocol.ts'
7
+
8
+ export const SKILL_KINDS = ['work', 'plan', 'goal'] as const
9
+ export type SkillKind = (typeof SKILL_KINDS)[number]
10
+ export const SKILL_KIND_DIRS: Record<SkillKind, string> = {
11
+ work: 'cmd_skills',
12
+ plan: 'plan_skills',
13
+ goal: 'goal_skills',
14
+ }
15
+ export const TOOLS_DIR = 'tools'
16
+ export const SKILL_DIRS = [...SKILL_KINDS.map((kind) => SKILL_KIND_DIRS[kind]), TOOLS_DIR]
17
+ export const SKILL_MANUAL = 'SKILL.md'
18
+ export const SKILL_REFERENCES = 'references'
19
+ export const SKILL_REVISIONS = 'revisions'
20
+ export const SKILL_PLATFORMS = ['linux', 'macos', 'windows']
21
+ export const UI_MANUAL_WARN_BYTES = 16 * 1024
22
+ export const PLAN_MANUAL_WARN_BYTES = 3 * 1024
23
+ const MAX_NAME_LEN = 200
24
+
25
+ /** Commands of the standard layer (Rust: `STANDARD_TOOLS` in buckyos `src/frame/lib_opendan/src/baseline.rs`): a manual
26
+ * does not declare them. */
27
+ export const STANDARD_COMMANDS: readonly string[] = EXT_TOOLS_RESERVED_COMMANDS
28
+
29
+ export interface SkillFinding {
30
+ code: string
31
+ /** `error` (not installable) | `high` | `medium` | `low`. */
32
+ level: string
33
+ where: string
34
+ note: string
35
+ }
36
+
37
+ export interface SkillPackageFile {
38
+ bytes: Uint8Array
39
+ }
40
+
41
+ export type SkillScope = 'work' | 'ui' | 'ui,work'
42
+
43
+ export interface LintedSkill {
44
+ kind: SkillKind
45
+ name: string
46
+ scope: SkillScope
47
+ description: string
48
+ requires: string
49
+ baseline: 'standard' | 'extended'
50
+ platforms: string[]
51
+ commands: string[]
52
+ size: number
53
+ references: string[]
54
+ }
55
+
56
+ export interface SkillLintResult {
57
+ skills: LintedSkill[]
58
+ findings: SkillFinding[]
59
+ }
60
+
61
+ // Words at a command position that are the shell's own or part of every runtime.
62
+ const SHELL_WORDS = new Set([
63
+ 'if', 'then', 'else', 'elif', 'fi', 'for', 'while', 'until', 'do', 'done', 'case', 'esac', 'in', 'function', 'select', 'time',
64
+ 'cd', 'echo', 'printf', 'export', 'set', 'unset', 'read', 'exit', 'return', 'source', 'eval', 'exec', 'test', 'true', 'false', 'local',
65
+ 'declare', 'trap', 'wait', 'shift', 'alias', 'type', 'command', 'pwd', 'kill', 'umask', 'ulimit', 'break', 'continue', 'let', 'readonly',
66
+ 'ls', 'cat', 'cp', 'mv', 'rm', 'mkdir', 'rmdir', 'touch', 'ln', 'chmod', 'chown', 'head', 'tail', 'grep', 'sed', 'awk', 'sort', 'uniq',
67
+ 'wc', 'cut', 'tr', 'tee', 'find', 'xargs', 'basename', 'dirname', 'date', 'sleep', 'env', 'which', 'diff', 'du', 'df', 'stat', 'mktemp',
68
+ 'sh', 'bash', 'id', 'whoami', 'uname', 'realpath', 'readlink', 'seq', 'yes', 'nohup', 'timeout', 'tar', 'gzip', 'gunzip', 'sha256sum',
69
+ 'base64', 'cmp', 'file', 'ps', 'less', 'more', 'printenv', 'hostname', 'expr', 'od', 'paste', 'comm', 'nl', 'tac', 'rev', 'fold', 'column',
70
+ 'read', 'shell',
71
+ ])
72
+ const SHELL_LANGS = new Set(['', 'sh', 'bash', 'shell', 'zsh', 'console'])
73
+ const ASSIGNMENT_KEY = /^[A-Za-z0-9_]+$/
74
+ const PLAIN_WORD = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/
75
+
76
+ function asciiLower(text: string): string {
77
+ return text.replace(/[A-Z]/g, (c) => c.toLowerCase())
78
+ }
79
+
80
+ /** The commands the shell code blocks of a manual run: the first word of each command, the shell's own words and
81
+ * placeholders left out. A heuristic for telling the owner what a manual relies on, never a gate. */
82
+ export function commandsInManual(text: string): Set<string> {
83
+ const out = new Set<string>()
84
+ let inBlock = false
85
+ let shell = false
86
+ let heredoc: string | undefined
87
+ let continued = false
88
+ for (const raw of text.split('\n')) {
89
+ let line = raw.trim()
90
+ if (line.startsWith('```')) {
91
+ inBlock = !inBlock
92
+ shell = inBlock && SHELL_LANGS.has(asciiLower(line.slice(3).trim()))
93
+ heredoc = undefined
94
+ continued = false
95
+ continue
96
+ }
97
+ if (!inBlock || !shell) continue
98
+ if (heredoc !== undefined) {
99
+ if (line === heredoc) heredoc = undefined
100
+ continue
101
+ }
102
+ const wasContinued = continued
103
+ continued = line.endsWith('\\')
104
+ const at = line.indexOf('<<')
105
+ if (at >= 0) {
106
+ const tag = line.slice(at + 2).replace(/^-+/, '').trim().split(/\s/)[0].replace(/^['"]+|['"]+$/g, '')
107
+ if (tag && /^[A-Za-z0-9_]+$/.test(tag)) heredoc = tag
108
+ }
109
+ if (wasContinued || !line || line.startsWith('#')) continue
110
+ if (line.startsWith('$ ')) line = line.slice(2)
111
+ let quote: string | undefined
112
+ const segments = ['']
113
+ const chars = Array.from(line)
114
+ for (let i = 0; i < chars.length; i += 1) {
115
+ const c = chars[i]
116
+ if (quote !== undefined) {
117
+ if (c === quote) quote = undefined
118
+ } else if (c === "'" || c === '"') {
119
+ quote = c
120
+ } else if (c === '#' && (i === 0 || /\s/.test(chars[i - 1]))) {
121
+ break
122
+ } else if (
123
+ // `a|b|c` without spaces is a list of alternatives in a usage line, not a pipe (as in skills.rs).
124
+ (c === '|' && (chars[i + 1] === undefined || /\s/.test(chars[i + 1]) || chars[i + 1] === '|' || (i > 0 && /\s/.test(chars[i - 1])))) ||
125
+ c === ';' || (c === '&' && chars[i + 1] === '&')
126
+ ) {
127
+ if (chars[i + 1] === c) i += 1
128
+ segments.push('')
129
+ continue
130
+ } else if (c === '$' && chars[i + 1] === '(') {
131
+ segments.push('')
132
+ i += 1
133
+ continue
134
+ }
135
+ segments[segments.length - 1] += c
136
+ }
137
+ for (const segment of segments) {
138
+ const first = segment.split(/\s+/).filter(Boolean).find((w) => {
139
+ const eq = w.indexOf('=')
140
+ if (eq >= 0 && ASSIGNMENT_KEY.test(w.slice(0, eq))) return false
141
+ return w !== 'sudo' && w !== '(' && w !== '{' && w !== '!'
142
+ })
143
+ if (first === undefined) continue
144
+ const word = first.replace(/^\(+/, '')
145
+ if (PLAIN_WORD.test(word) && /[a-z]/.test(word) && !SHELL_WORDS.has(word)) out.add(word)
146
+ }
147
+ }
148
+ return out
149
+ }
150
+
151
+ /** A manual split into its front matter (`---` lines around `key: value` lines) and its body; without front matter it
152
+ * is all body. */
153
+ export function splitFrontMatter(text: string): { fields: Map<string, string>; body: string } {
154
+ const trimmed = text.replace(/^+/, '')
155
+ const rest = trimmed.startsWith('---\n')
156
+ ? trimmed.slice(4)
157
+ : trimmed.startsWith('---\r\n')
158
+ ? trimmed.slice(5)
159
+ : undefined
160
+ if (rest === undefined) return { fields: new Map(), body: text.trim() }
161
+ const fields = new Map<string, string>()
162
+ let offset = 0
163
+ while (offset < rest.length) {
164
+ const end = rest.indexOf('\n', offset)
165
+ const next = end < 0 ? rest.length : end + 1
166
+ const line = rest.slice(offset, next).trim()
167
+ offset = next
168
+ if (line === '---') return { fields, body: rest.slice(offset).trim() }
169
+ const colon = line.indexOf(':')
170
+ if (colon < 0) continue
171
+ let value = line.slice(colon + 1).trim()
172
+ for (const q of ['"', "'"]) {
173
+ if (value.length >= 2 && value.startsWith(q) && value.endsWith(q)) {
174
+ value = value.slice(1, -1)
175
+ break
176
+ }
177
+ }
178
+ fields.set(line.slice(0, colon).trim(), value)
179
+ }
180
+ // No closing line: not front matter.
181
+ return { fields: new Map(), body: text.trim() }
182
+ }
183
+
184
+ function skillRequirements(fields: Map<string, string>): { baseline: 'standard' | 'extended'; platforms: string[] } {
185
+ const raw = (fields.get('baseline') ?? '').trim()
186
+ if (raw !== '' && raw !== 'standard' && raw !== 'extended') {
187
+ throw new Error(`baseline \`${raw}\` is not standard | extended`)
188
+ }
189
+ const platforms: string[] = []
190
+ for (const part of (fields.get('platforms') ?? '').split(',')) {
191
+ const p = part.trim()
192
+ if (!p) continue
193
+ if (!SKILL_PLATFORMS.includes(p)) throw new Error(`platform \`${p}\` is not one of ${SKILL_PLATFORMS.join(', ')}`)
194
+ if (!platforms.includes(p)) platforms.push(p)
195
+ }
196
+ return { baseline: raw === 'extended' ? 'extended' : 'standard', platforms }
197
+ }
198
+
199
+ function skillScope(fields: Map<string, string>): SkillScope {
200
+ let ui = false
201
+ let work = false
202
+ for (const part of (fields.get('scope') ?? '').split(',')) {
203
+ const word = part.trim()
204
+ if (word === 'ui') ui = true
205
+ else if (word === 'work') work = true
206
+ else if (word) throw new Error(`scope \`${word}\` is not ui | work`)
207
+ }
208
+ return ui ? (work ? 'ui,work' : 'ui') : 'work'
209
+ }
210
+
211
+ function skillCommandsOf(fields: Map<string, string>): string[] {
212
+ const commands = (fields.get('commands') ?? '').split(',').map((c) => c.trim())
213
+ .filter((c) => c && !c.startsWith('.') && /^[A-Za-z0-9._+-]+$/.test(c))
214
+ return commands.filter((c, index) => index === 0 || commands[index - 1] !== c)
215
+ }
216
+
217
+ function textOf(bytes: Uint8Array): string | undefined {
218
+ try {
219
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)
220
+ } catch {
221
+ return undefined
222
+ }
223
+ }
224
+
225
+ function byteLength(text: string): number {
226
+ return new TextEncoder().encode(text).length
227
+ }
228
+
229
+ /** Where a package file lands, and the skill it belongs to. */
230
+ function place(path: string): { kind: SkillKind; name: string } {
231
+ const bad = (hint = ''): never => {
232
+ throw new Error(
233
+ `\`${path}\` is not a skill file: a skill package holds <cmd_skills|plan_skills|goal_skills>/<name>/${SKILL_MANUAL} and their ${SKILL_REFERENCES}/…${hint}`,
234
+ )
235
+ }
236
+ const parts = path.split('/')
237
+ if (parts.some((p) => p === '' || p === '.' || p === '..')) bad()
238
+ if (parts[0] === TOOLS_DIR) {
239
+ throw new Error(
240
+ `\`${path}\`: a skill is text only and brings no command or install script; publish the commands as an extension package and name them in the manual's \`commands\``,
241
+ )
242
+ }
243
+ const kind = SKILL_KINDS.find((k) => SKILL_KIND_DIRS[k] === parts[0])
244
+ if (!kind || parts.length < 2) return bad()
245
+ if (parts.length === 2) {
246
+ return bad(parts[1].endsWith('.md') ? ` (a flat ${parts[0]}/<name>.md is no skill: move it to ${parts[0]}/${parts[1].slice(0, -3)}/${SKILL_MANUAL})` : '')
247
+ }
248
+ const manual = parts.length === 3 && parts[2] === SKILL_MANUAL
249
+ const reference = parts.length >= 4 && parts[2] === SKILL_REFERENCES
250
+ if (!manual && !reference) bad()
251
+ const name = parts[1]
252
+ if (name.length > MAX_NAME_LEN || name.startsWith('.') || !/^[A-Za-z0-9_.-]+$/.test(name)) bad()
253
+ return { kind, name }
254
+ }
255
+
256
+ function packageSkills(packageName: string, files: Map<string, SkillPackageFile>, findings: SkillFinding[]): LintedSkill[] {
257
+ const paths = [...files.keys()].sort()
258
+ const grouped = new Map<string, { kind: SkillKind; name: string; paths: string[] }>()
259
+ for (const path of paths) {
260
+ const { kind, name } = place(path)
261
+ const key = `${SKILL_KINDS.indexOf(kind)}:${name}`
262
+ if (!grouped.has(key)) grouped.set(key, { kind, name, paths: [] })
263
+ grouped.get(key)!.paths.push(path)
264
+ }
265
+ const binary = paths.find((path) => textOf(files.get(path)!.bytes) === undefined)
266
+ if (binary) throw new Error(`${binary} is not UTF-8 text: a skill is text only`)
267
+ if (grouped.size === 0) {
268
+ throw new Error(`package ${packageName} holds no skill (<cmd_skills|plan_skills|goal_skills>/<name>/${SKILL_MANUAL})`)
269
+ }
270
+ const out: LintedSkill[] = []
271
+ const groups = [...grouped.values()].sort((a, b) =>
272
+ SKILL_KINDS.indexOf(a.kind) - SKILL_KINDS.indexOf(b.kind) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
273
+ )
274
+ for (const { kind, name, paths: own } of groups) {
275
+ const dir = SKILL_KIND_DIRS[kind]
276
+ const manual = `${dir}/${name}/${SKILL_MANUAL}`
277
+ const file = files.get(manual)
278
+ if (!file) throw new Error(`${dir}/${name}/ has no ${SKILL_MANUAL}`)
279
+ const text = textOf(file.bytes)
280
+ if (text === undefined) throw new Error(`${manual} is not UTF-8 text`)
281
+ const { fields, body } = splitFrontMatter(text)
282
+ let requirements: ReturnType<typeof skillRequirements>
283
+ let scope: SkillScope
284
+ try {
285
+ requirements = skillRequirements(fields)
286
+ scope = skillScope(fields)
287
+ if (kind !== 'work') {
288
+ for (const key of ['scope', 'commands']) {
289
+ if ((fields.get(key) ?? '').trim()) {
290
+ throw new Error(`a ${kind} skill declares no \`${key}\`: it names no commands and is read, not frozen`)
291
+ }
292
+ }
293
+ }
294
+ } catch (error) {
295
+ throw new Error(`${manual}: ${(error as Error).message}`)
296
+ }
297
+ if (fields.has('name') && fields.get('name') !== name) {
298
+ throw new Error(`${manual}: front matter name \`${fields.get('name')}\` differs from its directory`)
299
+ }
300
+ const refPrefix = `${dir}/${name}/${SKILL_REFERENCES}/`
301
+ const skill: LintedSkill = {
302
+ kind,
303
+ name,
304
+ scope: kind === 'work' ? scope : 'work',
305
+ description: fields.get('description') ?? '',
306
+ requires: fields.get('requires') ?? '',
307
+ baseline: requirements.baseline,
308
+ platforms: requirements.platforms,
309
+ commands: skillCommandsOf(fields),
310
+ size: byteLength(body),
311
+ references: own.filter((p) => p.startsWith(refPrefix)).map((p) => p.slice(refPrefix.length)),
312
+ }
313
+ const add = (code: string, level: string, note: string) => findings.push({ code, level, where: manual, note })
314
+ if (!skill.description.trim()) add('no_description', 'medium', 'no `description`: whoever chooses manuals only sees the name')
315
+ const texts = [body]
316
+ for (const path of own) {
317
+ if (!path.includes(`/${SKILL_REFERENCES}/`) || !path.endsWith('.md')) continue
318
+ const reference = textOf(files.get(path)!.bytes)
319
+ if (reference !== undefined) texts.push(reference)
320
+ }
321
+ const used = [...new Set(texts.flatMap((t) => [...commandsInManual(t)]))].sort()
322
+ if (kind === 'work') {
323
+ if (skill.scope !== 'work' && skill.size > UI_MANUAL_WARN_BYTES) {
324
+ add('ui_manual_large', 'low', `${skill.size} bytes: every conversation that takes it carries them (advised: at most ${UI_MANUAL_WARN_BYTES})`)
325
+ }
326
+ const undeclared = used.filter((c) => !skill.commands.includes(c) && !STANDARD_COMMANDS.includes(c))
327
+ if (undeclared.length) add('undeclared_commands', 'low', `the manual runs ${undeclared.join(', ')} without naming them in \`commands\``)
328
+ const lower = texts.map((t) => t.toLowerCase())
329
+ const unused = skill.commands.filter((c) => !lower.some((t) => t.includes(c.toLowerCase())))
330
+ if (unused.length) add('unused_commands', 'low', `\`commands\` names ${unused.join(', ')} but the manual never mentions them`)
331
+ } else if (kind === 'plan') {
332
+ if (skill.size > PLAN_MANUAL_WARN_BYTES) {
333
+ add('plan_manual_large', 'low', `${skill.size} bytes (advised: at most ${PLAN_MANUAL_WARN_BYTES}): a plan reads it whole`)
334
+ }
335
+ const hard = texts.some((t) =>
336
+ t.includes('create-worksession') || t.includes('--cmd-skill') ||
337
+ t.split('\n').some((l) => l.includes('--skill ') && !l.includes('--skill <'))
338
+ )
339
+ if (hard || used.length) {
340
+ add(
341
+ 'plan_depends_on_commands',
342
+ 'medium',
343
+ 'a plan skill says how to split, order and check work, not which commands or manuals to use: move commands into a work skill and write "give this step a manual for X"',
344
+ )
345
+ }
346
+ }
347
+ out.push(skill)
348
+ }
349
+ return out
350
+ }
351
+
352
+ const PACKAGE_MANAGERS = [
353
+ 'apt-get ', 'apt install', 'brew install', 'npm install -g', 'npm i -g', 'pip install', 'pip3 install', 'winget install',
354
+ 'choco install', 'dnf install', 'yum install', 'apk add',
355
+ ]
356
+ const SECRET_WORDS = ['TOKEN', 'SECRET', 'PASSWORD', 'API_KEY', 'APIKEY', 'PRIVATE_KEY']
357
+
358
+ /** What `skills.install_plan` tells the owner about the content of a package (Rust: `plan()`), as far as it can be told
359
+ * without the Agent: nothing about what it replaces. */
360
+ function riskFindings(skills: LintedSkill[], files: Map<string, SkillPackageFile>, findings: SkillFinding[]): void {
361
+ const paths = [...files.keys()].sort()
362
+ for (const skill of skills) {
363
+ const dir = SKILL_KIND_DIRS[skill.kind]
364
+ const key = `${skill.kind}:${skill.name}`
365
+ if (skill.scope !== 'work') {
366
+ findings.push({ code: 'ui_scope', level: 'medium', where: key, note: 'its scope includes `ui`: once the owner adds it to the UI set it goes into the prompt of every conversation' })
367
+ }
368
+ for (const path of paths) {
369
+ if (!path.startsWith(`${dir}/${skill.name}/`)) continue
370
+ const text = textOf(files.get(path)!.bytes)
371
+ if (text === undefined) continue
372
+ const lower = asciiLower(text)
373
+ const piped = lower.split('\n').some((l) =>
374
+ (l.includes('curl ') || l.includes('wget ')) && (l.includes('| sh') || l.includes('|sh') || l.includes('| bash') || l.includes('|bash'))
375
+ )
376
+ if (piped) {
377
+ findings.push({ code: 'network_script', level: 'high', where: path, note: 'tells the agent to download a script and run it (`curl … | sh`)' })
378
+ }
379
+ const managers = PACKAGE_MANAGERS.filter((m) => lower.includes(m))
380
+ if (managers.length) {
381
+ findings.push({ code: 'package_manager', level: 'medium', where: path, note: `uses a package manager (${managers.join(', ').replaceAll(' ', ' ')})` })
382
+ }
383
+ if (lower.split('\n').some((l) => l.split(/\s+/).includes('sudo'))) {
384
+ findings.push({ code: 'privilege', level: 'high', where: path, note: 'asks for root (`sudo`)' })
385
+ }
386
+ const secrets = [...new Set(
387
+ text.split(/[^A-Za-z0-9_]/).filter((w) => w.length > 5 && /^[A-Z0-9_]+$/.test(w) && SECRET_WORDS.some((s) => w.includes(s))),
388
+ )].sort()
389
+ if (secrets.length) {
390
+ findings.push({ code: 'secrets', level: 'medium', where: path, note: `reads secrets from the environment (${secrets.join(', ')})` })
391
+ }
392
+ }
393
+ }
394
+ }
395
+
396
+ /** The content digest of a package (Rust: `content_digest`): `sha256:<hex>` over the lines `<path>|<sha256 of the file>`
397
+ * in path order. The Agent reports the same value as `digest` of the install plan and of the installed package. */
398
+ export function skillContentDigest(files: Map<string, SkillPackageFile>): string {
399
+ const lines = [...files.keys()].sort().map((path) => `${path}|${sha256Bytes(files.get(path)!.bytes)}\n`)
400
+ return `sha256:${sha256Bytes(new TextEncoder().encode(lines.join('')))}`
401
+ }
402
+
403
+ /** Check a skill package without an Agent (`pikg doctor`, a directory given to `skill install`). A package that cannot
404
+ * be installed gets one `invalid_package` finding of level `error`, first; the rest is advice. */
405
+ export function lintSkillPackage(packageName: string, files: Map<string, SkillPackageFile>): SkillLintResult {
406
+ const findings: SkillFinding[] = []
407
+ try {
408
+ const skills = packageSkills(packageName, files, findings)
409
+ riskFindings(skills, files, findings)
410
+ return { skills, findings }
411
+ } catch (error) {
412
+ findings.unshift({ code: 'invalid_package', level: 'error', where: packageName, note: (error as Error).message })
413
+ return { skills: [], findings }
414
+ }
415
+ }
416
+
417
+ /** A directory laid out like the `agent_skills` sub package, read as `pikg build` archives it: the skill directories
418
+ * only (`revisions/` of a manual left out; a `tools/` is read so that the package is refused for it), links followed
419
+ * while they stay inside. */
420
+ export async function readSkillDirectory(
421
+ root: string,
422
+ limit: number,
423
+ ): Promise<{ files: Map<string, SkillPackageFile>; ignored: string[] }> {
424
+ const host = getHost()
425
+ const realRoot = await host.realPath(root)
426
+ const files = new Map<string, SkillPackageFile>()
427
+ const ignored: string[] = []
428
+ let total = 0
429
+ const walk = async (directory: string, prefix: string): Promise<void> => {
430
+ const children = (await host.readDir(directory)).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
431
+ for (const child of children) {
432
+ const rel = prefix ? `${prefix}/${child.name}` : child.name
433
+ const parts = rel.split('/')
434
+ if (parts.length > 32) throw new Error(`${rel}: nested too deep`)
435
+ if (!prefix && !SKILL_DIRS.includes(child.name)) {
436
+ ignored.push(rel)
437
+ continue
438
+ }
439
+ if (parts[0] !== TOOLS_DIR && parts.length === 3 && parts[2] === SKILL_REVISIONS) continue
440
+ let path = host.path.join(directory, child.name)
441
+ if ((await host.lstat(path)).isSymlink) {
442
+ path = await host.realPath(path)
443
+ const inside = host.path.relative(realRoot, path)
444
+ if (inside === '..' || inside.startsWith(`..${host.path.sep}`) || host.path.isAbsolute(inside)) {
445
+ throw new Error(`${rel}: a link out of the skill directory`)
446
+ }
447
+ }
448
+ const info = await host.stat(path)
449
+ if (info.isDirectory) {
450
+ await walk(path, rel)
451
+ } else if (info.isFile) {
452
+ total += info.size
453
+ if (total > limit) throw new Error(`the skill directory holds more than ${limit} bytes`)
454
+ files.set(rel, { bytes: await host.readFile(path) })
455
+ } else {
456
+ throw new Error(`${rel}: not a regular file`)
457
+ }
458
+ }
459
+ }
460
+ await walk(realRoot, '')
461
+ return { files, ignored }
462
+ }
package/cli/version.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // Generated by scripts/generate-cli-version.mjs. Do not edit.
2
- export const PACKAGE_VERSION = '0.7.169'
2
+ export const PACKAGE_VERSION = '0.7.175'
3
3
  export const TOOL_VERSION = PACKAGE_VERSION
4
4
  export const SDK_VERSION = PACKAGE_VERSION
5
5
  export const PROTOCOL_VERSION = '1'
@@ -0,0 +1,105 @@
1
+ import { b7 as ht } from "./ndn_types-0fac2499.mjs";
2
+ const BROWSER_USER_INFO_STORAGE_KEY = "user_info";
3
+ const BROWSER_IDENTITY_STORAGE_KEY = "buckyos.identity";
4
+ function getAccountStorageKey(appId) {
5
+ return `buckyos.account_info.${appId}`;
6
+ }
7
+ function parseBrowserUserInfo(raw) {
8
+ if (raw == null) {
9
+ return null;
10
+ }
11
+ try {
12
+ const parsed = JSON.parse(raw);
13
+ const userId = typeof parsed.user_id === "string" ? parsed.user_id.trim() : "";
14
+ const userType = typeof parsed.user_type === "string" ? parsed.user_type.trim() : "";
15
+ const userNameCandidate = typeof parsed.user_name === "string" ? parsed.user_name.trim() : typeof parsed.show_name === "string" ? parsed.show_name.trim() : "";
16
+ if (!userId || !userType) {
17
+ return null;
18
+ }
19
+ return {
20
+ user_name: userNameCandidate || userId,
21
+ user_id: userId,
22
+ user_type: userType
23
+ };
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+ function hashPassword(username, password, nonce = null) {
29
+ const shaObj = new ht("SHA-256", "TEXT", { encoding: "UTF8" });
30
+ shaObj.update(password + username + ".buckyos");
31
+ let org_password_hash_str = shaObj.getHash("B64");
32
+ if (nonce == null) {
33
+ return org_password_hash_str;
34
+ }
35
+ const shaObj2 = new ht("SHA-256", "TEXT", { encoding: "UTF8" });
36
+ let salt = org_password_hash_str + nonce.toString();
37
+ shaObj2.update(salt);
38
+ let result = shaObj2.getHash("B64");
39
+ return result;
40
+ }
41
+ function cleanLocalAccountInfo(appId) {
42
+ localStorage.removeItem(getAccountStorageKey(appId));
43
+ localStorage.removeItem(BROWSER_USER_INFO_STORAGE_KEY);
44
+ localStorage.removeItem(BROWSER_IDENTITY_STORAGE_KEY);
45
+ let cookie_options = {
46
+ path: "/",
47
+ expires: /* @__PURE__ */ new Date(0),
48
+ secure: true,
49
+ sameSite: "Lax"
50
+ };
51
+ document.cookie = `${appId}_token=; ${Object.entries(cookie_options).map(([key, value]) => `${key}=${value}`).join("; ")}`;
52
+ }
53
+ function saveLocalAccountInfo(appId, account_info) {
54
+ if (account_info.session_token == null) {
55
+ console.error("session_token is null,can't save account info");
56
+ return;
57
+ }
58
+ localStorage.setItem(getAccountStorageKey(appId), JSON.stringify(account_info));
59
+ let cookie_options = {
60
+ path: "/",
61
+ expires: new Date(Date.now() + 1e3 * 60 * 60 * 24 * 30),
62
+ // 30天
63
+ secure: true,
64
+ sameSite: "Lax"
65
+ };
66
+ document.cookie = `${appId}_token=${account_info.session_token}; ${Object.entries(cookie_options).map(([key, value]) => `${key}=${value}`).join("; ")}`;
67
+ }
68
+ function saveBrowserUserInfo(userInfo) {
69
+ localStorage.setItem(BROWSER_USER_INFO_STORAGE_KEY, JSON.stringify(userInfo));
70
+ }
71
+ function getBrowserUserInfo() {
72
+ return parseBrowserUserInfo(localStorage.getItem(BROWSER_USER_INFO_STORAGE_KEY));
73
+ }
74
+ function clearBrowserUserInfo() {
75
+ localStorage.removeItem(BROWSER_USER_INFO_STORAGE_KEY);
76
+ }
77
+ function saveBrowserIdentity(identity) {
78
+ localStorage.setItem(BROWSER_IDENTITY_STORAGE_KEY, JSON.stringify(identity));
79
+ }
80
+ function getBrowserIdentityRaw() {
81
+ const raw = localStorage.getItem(BROWSER_IDENTITY_STORAGE_KEY);
82
+ if (!raw) {
83
+ return null;
84
+ }
85
+ try {
86
+ return JSON.parse(raw);
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+ function clearBrowserIdentity() {
92
+ localStorage.removeItem(BROWSER_IDENTITY_STORAGE_KEY);
93
+ }
94
+ export {
95
+ saveBrowserUserInfo as a,
96
+ getBrowserUserInfo as b,
97
+ clearBrowserUserInfo as c,
98
+ clearBrowserIdentity as d,
99
+ saveLocalAccountInfo as e,
100
+ cleanLocalAccountInfo as f,
101
+ getBrowserIdentityRaw as g,
102
+ hashPassword as h,
103
+ saveBrowserIdentity as s
104
+ };
105
+ //# sourceMappingURL=account-7a7bde6f.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-7a7bde6f.mjs","sources":["../src/account.ts"],"sourcesContent":["import jsSHA from 'jssha';\n\nexport interface AccountInfo {\n user_name: string;\n user_id: string;\n /**\n * A Zone account type (`admin` | `user` | `limited` | `root`, see\n * `ZoneUserType`) for user sessions, `service` for an AppService runtime.\n * Kept as a string: an unknown value must not break the session.\n */\n user_type?: string;\n session_token: string;\n refresh_token?: string;\n}\n\nconst BROWSER_USER_INFO_STORAGE_KEY = \"user_info\";\nconst BROWSER_IDENTITY_STORAGE_KEY = \"buckyos.identity\";\n\nexport interface BrowserUserInfo {\n user_name: string;\n user_id: string;\n /** Zone account type as verify-hub returned it; see `ZoneUserType`. */\n user_type: string;\n}\n\nfunction getAccountStorageKey(appId:string):string {\n return `buckyos.account_info.${appId}`;\n}\n\nfunction parseBrowserUserInfo(raw:string|null):BrowserUserInfo|null {\n if(raw == null) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(raw) as {\n show_name?: unknown;\n user_name?: unknown;\n user_id?: unknown;\n user_type?: unknown;\n };\n const userId = typeof parsed.user_id === 'string' ? parsed.user_id.trim() : '';\n const userType = typeof parsed.user_type === 'string' ? parsed.user_type.trim() : '';\n const userNameCandidate = typeof parsed.user_name === 'string'\n ? parsed.user_name.trim()\n : typeof parsed.show_name === 'string'\n ? parsed.show_name.trim()\n : '';\n\n if(!userId || !userType) {\n return null;\n }\n\n return {\n user_name: userNameCandidate || userId,\n user_id: userId,\n user_type: userType,\n };\n } catch {\n return null;\n }\n}\n\nexport function hashPassword(username:string,password:string,nonce:number|null=null):string {\n const shaObj = new jsSHA(\"SHA-256\", \"TEXT\", { encoding: \"UTF8\" });\n shaObj.update(password+username+\".buckyos\");\n let org_password_hash_str = shaObj.getHash(\"B64\");\n if (nonce == null) {\n return org_password_hash_str;\n }\n const shaObj2 = new jsSHA(\"SHA-256\", \"TEXT\", { encoding: \"UTF8\" });\n let salt = org_password_hash_str + nonce.toString();\n shaObj2.update(salt);\n let result = shaObj2.getHash(\"B64\");\n return result;\n}\n\nexport function cleanLocalAccountInfo(appId:string) {\n localStorage.removeItem(getAccountStorageKey(appId));\n localStorage.removeItem(BROWSER_USER_INFO_STORAGE_KEY);\n localStorage.removeItem(BROWSER_IDENTITY_STORAGE_KEY);\n //删除cookie\n let cookie_options = {\n path: \"/\",\n expires: new Date(0),\n secure: true,\n sameSite: \"Lax\"\n };\n document.cookie = `${appId}_token=; ${Object.entries(cookie_options).map(([key, value]) => `${key}=${value}`).join('; ')}`;\n\n}\n\nexport function saveLocalAccountInfo(appId:string, account_info:AccountInfo) {\n if(account_info.session_token == null) {\n console.error(\"session_token is null,can't save account info\");\n return;\n }\n\n localStorage.setItem(getAccountStorageKey(appId), JSON.stringify(account_info));\n //session token用cookie存储\n let cookie_options = {\n path: \"/\",\n expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30), // 30天\n secure: true,\n sameSite: \"Lax\"\n };\n document.cookie = `${appId}_token=${account_info.session_token}; ${Object.entries(cookie_options).map(([key, value]) => `${key}=${value}`).join('; ')}`;\n}\n\nexport function saveBrowserUserInfo(userInfo:BrowserUserInfo) {\n localStorage.setItem(BROWSER_USER_INFO_STORAGE_KEY, JSON.stringify(userInfo));\n}\n\nexport function getBrowserUserInfo():BrowserUserInfo|null {\n return parseBrowserUserInfo(localStorage.getItem(BROWSER_USER_INFO_STORAGE_KEY));\n}\n\nexport function clearBrowserUserInfo() {\n localStorage.removeItem(BROWSER_USER_INFO_STORAGE_KEY);\n}\n\n/** The last current identity `/sso_refresh` returned (raw JSON, parse with `parseCurrentIdentity`). */\nexport function saveBrowserIdentity(identity:unknown) {\n localStorage.setItem(BROWSER_IDENTITY_STORAGE_KEY, JSON.stringify(identity));\n}\n\nexport function getBrowserIdentityRaw():unknown {\n const raw = localStorage.getItem(BROWSER_IDENTITY_STORAGE_KEY);\n if (!raw) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nexport function clearBrowserIdentity() {\n localStorage.removeItem(BROWSER_IDENTITY_STORAGE_KEY);\n}\n\n"],"names":["jsSHA"],"mappings":";AAeA,MAAM,gCAAgC;AACtC,MAAM,+BAA+B;AASrC,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AAuB;AACnC,eAAa,WAAW,4BAA4B;AACxD;"}
@@ -0,0 +1,2 @@
1
+ "use strict";const e=require("./ndn_types-5b138882.js"),t="user_info",n="buckyos.identity";function o(e){return`buckyos.account_info.${e}`}exports.cleanLocalAccountInfo=function(e){localStorage.removeItem(o(e)),localStorage.removeItem(t),localStorage.removeItem(n);let r={path:"/",expires:new Date(0),secure:!0,sameSite:"Lax"};document.cookie=`${e}_token=; ${Object.entries(r).map((([e,t])=>`${e}=${t}`)).join("; ")}`},exports.clearBrowserIdentity=function(){localStorage.removeItem(n)},exports.clearBrowserUserInfo=function(){localStorage.removeItem(t)},exports.getBrowserIdentityRaw=function(){const e=localStorage.getItem(n);if(!e)return null;try{return JSON.parse(e)}catch{return null}},exports.getBrowserUserInfo=function(){return function(e){if(null==e)return null;try{const t=JSON.parse(e),n="string"==typeof t.user_id?t.user_id.trim():"",o="string"==typeof t.user_type?t.user_type.trim():"",r="string"==typeof t.user_name?t.user_name.trim():"string"==typeof t.show_name?t.show_name.trim():"";return n&&o?{user_name:r||n,user_id:n,user_type:o}:null}catch{return null}}(localStorage.getItem(t))},exports.hashPassword=function(t,n,o=null){const r=new e.ht("SHA-256","TEXT",{encoding:"UTF8"});r.update(n+t+".buckyos");let s=r.getHash("B64");if(null==o)return s;const i=new e.ht("SHA-256","TEXT",{encoding:"UTF8"});let a=s+o.toString();return i.update(a),i.getHash("B64")},exports.saveBrowserIdentity=function(e){localStorage.setItem(n,JSON.stringify(e))},exports.saveBrowserUserInfo=function(e){localStorage.setItem(t,JSON.stringify(e))},exports.saveLocalAccountInfo=function(e,t){if(null==t.session_token)return void console.error("session_token is null,can't save account info");localStorage.setItem(o(e),JSON.stringify(t));let n={path:"/",expires:new Date(Date.now()+2592e6),secure:!0,sameSite:"Lax"};document.cookie=`${e}_token=${t.session_token}; ${Object.entries(n).map((([e,t])=>`${e}=${t}`)).join("; ")}`};
2
+ //# sourceMappingURL=account-b12ac6b9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-b12ac6b9.js","sources":["../src/account.ts"],"sourcesContent":["import jsSHA from 'jssha';\n\nexport interface AccountInfo {\n user_name: string;\n user_id: string;\n /**\n * A Zone account type (`admin` | `user` | `limited` | `root`, see\n * `ZoneUserType`) for user sessions, `service` for an AppService runtime.\n * Kept as a string: an unknown value must not break the session.\n */\n user_type?: string;\n session_token: string;\n refresh_token?: string;\n}\n\nconst BROWSER_USER_INFO_STORAGE_KEY = \"user_info\";\nconst BROWSER_IDENTITY_STORAGE_KEY = \"buckyos.identity\";\n\nexport interface BrowserUserInfo {\n user_name: string;\n user_id: string;\n /** Zone account type as verify-hub returned it; see `ZoneUserType`. */\n user_type: string;\n}\n\nfunction getAccountStorageKey(appId:string):string {\n return `buckyos.account_info.${appId}`;\n}\n\nfunction parseBrowserUserInfo(raw:string|null):BrowserUserInfo|null {\n if(raw == null) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(raw) as {\n show_name?: unknown;\n user_name?: unknown;\n user_id?: unknown;\n user_type?: unknown;\n };\n const userId = typeof parsed.user_id === 'string' ? parsed.user_id.trim() : '';\n const userType = typeof parsed.user_type === 'string' ? parsed.user_type.trim() : '';\n const userNameCandidate = typeof parsed.user_name === 'string'\n ? parsed.user_name.trim()\n : typeof parsed.show_name === 'string'\n ? parsed.show_name.trim()\n : '';\n\n if(!userId || !userType) {\n return null;\n }\n\n return {\n user_name: userNameCandidate || userId,\n user_id: userId,\n user_type: userType,\n };\n } catch {\n return null;\n }\n}\n\nexport function hashPassword(username:string,password:string,nonce:number|null=null):string {\n const shaObj = new jsSHA(\"SHA-256\", \"TEXT\", { encoding: \"UTF8\" });\n shaObj.update(password+username+\".buckyos\");\n let org_password_hash_str = shaObj.getHash(\"B64\");\n if (nonce == null) {\n return org_password_hash_str;\n }\n const shaObj2 = new jsSHA(\"SHA-256\", \"TEXT\", { encoding: \"UTF8\" });\n let salt = org_password_hash_str + nonce.toString();\n shaObj2.update(salt);\n let result = shaObj2.getHash(\"B64\");\n return result;\n}\n\nexport function cleanLocalAccountInfo(appId:string) {\n localStorage.removeItem(getAccountStorageKey(appId));\n localStorage.removeItem(BROWSER_USER_INFO_STORAGE_KEY);\n localStorage.removeItem(BROWSER_IDENTITY_STORAGE_KEY);\n //删除cookie\n let cookie_options = {\n path: \"/\",\n expires: new Date(0),\n secure: true,\n sameSite: \"Lax\"\n };\n document.cookie = `${appId}_token=; ${Object.entries(cookie_options).map(([key, value]) => `${key}=${value}`).join('; ')}`;\n\n}\n\nexport function saveLocalAccountInfo(appId:string, account_info:AccountInfo) {\n if(account_info.session_token == null) {\n console.error(\"session_token is null,can't save account info\");\n return;\n }\n\n localStorage.setItem(getAccountStorageKey(appId), JSON.stringify(account_info));\n //session token用cookie存储\n let cookie_options = {\n path: \"/\",\n expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30), // 30天\n secure: true,\n sameSite: \"Lax\"\n };\n document.cookie = `${appId}_token=${account_info.session_token}; ${Object.entries(cookie_options).map(([key, value]) => `${key}=${value}`).join('; ')}`;\n}\n\nexport function saveBrowserUserInfo(userInfo:BrowserUserInfo) {\n localStorage.setItem(BROWSER_USER_INFO_STORAGE_KEY, JSON.stringify(userInfo));\n}\n\nexport function getBrowserUserInfo():BrowserUserInfo|null {\n return parseBrowserUserInfo(localStorage.getItem(BROWSER_USER_INFO_STORAGE_KEY));\n}\n\nexport function clearBrowserUserInfo() {\n localStorage.removeItem(BROWSER_USER_INFO_STORAGE_KEY);\n}\n\n/** The last current identity `/sso_refresh` returned (raw JSON, parse with `parseCurrentIdentity`). */\nexport function saveBrowserIdentity(identity:unknown) {\n localStorage.setItem(BROWSER_IDENTITY_STORAGE_KEY, JSON.stringify(identity));\n}\n\nexport function getBrowserIdentityRaw():unknown {\n const raw = localStorage.getItem(BROWSER_IDENTITY_STORAGE_KEY);\n if (!raw) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nexport function clearBrowserIdentity() {\n localStorage.removeItem(BROWSER_IDENTITY_STORAGE_KEY);\n}\n\n"],"names":["BROWSER_USER_INFO_STORAGE_KEY","BROWSER_IDENTITY_STORAGE_KEY","getAccountStorageKey","appId","localStorage","removeItem","cookie_options","path","expires","Date","secure","sameSite","document","cookie","Object","entries","map","key","value","join","raw","getItem","JSON","parse","parsed","userId","user_id","trim","userType","user_type","userNameCandidate","user_name","show_name","parseBrowserUserInfo","username","password","nonce","shaObj","jsSHA","encoding","update","org_password_hash_str","getHash","shaObj2","salt","toString","identity","setItem","stringify","userInfo","account_info","session_token","console","error","now"],"mappings":"wDAeMA,EAAgC,YAChCC,EAA+B,mBASrC,SAASC,EAAqBC,GAC1B,MAAO,wBAAwBA,GACnC,+BAkDO,SAA+BA,GACrBC,aAAAC,WAAWH,EAAqBC,IAC7CC,aAAaC,WAAWL,GACxBI,aAAaC,WAAWJ,GAExB,IAAIK,EAAiB,CACjBC,KAAM,IACNC,QAAa,IAAAC,KAAK,GAClBC,QAAQ,EACRC,SAAU,OAELC,SAAAC,OAAS,GAAGV,aAAiBW,OAAOC,QAAQT,GAAgBU,KAAI,EAAEC,EAAKC,KAAW,GAAGD,KAAOC,MAASC,KAAK,OAEvH,+BAgDO,WACHf,aAAaC,WAAWJ,EAC5B,+BAvBO,WACHG,aAAaC,WAAWL,EAC5B,gCAOO,WACG,MAAAoB,EAAMhB,aAAaiB,QAAQpB,GACjC,IAAKmB,EACM,OAAA,KAEP,IACO,OAAAE,KAAKC,MAAMH,EAAG,CACjB,MACG,OAAA,IACX,CACJ,6BAvBO,WACH,OArFJ,SAA8BA,GAC1B,GAAU,MAAPA,EACQ,OAAA,KAGP,IACM,MAAAI,EAASF,KAAKC,MAAMH,GAMpBK,EAAmC,iBAAnBD,EAAOE,QAAuBF,EAAOE,QAAQC,OAAS,GACtEC,EAAuC,iBAArBJ,EAAOK,UAAyBL,EAAOK,UAAUF,OAAS,GAC5EG,EAAgD,iBAArBN,EAAOO,UAClCP,EAAOO,UAAUJ,OACW,iBAArBH,EAA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