@astrale-os/cli 0.4.0-alpha.13

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 (219) hide show
  1. package/.check-workspace.cjs +40 -0
  2. package/README.md +151 -0
  3. package/dist/astrale.js +59749 -0
  4. package/package.json +90 -0
  5. package/src/command.ts +40 -0
  6. package/src/commands/__tests__/admin-instance.test.ts +73 -0
  7. package/src/commands/__tests__/auth-login.test.ts +178 -0
  8. package/src/commands/__tests__/auth-token.test.ts +223 -0
  9. package/src/commands/__tests__/call.test.ts +72 -0
  10. package/src/commands/__tests__/domain-list.test.ts +74 -0
  11. package/src/commands/__tests__/help-contract.test.ts +136 -0
  12. package/src/commands/__tests__/install-identity-override.test.ts +65 -0
  13. package/src/commands/__tests__/instance-bookmark.test.ts +101 -0
  14. package/src/commands/__tests__/instance-create-hosts.test.ts +29 -0
  15. package/src/commands/__tests__/instance-list-rows.test.ts +63 -0
  16. package/src/commands/__tests__/logs.test.ts +117 -0
  17. package/src/commands/__tests__/ls.test.ts +25 -0
  18. package/src/commands/__tests__/setup-plan.test.ts +61 -0
  19. package/src/commands/admin/status.ts +61 -0
  20. package/src/commands/admin/use.ts +77 -0
  21. package/src/commands/auth/login.ts +82 -0
  22. package/src/commands/auth/logout.ts +50 -0
  23. package/src/commands/auth/status.ts +86 -0
  24. package/src/commands/auth/token.ts +162 -0
  25. package/src/commands/browser.ts +207 -0
  26. package/src/commands/call.ts +300 -0
  27. package/src/commands/describe.ts +182 -0
  28. package/src/commands/domain/install.ts +420 -0
  29. package/src/commands/domain/list.ts +154 -0
  30. package/src/commands/domain/publish.ts +155 -0
  31. package/src/commands/get.ts +60 -0
  32. package/src/commands/identity/create.ts +26 -0
  33. package/src/commands/identity/delete.ts +18 -0
  34. package/src/commands/identity/export.ts +66 -0
  35. package/src/commands/identity/import.ts +101 -0
  36. package/src/commands/identity/list.ts +56 -0
  37. package/src/commands/identity/register.ts +170 -0
  38. package/src/commands/identity/sync.ts +32 -0
  39. package/src/commands/identity/unsync.ts +24 -0
  40. package/src/commands/identity/use.ts +18 -0
  41. package/src/commands/identity/whoami.ts +34 -0
  42. package/src/commands/idp/add.ts +150 -0
  43. package/src/commands/idp/list.ts +57 -0
  44. package/src/commands/idp/refresh.ts +38 -0
  45. package/src/commands/idp/remove.ts +36 -0
  46. package/src/commands/idp/show.ts +29 -0
  47. package/src/commands/instance/active.ts +64 -0
  48. package/src/commands/instance/bookmark.ts +72 -0
  49. package/src/commands/instance/create.ts +69 -0
  50. package/src/commands/instance/delete.ts +72 -0
  51. package/src/commands/instance/forget.ts +26 -0
  52. package/src/commands/instance/list.ts +149 -0
  53. package/src/commands/instance/status.ts +42 -0
  54. package/src/commands/instance/use.ts +210 -0
  55. package/src/commands/logs.ts +347 -0
  56. package/src/commands/ls.ts +229 -0
  57. package/src/commands/query.ts +32 -0
  58. package/src/commands/setup.ts +54 -0
  59. package/src/commands/status.ts +60 -0
  60. package/src/commands/studio.ts +401 -0
  61. package/src/commands/token.ts +77 -0
  62. package/src/commands/update.ts +267 -0
  63. package/src/commands/use.ts +87 -0
  64. package/src/errors.ts +65 -0
  65. package/src/kernel/__tests__/auth.test.ts +77 -0
  66. package/src/kernel/__tests__/errors.test.ts +43 -0
  67. package/src/kernel/__tests__/remote-routing.test.ts +70 -0
  68. package/src/kernel/auth.ts +234 -0
  69. package/src/kernel/ca-fetch.ts +119 -0
  70. package/src/kernel/client.ts +191 -0
  71. package/src/kernel/errors.ts +280 -0
  72. package/src/kernel/expand.ts +217 -0
  73. package/src/kernel/index.ts +14 -0
  74. package/src/kernel/options.ts +22 -0
  75. package/src/kernel/remote-routing.ts +88 -0
  76. package/src/kernel/run.ts +63 -0
  77. package/src/kernel/types.ts +14 -0
  78. package/src/lib/__tests__/admin-target.test.ts +112 -0
  79. package/src/lib/__tests__/binary.test.ts +56 -0
  80. package/src/lib/__tests__/command-dx.test.ts +58 -0
  81. package/src/lib/__tests__/concurrency.test.ts +62 -0
  82. package/src/lib/__tests__/config.test.ts +53 -0
  83. package/src/lib/__tests__/design.test.ts +99 -0
  84. package/src/lib/__tests__/domain-identity.test.ts +60 -0
  85. package/src/lib/__tests__/format.test.ts +22 -0
  86. package/src/lib/__tests__/fs-atomic.test.ts +104 -0
  87. package/src/lib/__tests__/identity.test.ts +79 -0
  88. package/src/lib/__tests__/idp-session.driver.ts +53 -0
  89. package/src/lib/__tests__/idp-session.test.ts +357 -0
  90. package/src/lib/__tests__/idp.test.ts +385 -0
  91. package/src/lib/__tests__/instance-candidates.test.ts +73 -0
  92. package/src/lib/__tests__/instance-target.test.ts +183 -0
  93. package/src/lib/__tests__/instance.test.ts +136 -0
  94. package/src/lib/__tests__/keys.test.ts +129 -0
  95. package/src/lib/__tests__/local-status.test.ts +202 -0
  96. package/src/lib/__tests__/output.test.ts +150 -0
  97. package/src/lib/__tests__/panel.test.ts +40 -0
  98. package/src/lib/__tests__/port.test.ts +44 -0
  99. package/src/lib/__tests__/prompt.test.ts +25 -0
  100. package/src/lib/__tests__/sdk-deps.test.ts +68 -0
  101. package/src/lib/__tests__/self.test.ts +272 -0
  102. package/src/lib/__tests__/studio-server-deps.test.ts +74 -0
  103. package/src/lib/__tests__/table.test.ts +53 -0
  104. package/src/lib/__tests__/update.test.ts +246 -0
  105. package/src/lib/__tests__/use-target.test.ts +56 -0
  106. package/src/lib/__tests__/validation.test.ts +34 -0
  107. package/src/lib/admin-domain.ts +25 -0
  108. package/src/lib/admin-instance.ts +26 -0
  109. package/src/lib/admin-target.ts +217 -0
  110. package/src/lib/binary.ts +131 -0
  111. package/src/lib/browser.ts +150 -0
  112. package/src/lib/command-dx.ts +161 -0
  113. package/src/lib/concurrency.ts +31 -0
  114. package/src/lib/config.ts +45 -0
  115. package/src/lib/domain-identity.ts +49 -0
  116. package/src/lib/env.ts +49 -0
  117. package/src/lib/format.ts +4 -0
  118. package/src/lib/fs-atomic.ts +126 -0
  119. package/src/lib/identity.ts +256 -0
  120. package/src/lib/idp-session.ts +134 -0
  121. package/src/lib/idp.ts +876 -0
  122. package/src/lib/instance-candidates.ts +49 -0
  123. package/src/lib/instance-target.ts +182 -0
  124. package/src/lib/instance.ts +395 -0
  125. package/src/lib/keys.ts +294 -0
  126. package/src/lib/local-status.ts +152 -0
  127. package/src/lib/log.ts +116 -0
  128. package/src/lib/login-flow.ts +164 -0
  129. package/src/lib/meta.ts +86 -0
  130. package/src/lib/output.ts +222 -0
  131. package/src/lib/panel.ts +61 -0
  132. package/src/lib/paths.ts +11 -0
  133. package/src/lib/port.ts +41 -0
  134. package/src/lib/proc.ts +82 -0
  135. package/src/lib/prompt.ts +136 -0
  136. package/src/lib/provision-instance.ts +170 -0
  137. package/src/lib/sdk-deps.ts +104 -0
  138. package/src/lib/self.ts +166 -0
  139. package/src/lib/skills.ts +171 -0
  140. package/src/lib/table.ts +62 -0
  141. package/src/lib/update.ts +315 -0
  142. package/src/lib/use-target.ts +24 -0
  143. package/src/lib/validation.ts +59 -0
  144. package/src/program.ts +200 -0
  145. package/src/registry.ts +59 -0
  146. package/src/setup/__tests__/util.test.ts +29 -0
  147. package/src/setup/engine.ts +83 -0
  148. package/src/setup/render.ts +109 -0
  149. package/src/setup/steps/admin.ts +78 -0
  150. package/src/setup/steps/agent-browser.ts +81 -0
  151. package/src/setup/steps/auth.ts +54 -0
  152. package/src/setup/steps/domain.ts +68 -0
  153. package/src/setup/steps/index.ts +18 -0
  154. package/src/setup/steps/instance.ts +119 -0
  155. package/src/setup/steps/skills-bridge.ts +70 -0
  156. package/src/setup/steps/skills.ts +59 -0
  157. package/src/setup/types.ts +61 -0
  158. package/src/setup/util.ts +34 -0
  159. package/src/test-utils.ts +18 -0
  160. package/studio/client/dist/assets/index-DOwzZAEK.css +1 -0
  161. package/studio/client/dist/assets/index-wtU0Zxhy.js +183 -0
  162. package/studio/client/dist/index.html +13 -0
  163. package/studio/package.json +62 -0
  164. package/studio/server/agent/ask.ts +68 -0
  165. package/studio/server/agent/bridge-mcp.ts +182 -0
  166. package/studio/server/agent/bridge.ts +188 -0
  167. package/studio/server/agent/claude.ts +666 -0
  168. package/studio/server/agent/mock.ts +186 -0
  169. package/studio/server/agent/prompt.ts +202 -0
  170. package/studio/server/agent/registry.ts +29 -0
  171. package/studio/server/agent/runner.ts +484 -0
  172. package/studio/server/agent/schema-map.ts +112 -0
  173. package/studio/server/agent/types.ts +120 -0
  174. package/studio/server/api.ts +574 -0
  175. package/studio/server/cache.ts +138 -0
  176. package/studio/server/detect.ts +81 -0
  177. package/studio/server/domain.ts +70 -0
  178. package/studio/server/index.ts +136 -0
  179. package/studio/server/introspect/anatomy-extras.ts +398 -0
  180. package/studio/server/introspect/anatomy.ts +108 -0
  181. package/studio/server/introspect/bundle.ts +57 -0
  182. package/studio/server/introspect/core-extractor.ts +119 -0
  183. package/studio/server/introspect/core.ts +44 -0
  184. package/studio/server/introspect/diff.ts +133 -0
  185. package/studio/server/introspect/extractor.ts +102 -0
  186. package/studio/server/introspect/hash.ts +21 -0
  187. package/studio/server/introspect/overlay-tsmorph.ts +874 -0
  188. package/studio/server/introspect/overlay.ts +57 -0
  189. package/studio/server/introspect/runtime.ts +99 -0
  190. package/studio/server/introspect/schema-refs.ts +46 -0
  191. package/studio/server/lifecycle.ts +38 -0
  192. package/studio/server/sse.ts +57 -0
  193. package/studio/server/state/baseline.ts +211 -0
  194. package/studio/server/state/catalog.ts +117 -0
  195. package/studio/server/state/comments.ts +321 -0
  196. package/studio/server/state/context.ts +167 -0
  197. package/studio/server/state/copy.ts +156 -0
  198. package/studio/server/state/create.ts +156 -0
  199. package/studio/server/state/documents.ts +70 -0
  200. package/studio/server/state/env.ts +161 -0
  201. package/studio/server/state/git.ts +75 -0
  202. package/studio/server/state/handoff.ts +55 -0
  203. package/studio/server/state/harness-gateway.ts +181 -0
  204. package/studio/server/state/harness-token.ts +0 -0
  205. package/studio/server/state/instance.ts +244 -0
  206. package/studio/server/state/integrations.ts +55 -0
  207. package/studio/server/state/layout.ts +55 -0
  208. package/studio/server/state/settings.ts +39 -0
  209. package/studio/server/state/store.ts +97 -0
  210. package/studio/server/state/updates.ts +63 -0
  211. package/studio/server/state/usage.ts +37 -0
  212. package/studio/server/state/views.ts +138 -0
  213. package/studio/server/state/visibility.ts +33 -0
  214. package/studio/server/watch.ts +81 -0
  215. package/studio/server/workspace-state.ts +26 -0
  216. package/studio/server/workspace-watch.ts +101 -0
  217. package/studio/shared/types.ts +873 -0
  218. package/studio/tsconfig.json +23 -0
  219. package/tsconfig.json +14 -0
@@ -0,0 +1,60 @@
1
+ import chalk from 'chalk'
2
+
3
+ import type { CommandDefinition } from '../command'
4
+
5
+ import { readLocalStatus } from '../lib/local-status'
6
+ import { log } from '../lib/log'
7
+ import { isMachine, output, RAW_OUTPUT_OPTIONS } from '../lib/output'
8
+
9
+ export default {
10
+ name: 'status',
11
+ description: 'Show local CLI context: active instance, identity, and cached auth state',
12
+ options: [...RAW_OUTPUT_OPTIONS],
13
+ action: async (opts: { raw?: boolean; json?: boolean }) => {
14
+ const status = await readLocalStatus()
15
+
16
+ if (isMachine(opts)) {
17
+ output(status, opts)
18
+ return
19
+ }
20
+
21
+ console.log(chalk.bold('Admin'))
22
+ if ('error' in status.admin) {
23
+ console.log(` ${chalk.red('invalid')}: ${status.admin.error}`)
24
+ } else {
25
+ console.log(` ${chalk.bold(status.admin.name)} ${chalk.dim(status.admin.url)}`)
26
+ }
27
+
28
+ console.log('')
29
+ console.log(chalk.bold('Instance'))
30
+ if (status.instance) {
31
+ console.log(` ${chalk.bold(status.instance.active)} ${chalk.dim(status.instance.url)}`)
32
+ if (status.instance.issuer) console.log(` issuer: ${chalk.dim(status.instance.issuer)}`)
33
+ if (status.instance.defaultIdentity) {
34
+ console.log(` default identity: ${status.instance.defaultIdentity}`)
35
+ }
36
+ } else {
37
+ log.dim(' No active instance. Run: astrale instance bookmark <name> --url <url> --use')
38
+ }
39
+
40
+ console.log('')
41
+ console.log(chalk.bold('Identity'))
42
+ if (status.identity) {
43
+ const source =
44
+ status.identity.source === 'idp'
45
+ ? `idp:${status.identity.idp ?? 'unknown'}`
46
+ : status.identity.source
47
+ console.log(` ${chalk.bold(status.identity.name)} ${chalk.dim(`[${source}]`)}`)
48
+ console.log(` subject: ${chalk.dim(status.identity.subject)}`)
49
+ if (status.identity.session) {
50
+ const state =
51
+ !status.identity.session.cached || status.identity.session.requiresLogin
52
+ ? chalk.yellow('login required')
53
+ : chalk.green('ready')
54
+ console.log(` session: ${state}`)
55
+ }
56
+ } else {
57
+ log.dim(' No default identity. Run: astrale identity create <name>')
58
+ }
59
+ },
60
+ } satisfies CommandDefinition
@@ -0,0 +1,401 @@
1
+ import type { ChildProcess } from 'node:child_process'
2
+
3
+ import { existsSync, realpathSync } from 'node:fs'
4
+ import { dirname, join, resolve } from 'node:path'
5
+
6
+ import type { CommandDefinition } from '../command'
7
+
8
+ import { fatal, log } from '../lib/log'
9
+ import { isMachine, output, RAW_OUTPUT_OPTIONS, type RawOutputOpts } from '../lib/output'
10
+ import { findFreePort, portFree } from '../lib/port'
11
+ import { run, spawnHandle } from '../lib/proc'
12
+
13
+ type StudioOpts = RawOutputOpts & {
14
+ port?: string
15
+ open?: boolean // `--open` → true. Default (undefined) prints the URL without launching a browser.
16
+ dev?: boolean
17
+ prod?: boolean
18
+ schemaDir?: string
19
+ }
20
+
21
+ // Uncommon, safe bands in the IANA Registered range (well below the OS
22
+ // ephemeral range), away from the popular dev ports (3000/5173/8080/…).
23
+ // Concurrent studios in different workspaces ladder up: 4319, 4320, 4321…
24
+ const STUDIO_PORT_BASE = 4319
25
+ const VITE_PORT_BASE = 5273
26
+ const PORT_SPAN = 20
27
+
28
+ /**
29
+ * Locate the studio package shipped with / alongside the CLI. Anchored to the
30
+ * resolved CLI ENTRY (process.argv[1], deref'd through any install symlink) —
31
+ * NOT import.meta.url, which differs between the bundled dist and the unbundled
32
+ * source run. From `<cli>/bin/astrale.ts`, `<cli>/dist/astrale.js`, or a
33
+ * published `<pkg>/dist/astrale.js`, the studio is the sibling `../studio`.
34
+ * `ASTRALE_STUDIO_DIR` overrides everything (point at an out-of-tree checkout).
35
+ */
36
+ function resolveStudioDir(): string {
37
+ const candidates: string[] = []
38
+ if (process.env.ASTRALE_STUDIO_DIR) candidates.push(process.env.ASTRALE_STUDIO_DIR)
39
+ try {
40
+ const entryDir = dirname(realpathSync(process.argv[1] ?? ''))
41
+ candidates.push(join(entryDir, '..', 'studio'), join(entryDir, 'studio'))
42
+ } catch {
43
+ /* argv[1] unreadable — fall through to the error below */
44
+ }
45
+ for (const c of candidates) {
46
+ if (existsSync(join(c, 'server', 'index.ts'))) return resolve(c)
47
+ }
48
+ throw new Error(
49
+ `Domain Studio assets not found (looked in: ${candidates.join(', ') || '<none>'}). ` +
50
+ `Reinstall the astrale CLI, or set ASTRALE_STUDIO_DIR to a studio checkout.`,
51
+ )
52
+ }
53
+
54
+ /** Dev iff the resolved studio dir is the MONOREPO SOURCE — the published copy ships only client/dist (no client/src, no vite.config). */
55
+ function isDevSource(studioDir: string): boolean {
56
+ return (
57
+ existsSync(join(studioDir, 'vite.config.ts')) && existsSync(join(studioDir, 'client', 'src'))
58
+ )
59
+ }
60
+
61
+ /**
62
+ * Resolve the Vite launcher bin. We spawn it DIRECTLY (not via `bun x vite`):
63
+ * the pnpm `.bin/vite` shim stays inside our detached process group, so a group
64
+ * kill reaps it cleanly — `bun x` forks Vite as a grandchild that escapes and
65
+ * orphans. Checks the package's own node_modules first, then the hoisted root.
66
+ */
67
+ function resolveViteBin(studioDir: string): string | null {
68
+ for (const c of [
69
+ join(studioDir, 'node_modules', '.bin', 'vite'),
70
+ join(studioDir, '..', '..', 'node_modules', '.bin', 'vite'),
71
+ ]) {
72
+ if (existsSync(c)) return c
73
+ }
74
+ return null
75
+ }
76
+
77
+ /** The studio server is a Bun server (Bun.serve/import.meta.dir); fail early with a hint if Bun is absent rather than surfacing a raw child ENOENT. */
78
+ async function ensureBun(): Promise<void> {
79
+ try {
80
+ if ((await run('bun', ['--version'])).code === 0) return
81
+ } catch {
82
+ /* ENOENT — handled below */
83
+ }
84
+ throw new Error(
85
+ 'Domain Studio requires Bun on PATH. Install it from https://bun.sh, then re-run `astrale studio`.',
86
+ )
87
+ }
88
+
89
+ /** Poll a URL until it answers (any HTTP response = up) or the deadline passes. */
90
+ async function waitForHttp(url: string, timeoutMs = 20_000): Promise<boolean> {
91
+ const deadline = Date.now() + timeoutMs
92
+ while (Date.now() < deadline) {
93
+ try {
94
+ await fetch(url, { signal: AbortSignal.timeout(1000) })
95
+ return true
96
+ } catch {
97
+ await new Promise((r) => setTimeout(r, 150))
98
+ }
99
+ }
100
+ return false
101
+ }
102
+
103
+ function openBrowser(url: string): void {
104
+ // win32: `start` is a cmd.exe builtin, not a PATH executable — must go through
105
+ // `cmd /c start "" <url>` (the empty "" is the title arg `start` consumes).
106
+ const [cmd, args] =
107
+ process.platform === 'darwin'
108
+ ? ['open', [url]]
109
+ : process.platform === 'win32'
110
+ ? ['cmd', ['/c', 'start', '', url]]
111
+ : ['xdg-open', [url]]
112
+ try {
113
+ spawnHandle(cmd, args as string[], { stdio: 'ignore' }).unref()
114
+ } catch {
115
+ /* best-effort; headless ok */
116
+ }
117
+ }
118
+
119
+ async function pickPort(
120
+ explicit: string | undefined,
121
+ base: number,
122
+ label: string,
123
+ ): Promise<number> {
124
+ if (explicit !== undefined) {
125
+ // Strict decimal — reject '4e3', '0x10D7', whitespace-padded, etc.
126
+ const p = /^\d+$/.test(explicit) ? Number(explicit) : NaN
127
+ if (!Number.isInteger(p) || p < 1 || p > 65535) throw new Error(`invalid --port: ${explicit}`)
128
+ // Explicit intent must NOT be silently relocated — probe once, error if busy.
129
+ if (!(await portFree(p))) {
130
+ throw new Error(
131
+ `port ${p} is busy (another studio?). Pick a free --port, or omit it to auto-select.`,
132
+ )
133
+ }
134
+ return p
135
+ }
136
+ const p = await findFreePort(base, PORT_SPAN)
137
+ if (p === null)
138
+ throw new Error(`no free ${label} port in ${base}-${base + PORT_SPAN - 1}; pass --port`)
139
+ return p
140
+ }
141
+
142
+ export default {
143
+ name: 'studio',
144
+ description: 'Launch the local Domain Studio GUI for a workspace',
145
+ arguments: [
146
+ {
147
+ name: 'path',
148
+ description: 'Workspace or domain dir to open (default: current dir)',
149
+ required: false,
150
+ },
151
+ ],
152
+ options: [
153
+ { flags: '--port <n>', description: 'Studio HTTP port (default: first free in 4319-4338)' },
154
+ {
155
+ flags: '--open',
156
+ description: 'Open the studio in your browser (default: just print the URL)',
157
+ },
158
+ {
159
+ flags: '--dev',
160
+ description:
161
+ 'Live-edit mode for hacking on the studio itself (Vite HMR + server reload; needs the source checkout)',
162
+ },
163
+ { flags: '--prod', description: 'Serve the prebuilt client (the default)' },
164
+ { flags: '--schema-dir <dir>', description: 'Schema entry dir to scan for (default: schema)' },
165
+ ...RAW_OUTPUT_OPTIONS,
166
+ ],
167
+ afterHelpText: `
168
+ Behavior:
169
+ Launches the Domain Studio — a local web GUI to author and inspect a domain —
170
+ pointed at <path> (the current directory by default), so you can run it from
171
+ any workspace. The studio is a Bun server (Bun is required on PATH) shipped with
172
+ the CLI; the command locates it next to the astrale binary (override with
173
+ ASTRALE_STUDIO_DIR).
174
+
175
+ Port: binds the first free loopback port in 4319-4338, so a studio already
176
+ running in another workspace simply takes the next port (4320, 4321, …). An
177
+ explicit --port is used as-is, or errors if busy (never silently relocated).
178
+
179
+ By DEFAULT it serves the prebuilt client (fast, always works — this is what a
180
+ published install runs). --dev is the live-edit loop for hacking on the studio
181
+ ITSELF: a Vite dev server (client HMR) + a watched server (reloads on edits) so
182
+ studio changes reflect instantly; it requires the studio source checkout
183
+ (cli/studio) with Vite installed.
184
+
185
+ By default the command just PRINTS the URL — it does not pop a browser (that's
186
+ invasive when you already have a tab open). Pass --open to launch one.
187
+
188
+ The command stays attached and supervises its child processes; Ctrl-C tears
189
+ them all down (a second Ctrl-C force-kills). With --json it prints a
190
+ { url, port, mode, workspace } descriptor.
191
+
192
+ Examples:
193
+ $ astrale studio # start the studio + print its URL (no browser)
194
+ $ astrale studio --open # …and open it in a browser
195
+ $ astrale studio ./my-domain
196
+ $ astrale studio --port 4400
197
+ $ astrale studio --dev # live-edit the studio itself (from source)
198
+ `,
199
+ action: async (pathArg: string | undefined, opts: StudioOpts) => {
200
+ try {
201
+ const workspace = resolve(pathArg ?? process.cwd())
202
+ if (!existsSync(workspace)) throw new Error(`path not found: ${workspace}`)
203
+
204
+ const studioDir = resolveStudioDir()
205
+ if (process.env.ASTRALE_STUDIO_DIR && studioDir === resolve(process.env.ASTRALE_STUDIO_DIR)) {
206
+ log.dim(` using ASTRALE_STUDIO_DIR=${studioDir}`)
207
+ }
208
+ await ensureBun()
209
+
210
+ // Default to PROD — serve the prebuilt client. It always renders, is what a
211
+ // published/global install runs, and avoids dev's heavy source-module graph.
212
+ // --dev opts into the live-edit loop, which needs the studio SOURCE
213
+ // (cli/studio) with Vite installed.
214
+ const dev = opts.dev === true
215
+ let viteBin: string | null = null
216
+ if (dev) {
217
+ if (!isDevSource(studioDir)) {
218
+ throw new Error(
219
+ '--dev needs the studio source checkout (cli/studio); a published install runs prod only.',
220
+ )
221
+ }
222
+ viteBin = resolveViteBin(studioDir)
223
+ if (!viteBin)
224
+ throw new Error('Vite is not installed — run `pnpm install` at the workspace root.')
225
+ }
226
+
227
+ const studioPort = await pickPort(opts.port, STUDIO_PORT_BASE, 'studio')
228
+ if (opts.port === undefined && studioPort !== STUDIO_PORT_BASE) {
229
+ log.dim(` port ${STUDIO_PORT_BASE} busy (another studio?) — using ${studioPort}`)
230
+ }
231
+ const displayUrl = `http://localhost:${studioPort}`
232
+ // The studio server binds 127.0.0.1, so we PROBE IPv4 explicitly — `localhost`
233
+ // can resolve to ::1 first, which a 127.0.0.1-only listener won't answer.
234
+ const probeUrl = `http://127.0.0.1:${studioPort}/`
235
+
236
+ // Supervise the child processes. Each runs in its OWN process group
237
+ // (detached) so one group signal tears down the whole tree — Vite, the
238
+ // watched server, and their grandchildren (extractor / MCP islands). We
239
+ // track liveness (so we never group-signal an exited child — PID-reuse
240
+ // safe), escalate SIGTERM→SIGKILL on a timeout (an unresponsive child — long
241
+ // SSE / in-flight agent turn — can't wedge the CLI), and a second Ctrl-C
242
+ // force-kills immediately. Handlers attach synchronously at spawn, so a
243
+ // fast-failing child is never missed and a dead child downs the rest.
244
+ const children: ChildProcess[] = []
245
+ const alive = new Set<ChildProcess>()
246
+ let shuttingDown = false
247
+ let failed = false
248
+ let killTimer: ReturnType<typeof setTimeout> | undefined
249
+ const signalGroup = (c: ChildProcess, sig: NodeJS.Signals) => {
250
+ if (c.pid === undefined || !alive.has(c)) return
251
+ try {
252
+ process.kill(-c.pid, sig) // negative pid → the process group (POSIX)
253
+ } catch {
254
+ try {
255
+ c.kill(sig)
256
+ } catch {
257
+ /* gone, or win32 group semantics unsupported */
258
+ }
259
+ }
260
+ }
261
+ const killAll = () => {
262
+ if (shuttingDown) {
263
+ for (const c of children) signalGroup(c, 'SIGKILL') // second signal → escalate now
264
+ return
265
+ }
266
+ shuttingDown = true
267
+ for (const c of children) signalGroup(c, 'SIGTERM')
268
+ killTimer = setTimeout(() => {
269
+ for (const c of children) signalGroup(c, 'SIGKILL')
270
+ }, 5_000)
271
+ killTimer.unref?.()
272
+ }
273
+ const supervise = (c: ChildProcess, role: string): ChildProcess => {
274
+ children.push(c)
275
+ alive.add(c)
276
+ c.once('error', (err) => {
277
+ failed = true
278
+ log.error(` studio ${role} failed: ${err instanceof Error ? err.message : String(err)}`)
279
+ killAll()
280
+ })
281
+ c.once('exit', () => {
282
+ alive.delete(c)
283
+ if (alive.size === 0 && killTimer) clearTimeout(killTimer)
284
+ if (!shuttingDown) {
285
+ failed = true // a child died on its own → tear the rest down
286
+ killAll()
287
+ }
288
+ })
289
+ return c
290
+ }
291
+ process.on('SIGINT', killAll)
292
+ process.on('SIGTERM', killAll)
293
+
294
+ let serverChild: ChildProcess
295
+ if (dev && viteBin) {
296
+ const vitePort = await pickPort(undefined, VITE_PORT_BASE, 'vite')
297
+ // Bind Vite to IPv4 loopback explicitly — its default `localhost` binds
298
+ // ONLY ::1 here, which the 127.0.0.1 server-side proxy and our probe
299
+ // can't reach. --strictPort: the server must know Vite's exact port.
300
+ supervise(
301
+ spawnHandle(
302
+ viteBin,
303
+ ['--host', '127.0.0.1', '--port', String(vitePort), '--strictPort'],
304
+ {
305
+ cwd: studioDir,
306
+ detached: true,
307
+ // STUDIO_VITE_PORT → vite.config points the HMR WebSocket at Vite
308
+ // directly (the page is served via the studio proxy on another port).
309
+ env: { ...process.env, STUDIO_VITE_PORT: String(vitePort) },
310
+ },
311
+ ),
312
+ 'vite',
313
+ )
314
+ if (!(await waitForHttp(`http://127.0.0.1:${vitePort}/`))) {
315
+ killAll()
316
+ await new Promise((r) => setTimeout(r, 500)) // let SIGTERM land before we exit
317
+ throw new Error(
318
+ 'Vite dev server did not start — run `pnpm install` at the workspace root, or use --prod.',
319
+ )
320
+ }
321
+ serverChild = supervise(
322
+ spawnHandle(
323
+ 'bun',
324
+ ['--watch', 'server/index.ts', workspace, '--port', String(studioPort), '--no-open'],
325
+ {
326
+ cwd: studioDir,
327
+ detached: true,
328
+ env: {
329
+ ...process.env,
330
+ DOMAIN_STUDIO_DEV: '1',
331
+ VITE_URL: `http://127.0.0.1:${vitePort}`,
332
+ PORT: String(studioPort),
333
+ DOMAIN_STUDIO_HOST: '127.0.0.1',
334
+ },
335
+ },
336
+ ),
337
+ 'server',
338
+ )
339
+ } else {
340
+ const dist = join(studioDir, 'client', 'dist')
341
+ if (!existsSync(join(dist, 'index.html'))) {
342
+ throw new Error(
343
+ `studio client not built at ${dist} — run: pnpm --filter @astrale-os/studio build`,
344
+ )
345
+ }
346
+ serverChild = supervise(
347
+ spawnHandle(
348
+ 'bun',
349
+ ['server/index.ts', workspace, '--port', String(studioPort), '--no-open'],
350
+ {
351
+ cwd: studioDir,
352
+ detached: true,
353
+ env: {
354
+ ...process.env,
355
+ DOMAIN_STUDIO_DIST: dist,
356
+ PORT: String(studioPort),
357
+ DOMAIN_STUDIO_HOST: '127.0.0.1',
358
+ },
359
+ },
360
+ ),
361
+ 'server',
362
+ )
363
+ }
364
+
365
+ // Resolve when the studio server ends (Ctrl-C, crash, or kill). Attached
366
+ // synchronously right after spawn — never lost to a race with a fast exit.
367
+ // NOTE: in dev the server runs under `bun --watch`, which survives an
368
+ // uncaught crash to hot-restart on the next edit (the intended edit loop), so
369
+ // the CLI stays attached until you Ctrl-C — which always tears it down.
370
+ const serverDone = new Promise<number>((res) =>
371
+ serverChild.once('exit', (code) => res(code ?? 0)),
372
+ )
373
+
374
+ if (!isMachine(opts))
375
+ log.step(
376
+ `Starting Domain Studio${dev ? ' (dev)' : ''} — ${displayUrl} (indexing the workspace…)`,
377
+ )
378
+ // Indexing a multi-domain workspace is genuinely slow (the server boots +
379
+ // introspects every domain before it answers), so be patient — `waitForHttp`
380
+ // returns the instant the server is up, and only hits this ceiling in a
381
+ // pathological case. We open the browser once it actually answers.
382
+ const ready = await waitForHttp(probeUrl, 180_000)
383
+ if (isMachine(opts)) {
384
+ output({ url: displayUrl, port: studioPort, mode: dev ? 'dev' : 'prod', workspace }, opts)
385
+ } else {
386
+ log.success(`Domain Studio${dev ? ' (dev — live reload)' : ''}`)
387
+ log.info(` ${workspace}`)
388
+ log.info(` → ${displayUrl}`)
389
+ if (!ready) log.warn(' still starting — open the URL above once it finishes indexing.')
390
+ }
391
+ if (ready && opts.open === true) openBrowser(displayUrl)
392
+
393
+ // Stay attached until the studio server ends; surface a non-zero code when a
394
+ // child FAILURE (not a user Ctrl-C) drove the teardown.
395
+ const code = await serverDone
396
+ process.exitCode = failed && code === 0 ? 1 : code
397
+ } catch (e) {
398
+ fatal(e)
399
+ }
400
+ },
401
+ } satisfies CommandDefinition
@@ -0,0 +1,77 @@
1
+ import type { CommandDefinition } from '../command'
2
+ import type { KernelCommandOpts } from '../kernel'
3
+
4
+ import { runKernelCommand } from '../kernel'
5
+ import { mintDelegationPath } from '../kernel/remote-routing'
6
+ import { log } from '../lib/log'
7
+
8
+ /**
9
+ * `astrale token` — mint a fresh delegation token for the active instance
10
+ * + active identity (§2.5). Shortcut over the mintDelegationCredential call.
11
+ */
12
+ export type TokenOpts = KernelCommandOpts & {
13
+ audience?: string
14
+ ttl?: string
15
+ // `--for <identity>` is an alias of `--as` (reads better at mint-time).
16
+ // Promoted into opts.as before the credential resolver runs.
17
+ for?: string
18
+ }
19
+
20
+ export async function tokenCommand(opts: TokenOpts): Promise<void> {
21
+ if (opts.for && !opts.as) opts.as = opts.for
22
+ await runKernelCommand<string>({
23
+ opts,
24
+ label: 'Minting delegation token',
25
+ fn: async (ctx) => {
26
+ const audience = opts.audience ?? ''
27
+ const parsedTtl = Number(opts.ttl)
28
+ const ttl = Number.isFinite(parsedTtl) && parsedTtl > 0 ? parsedTtl : 3600
29
+ const mintPath = await mintDelegationPath(ctx.client, ctx.credential)
30
+ const result = (await ctx.client.call(mintPath, {
31
+ audience,
32
+ delegation: { kind: 'identity', self: true },
33
+ ttl,
34
+ })) as string
35
+ return result
36
+ },
37
+ format: (token, fmtOpts, isRaw) => {
38
+ if (isRaw) {
39
+ process.stdout.write(token + '\n')
40
+ return
41
+ }
42
+ log.dim(' (delegation token — ES256, self-identity)')
43
+ process.stdout.write(`${token}\n`)
44
+ },
45
+ })
46
+ }
47
+
48
+ export default {
49
+ name: 'token',
50
+ description: 'Mint a fresh delegation token for the active instance + identity',
51
+ afterHelpText: `
52
+ Behavior:
53
+ Default ttl 3600s, audience empty. The result is a two-layer
54
+ envelope: an outer JWT signed by the kernel system key
55
+ (sub __system__) wrapping an inner ES256 delegation credential for
56
+ the identity. The token aud must match the worker's expected
57
+ audience or the worker rejects it. --for is an alias of --as.
58
+
59
+ What this token is FOR — worker-direct HTTP calls:
60
+ Use it as a Bearer token against a domain worker's own URL
61
+ (curl/fetch to its remote functions). It carries NO .grant claim,
62
+ so it CANNOT drive a raw kernel ClientSession — for kernel calls
63
+ use 'astrale call' (which signs per-call) instead.
64
+
65
+ Examples:
66
+ $ export TOKEN=$(astrale token --audience dist.astrale.ai --raw)
67
+ $ astrale token --audience worker.example.com --for alice -i staging
68
+ `,
69
+ options: [
70
+ { flags: '--audience <aud>', description: 'Token audience (defaults to empty)' },
71
+ { flags: '--ttl <sec>', description: 'TTL in seconds (default: 3600)' },
72
+ { flags: '--for <identity>', description: 'Mint the token for this identity (alias of --as)' },
73
+ ],
74
+ action: async (opts) => {
75
+ await tokenCommand(opts as Parameters<typeof tokenCommand>[0])
76
+ },
77
+ } satisfies CommandDefinition