@struktoai/mirage-cli 0.0.1 → 0.0.2

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.
package/README.md CHANGED
@@ -23,135 +23,125 @@
23
23
  <img src="https://img.shields.io/npm/v/%40struktoai%2Fmirage-cli.svg?color=0C0C0C&labelColor=FAFAFA"/></a>
24
24
  </p>
25
25
 
26
- Mirage is **a Unified Virtual File System for AI Agents**: a single tree that mounts services and data sources like S3, Google Drive, Slack, Gmail, and Redis side-by-side as one filesystem.
26
+ <p align="center">
27
+ <a href="https://github.com/strukto-ai/mirage#readme"><img alt="README in English" src="https://img.shields.io/badge/English-d9d9d9"></a>
28
+ <a href="https://github.com/strukto-ai/mirage/blob/main/readme/README.zh-CN.md"><img alt="简体中文 README" src="https://img.shields.io/badge/简体中文-d9d9d9"></a>
29
+ <a href="https://github.com/strukto-ai/mirage/blob/main/readme/README.zh-TW.md"><img alt="繁體中文 README" src="https://img.shields.io/badge/繁體中文-d9d9d9"></a>
30
+ <a href="https://github.com/strukto-ai/mirage/blob/main/readme/README.fr.md"><img alt="README en Français" src="https://img.shields.io/badge/Français-d9d9d9"></a>
31
+ <a href="https://github.com/strukto-ai/mirage/blob/main/readme/README.vi.md"><img alt="README Tiếng Việt" src="https://img.shields.io/badge/Ti%E1%BA%BFng%20Vi%E1%BB%87t-d9d9d9"></a>
32
+ <a href="https://github.com/strukto-ai/mirage/blob/main/readme/README.ko.md"><img alt="README 한국어" src="https://img.shields.io/badge/%ED%95%9C%EA%B5%AD%EC%96%B4-d9d9d9"></a>
33
+ </p>
27
34
 
28
- AI agents reach every backend with the same handful of Unix-like tools, and pipelines compose across services as naturally as on a local disk. It's a simulated environment, agents see one filesystem underneath. Any LLM that already knows bash can use Mirage out of the box, with zero new vocabulary.
35
+ Mirage is **a Unified Virtual File System for AI Agents**: it mounts services and data sources like S3, Google Drive, Slack, Gmail, and Redis side-by-side as one filesystem. Any LLM that already knows bash can read, grep, and pipe across every backend out of the box, with zero new vocabulary.
29
36
 
30
37
  ```ts
31
38
  const ws = new Workspace({
32
- '/data': new RAMResource(),
33
- '/s3': new S3Resource({ bucket: 'logs' }),
34
- '/slack': new SlackResource({}),
35
- '/github': new GitHubResource({}),
39
+ '/data': new RAMResource(),
40
+ '/s3': new S3Resource({ bucket: 'logs' }),
41
+ '/slack': new SlackResource({ token: process.env.SLACK_BOT_TOKEN! }),
36
42
  })
37
43
 
38
- await ws.execute('grep alert /slack/general/*.json | wc -l')
39
- await ws.execute('cat /github/mirage/README.md')
44
+ await ws.execute('grep -r alert /slack/channels/general__C04QX/ | wc -l')
40
45
  await ws.execute('cp /s3/report.csv /data/local.csv')
46
+ await ws.execute('wc -l $(find /s3/data -name "*.jsonl")')
47
+
48
+ // Commands are extensible: register new commands, or override one per
49
+ // resource + filetype, e.g. `cat` on S3 Parquet renders rows as JSON.
50
+ ws.command('summarize', ...)
51
+ ws.command('cat', { resource: 's3', filetype: 'parquet' }, ...)
52
+
53
+ await ws.execute('summarize /data/local.csv')
54
+ await ws.execute('cat /s3/events/2026-05-06.parquet | jq .user')
41
55
  ```
42
56
 
43
57
  ## About
44
58
 
45
- - **One filesystem, every backend.** Every service speaks the same filesystem semantics, so agents reason about one abstraction instead of N SDKs and M MCPs, leaning on the filesystem and bash vocabulary LLMs are most fluent in.
46
- - **Multiple resources, one filesystem:** RAM, Disk, Redis, S3 / R2 / OCI / Supabase / GCS, Gmail / GDrive / GDocs / GSheets / GSlides, GitHub / Linear / Notion / Trello, Slack / Discord / Telegram / Email, MongoDB, SSH, and more, mounted side-by-side under a single root.
47
- - **Familiar bash tools across every mount.** Agents reuse the same handful of Unix-like tools instead of learning a new API per service, and pipelines compose across services as naturally as on a local disk, the exact corpus modern LLMs are most heavily trained on.
48
- - **Portable workspaces:** clone, snapshot, and version your environment. Move agent runs between machines without restarting or reconfiguring the system.
49
- - **Embed in your apps and services:** Python and TypeScript SDKs let you give your AI agents a virtual filesystem directly inside FastAPI, Express, browser apps, or any async runtime, no separate process required. Clone, snapshot, and version the workspace from inside your code.
50
- - **Works with major agent application frameworks:** OpenAI Agents SDK, Vercel AI SDK (TypeScript), LangChain, Pydantic AI, CAMEL, and OpenHands.
51
- - **Lightweight CLI + daemon:** plugs into coding agents like Claude Code and Codex so they reach every mounted resource through familiar bash, getting more useful work done per turn.
59
+ - **One interface instead of N SDKs and M MCPs.** Every service speaks the same filesystem semantics, and pipelines compose across services as naturally as on a local disk.
60
+ - **Around 50 built-in backends:** RAM, Disk, Redis, S3 / R2 / OCI / Supabase / GCS, Gmail / GDrive / GDocs / GSheets / GSlides, GitHub / Linear / Notion / Trello, Slack / Discord / Telegram / Email, MongoDB / Postgres / LanceDB, SSH, and more, mounted side-by-side under a single root.
61
+ - **Portable workspaces:** clone, snapshot, and version a workspace; agent runs move between machines without restarting or reconfiguring the system.
62
+ - **Embeddable:** the Python and TypeScript SDKs run in-process inside FastAPI, Express, browser apps, or any async runtime; no separate process required.
63
+ - **Agent integrations:** OpenAI Agents SDK, Vercel AI SDK, LangChain, Pydantic AI, CAMEL, and OpenHands via the SDKs; coding agents like Claude Code and Codex via the lightweight CLI + daemon.
52
64
 
53
65
  ## Architecture
54
66
 
55
67
  <p align="center">
56
68
  <picture>
57
69
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/strukto-ai/mirage/main/assets/mirage-arch-dark.svg">
58
- <img src="https://raw.githubusercontent.com/strukto-ai/mirage/main/assets/mirage-arch-light.svg" alt="Mirage architecture: AI Agent and Application → Mirage Bash and VFS → Dispatcher &amp; Cache → Infrastructure and Remote" width="900">
70
+ <img src="https://raw.githubusercontent.com/strukto-ai/mirage/main/assets/mirage-arch-light.svg" alt="Mirage architecture: AI Agent and Application → Mirage Bash and VFS → Dispatcher &amp; Cache → Infrastructure and Remote" width="720">
59
71
  </picture>
60
72
  </p>
61
73
 
62
74
  ## Installation
63
75
 
64
- ### Prerequisites
65
-
66
- - **Python** ≥ 3.12 for the `mirage-ai` package and the `mirage` CLI
76
+ - **Python** ≥ 3.11 for the `mirage-ai` package and the `mirage` CLI
67
77
  - **Node.js** ≥ 20 for the TypeScript SDK
68
78
  - **macOS** or **Linux** (FUSE-based mounts require platform support)
69
79
 
70
80
  ### Python
71
81
 
72
82
  ```bash
73
- uv add mirage-ai
83
+ uv add mirage-ai # installs the `mirage` library and the `mirage` CLI binary
74
84
  ```
75
85
 
76
- This installs both the `mirage` library and the `mirage` CLI binary.
77
-
78
86
  ### TypeScript
79
87
 
80
- Pick the package that matches your runtime:
81
-
82
88
  ```bash
83
89
  npm install @struktoai/mirage-node # Node.js servers and CLIs
84
90
  npm install @struktoai/mirage-browser # browser / edge runtimes
85
- npm install @struktoai/mirage-core # runtime-agnostic primitives
91
+ npm install @struktoai/mirage-agents # OpenAI / Vercel AI / LangChain / Mastra adapters
86
92
  ```
87
93
 
88
- `@struktoai/mirage-node` and `@struktoai/mirage-browser` both pull in `@struktoai/mirage-core` automatically.
94
+ Both runtime packages pull in `@struktoai/mirage-core` automatically.
89
95
 
90
96
  ### CLI
91
97
 
92
98
  ```bash
93
- curl -fsSL https://strukto.ai/install.sh | sh
94
- ```
95
-
96
- Or via your package manager of choice:
97
-
98
- ```bash
99
- brew install mirage
100
- ```
101
-
102
- ```bash
99
+ curl -fsSL https://strukto.ai/mirage/install.sh | sh
100
+ # or
101
+ npm install -g @struktoai/mirage-cli
102
+ # or
103
103
  uvx mirage-ai
104
- ```
105
-
106
- ```bash
104
+ # or
107
105
  npx @struktoai/mirage-cli
108
106
  ```
109
107
 
110
- ## Quickstart (Python)
108
+ ## Quickstart
109
+
110
+ ### Python
111
111
 
112
112
  ```python
113
113
  from mirage import Workspace
114
- from mirage.resource.gdocs import GDocsConfig, GDocsResource
115
114
  from mirage.resource.ram import RAMResource
116
115
  from mirage.resource.s3 import S3Config, S3Resource
117
- from mirage.resource.slack import SlackConfig, SlackResource
118
116
 
119
117
  ws = Workspace({
120
- "/data": RAMResource(),
121
- "/s3": S3Resource(S3Config(bucket="my-bucket")),
122
- "/slack": SlackResource(SlackConfig()),
123
- "/docs": GDocsResource(GDocsConfig()),
118
+ "/data": RAMResource(),
119
+ "/s3": S3Resource(S3Config(bucket="my-bucket")),
124
120
  })
125
121
 
126
122
  await ws.execute("cp /s3/report.csv /data/report.csv")
127
123
  await ws.execute("grep alert /s3/data/log.jsonl | wc -l")
128
124
 
129
- ws.snapshot("demo.tar")
125
+ await ws.snapshot("demo.tar")
130
126
  ```
131
127
 
132
- ## Quickstart (TypeScript)
128
+ ### TypeScript
133
129
 
134
130
  ```ts
135
- import {
136
- Workspace,
137
- RAMResource,
138
- S3Resource,
139
- SlackResource,
140
- GDocsResource,
141
- } from '@struktoai/mirage-browser'
131
+ import { Workspace, RAMResource, S3Resource } from '@struktoai/mirage-node'
142
132
 
143
133
  const ws = new Workspace({
144
134
  '/data': new RAMResource(),
145
135
  '/s3': new S3Resource({ bucket: 'my-bucket' }),
146
- '/slack': new SlackResource({}),
147
- '/docs': new GDocsResource({}),
148
136
  })
149
137
 
150
138
  await ws.execute('cp /s3/report.csv /data/report.csv')
151
139
  await ws.execute('grep alert /s3/data/log.jsonl | wc -l')
140
+
141
+ await ws.snapshot('demo.tar')
152
142
  ```
153
143
 
154
- ## Quickstart (CLI)
144
+ ### CLI
155
145
 
156
146
  ```bash
157
147
  mirage workspace create ws.yaml --id demo
@@ -163,89 +153,33 @@ mirage workspace load demo.tar --id demo-restored
163
153
 
164
154
  ## Agent Frameworks
165
155
 
166
- Mirage drops into the major agent application frameworks as a sandbox or tool layer. Your agent runs against the same mount tree it would in bash, so swapping the model or runtime never changes the surface.
167
-
168
- ### OpenAI Agents SDK (Python)
156
+ Mirage plugs into agent frameworks as a sandbox or tool layer. POSIX operations such as `read` can also be customized per resource and filetype, e.g. reading a PDF returns parsed pages instead of raw bytes.
169
157
 
170
- The `MirageSandboxClient` plugs a `Workspace` into the OpenAI Agents SDK as a sandbox: bash commands the agent runs execute against your mounts.
171
-
172
- ```python
173
- from agents import Runner
174
- from agents.run import RunConfig
175
- from agents.sandbox import SandboxAgent, SandboxRunConfig
176
-
177
- from mirage.agents.openai_agents import MirageSandboxClient
178
-
179
- client = MirageSandboxClient(ws)
180
- agent = SandboxAgent(
181
- name="Mirage Sandbox Agent",
182
- model="gpt-5.4-nano",
183
- instructions=ws.file_prompt,
184
- )
185
-
186
- result = await Runner.run(
187
- agent,
188
- "Summarize /s3/data/report.parquet into /report.txt.",
189
- run_config=RunConfig(sandbox=SandboxRunConfig(client=client)),
190
- )
191
- ```
192
-
193
- ### Vercel AI SDK (TypeScript)
194
-
195
- `mirageTools(ws)` exposes the workspace as a typed AI SDK tool set, so any model wired into the AI SDK can read and write across mounts, in Node or the browser.
196
-
197
- ```ts
198
- import { generateText } from 'ai'
199
- import { openai } from '@ai-sdk/openai'
200
- import { mirageTools } from '@struktoai/mirage-agents/vercel'
201
- import { buildSystemPrompt } from '@struktoai/mirage-agents/openai'
202
-
203
- const { text } = await generateText({
204
- model: openai('gpt-5.4-nano'),
205
- system: buildSystemPrompt({ mountInfo: { '/': 'In-memory filesystem' } }),
206
- prompt: "Use readFile to read /docs/paper.pdf, then describe what's in it.",
207
- tools: mirageTools(ws),
208
- })
209
- ```
210
-
211
- LangChain, Pydantic AI, CAMEL, OpenHands, and Mastra adapters live alongside these.
158
+ | | Integrations |
159
+ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
160
+ | Python | [OpenAI Agents SDK](https://docs.mirage.strukto.ai/python/agents/openai-agents), [LangChain](https://docs.mirage.strukto.ai/python/agents/langchain), [Pydantic AI](https://docs.mirage.strukto.ai/python/agents/pydantic-ai), [CAMEL](https://docs.mirage.strukto.ai/python/agents/camel), [OpenHands](https://docs.mirage.strukto.ai/python/agents/openhands), [Agno](https://docs.mirage.strukto.ai/python/agents/agno) |
161
+ | TypeScript | [Vercel AI SDK](https://docs.mirage.strukto.ai/typescript/agents/vercel), [OpenAI Agents SDK](https://docs.mirage.strukto.ai/typescript/agents/openai), [LangChain](https://docs.mirage.strukto.ai/typescript/agents/langchain), [Mastra](https://docs.mirage.strukto.ai/typescript/agents/mastra) |
162
+ | Coding agents | [Claude Code](https://docs.mirage.strukto.ai/python/agents/claude-code), [Codex](https://docs.mirage.strukto.ai/python/agents/codex), [OpenCode](https://docs.mirage.strukto.ai/typescript/agents/opencode), [Pi](https://docs.mirage.strukto.ai/typescript/agents/pi) |
212
163
 
213
164
  ## Cache
214
165
 
215
- Every `Workspace` ships with a **two-layer cache** so repeated work against remote backends (S3, GDrive, Slack, …) hits local state instead of the network:
166
+ Every `Workspace` has a two-layer cache so repeated work against remote backends hits local state instead of the network:
216
167
 
217
- - **Index cache.** Listings and metadata. The first directory walk hits the API; subsequent ones serve from the index until TTL expires.
218
- - **File cache.** Object bytes. The first read streams from origin; later pipelines read from cache.
219
- - **Pluggable backends.** Each layer is a store with two built-ins:
220
- - **RAM** (default): in-process, zero setup, 512 MB file cache and 10-minute index TTL. Best for single-process apps and notebooks.
221
- - **Redis**: shared across workers, processes, and machines. Best for serverless, multi-replica services, or when you want cache state to survive restarts.
168
+ - **Index cache:** listings and metadata. The first directory walk hits the API; later ones serve from the index until the TTL expires (default 10 minutes).
169
+ - **File cache:** object bytes. The first read streams from origin; later pipelines read from cache (default 512 MB).
170
+
171
+ Both layers default to in-process RAM with zero setup. A Redis store shares cache state across workers, processes, and machines:
222
172
 
223
173
  ```ts
224
- import { RedisFileCacheStore, RedisIndexCacheStore, Workspace } from 'mirage/node'
174
+ import { RedisFileCacheStore, S3Resource, Workspace } from '@struktoai/mirage-node'
225
175
 
226
176
  const ws = new Workspace(
227
177
  { '/s3': new S3Resource({ bucket: 'my-bucket' }) },
228
178
  {
229
- cache: new RedisFileCacheStore({ url: 'redis://localhost:6379/0', limit: '8GB' }),
230
- index: new RedisIndexCacheStore({ url: 'redis://localhost:6379/0', ttl: 600 }),
179
+ cache: new RedisFileCacheStore({ url: 'redis://localhost:6379/0', cacheLimit: '8GB' }),
180
+ index: { type: 'redis', url: 'redis://localhost:6379/0', ttl: 600 },
231
181
  },
232
182
  )
233
183
  ```
234
184
 
235
- ```ts
236
- import { S3Resource, Workspace } from 'mirage/node'
237
-
238
- const ws = new Workspace({ '/s3': new S3Resource({ bucket: 'my-bucket' }) })
239
-
240
- // 1. Index miss → S3 LIST. Listing stored in index cache.
241
- await ws.execute('ls /s3/data/')
242
-
243
- // 2. Index hit → 0 network calls.
244
- await ws.execute('find /s3/data/ -name "*.jsonl"')
245
-
246
- // 3. File miss → S3 GET. Bytes stored in file cache.
247
- await ws.execute('cat /s3/data/log.jsonl | wc -l')
248
-
249
- // 4. File hit → 0 network calls.
250
- await ws.execute('grep alert /s3/data/log.jsonl')
251
- ```
185
+ See the [cache docs](https://docs.mirage.strukto.ai/home/cache) for the full miss/hit lifecycle.
@@ -1,15 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  emit,
4
+ exitCodeFromResponse,
4
5
  fail,
5
6
  formatAge,
6
7
  formatTable,
7
8
  handleResponse,
8
9
  loadDaemonSettings,
9
10
  makeClient
10
- } from "../chunk-42V4PGGP.js";
11
+ } from "../chunk-IMRNFGEA.js";
11
12
 
12
13
  // src/main.ts
14
+ import { readFileSync as readFileSync4 } from "fs";
15
+ import { dirname, join as join2 } from "path";
16
+ import { fileURLToPath } from "url";
13
17
  import { Command } from "commander";
14
18
 
15
19
  // src/daemon.ts
@@ -167,15 +171,23 @@ function registerDaemonCommands(program) {
167
171
  }
168
172
 
169
173
  // src/execute.ts
174
+ import { readFileSync as readFileSync2 } from "fs";
170
175
  function registerExecuteCommand(program) {
171
176
  program.command("execute").description("Execute a command.").requiredOption("-w, --workspace <id>", "Workspace id").requiredOption("-c, --command <command>", "Shell command to execute").option("-s, --session <id>", "Session id").option("--bg", "Background; return job_id immediately").action(
172
177
  async (opts) => {
173
178
  const body = { command: opts.command, provision: false };
174
179
  if (opts.session !== void 0) body.sessionId = opts.session;
180
+ if (opts.bg !== true && !process.stdin.isTTY) {
181
+ body.stdinBase64 = readFileSync2(0).toString("base64");
182
+ }
175
183
  const path = `/v1/workspaces/${opts.workspace}/execute` + (opts.bg === true ? "?background=true" : "");
176
184
  const c = makeClient(loadDaemonSettings());
177
185
  await c.ensureRunning({ allowSpawn: false });
178
- emit(await handleResponse(await c.request("POST", path, { body: JSON.stringify(body) })));
186
+ const response = await handleResponse(
187
+ await c.request("POST", path, { body: JSON.stringify(body) })
188
+ );
189
+ emit(response);
190
+ process.exit(exitCodeFromResponse(response));
179
191
  }
180
192
  );
181
193
  }
@@ -195,18 +207,20 @@ function registerJobCommands(program) {
195
207
  job.command("get").argument("<id>").action(async (id) => {
196
208
  const c = buildClient2();
197
209
  await c.ensureRunning({ allowSpawn: false });
198
- emit(await handleResponse(await c.request("GET", `/v1/jobs/${id}`)));
210
+ const response = await handleResponse(await c.request("GET", `/v1/jobs/${id}`));
211
+ emit(response);
212
+ process.exit(exitCodeFromResponse(response));
199
213
  });
200
214
  job.command("wait").argument("<id>").option("--timeout <s>").action(async (id, opts) => {
201
215
  const c = buildClient2();
202
216
  await c.ensureRunning({ allowSpawn: false });
203
217
  const body = {};
204
218
  if (opts.timeout !== void 0) body.timeoutS = Number(opts.timeout);
205
- emit(
206
- await handleResponse(
207
- await c.request("POST", `/v1/jobs/${id}/wait`, { body: JSON.stringify(body) })
208
- )
219
+ const response = await handleResponse(
220
+ await c.request("POST", `/v1/jobs/${id}/wait`, { body: JSON.stringify(body) })
209
221
  );
222
+ emit(response);
223
+ process.exit(exitCodeFromResponse(response));
210
224
  });
211
225
  job.command("cancel").argument("<id>").action(async (id) => {
212
226
  const c = buildClient2();
@@ -238,11 +252,19 @@ function buildClient3() {
238
252
  }
239
253
  function registerSessionCommands(program) {
240
254
  const sess = program.command("session").description("Manage workspace sessions.");
241
- sess.command("create").argument("<wsId>").option("--id <sessionId>").action(async (wsId, opts) => {
255
+ sess.command("create").argument("<wsId>").option("--id <sessionId>").option(
256
+ "-m, --mount <prefix>",
257
+ "restrict session to this mount prefix; repeatable",
258
+ (value, prev) => prev.concat([value]),
259
+ []
260
+ ).action(async (wsId, opts) => {
242
261
  const c = buildClient3();
243
262
  await c.ensureRunning({ allowSpawn: false });
244
263
  const body = {};
245
264
  if (opts.id !== void 0) body.sessionId = opts.id;
265
+ if (opts.mount !== void 0 && opts.mount.length > 0) {
266
+ body.allowedMounts = opts.mount;
267
+ }
246
268
  emit(
247
269
  await handleResponse(
248
270
  await c.request("POST", `/v1/workspaces/${wsId}/sessions`, {
@@ -268,8 +290,8 @@ function registerSessionCommands(program) {
268
290
  }
269
291
 
270
292
  // src/workspace.ts
271
- import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
272
- import { basename } from "path";
293
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
294
+ import { resolve } from "path";
273
295
  import { interpolateEnv, loadWorkspaceConfig } from "@struktoai/mirage-server";
274
296
  import { parse as yamlParse } from "yaml";
275
297
  function buildClient4() {
@@ -282,6 +304,15 @@ function envRecord() {
282
304
  }
283
305
  return out;
284
306
  }
307
+ function loadConfigArgument(path) {
308
+ if (!existsSync2(path)) fail(`config file not found: ${path}`, 2);
309
+ const text = readFileSync3(path, "utf-8");
310
+ try {
311
+ return interpolateEnv(yamlParse(text), envRecord());
312
+ } catch (err) {
313
+ fail(`invalid config YAML/JSON at ${path}: ${String(err)}`, 2);
314
+ }
315
+ }
285
316
  function formatWorkspaceList(items) {
286
317
  if (items.length === 0) return "No active workspaces.";
287
318
  const rows = items.map((w) => [
@@ -321,6 +352,20 @@ function formatWorkspaceDetail(d) {
321
352
  }
322
353
  return lines.join("\n");
323
354
  }
355
+ function formatVersionLog(items) {
356
+ if (items.length === 0) return "No versions.";
357
+ return formatTable(
358
+ ["VERSION", "MESSAGE"],
359
+ items.map((v) => [v.id.slice(0, 12), v.message])
360
+ );
361
+ }
362
+ function formatDiff(changes) {
363
+ const lines = [];
364
+ for (const kind of ["added", "modified", "deleted"]) {
365
+ for (const path of changes[kind]) lines.push(`${kind.padEnd(9)} ${path}`);
366
+ }
367
+ return lines.length > 0 ? lines.join("\n") : "No changes.";
368
+ }
324
369
  function registerWorkspaceCommands(program) {
325
370
  const ws = program.command("workspace").description("Manage workspaces.");
326
371
  ws.command("create").description("Create a workspace; daemon auto-spawns if not running.").argument("<config>", "YAML/JSON workspace config").option("--id <id>", "Explicit workspace id").action(async (configPath, opts) => {
@@ -357,68 +402,101 @@ function registerWorkspaceCommands(program) {
357
402
  (d) => `Deleted workspace ${d.id}.`
358
403
  );
359
404
  });
360
- ws.command("clone").description("Clone a workspace; defaults to fresh local backings + shared remotes.").argument("<srcId>").option("--id <id>").option("--override <path>", "Partial config JSON/YAML for per-mount overrides").action(async (srcId, opts) => {
361
- const body = {};
405
+ ws.command("clone").description("Clone a workspace, optionally from one of its past versions.").argument("<srcId>").option("--id <id>", "Explicit id for the clone").option("--at <ref>", "Clone from a past version (id or branch) not the live state").action(async (srcId, opts) => {
406
+ const body = { sourceId: srcId };
362
407
  if (opts.id !== void 0) body.id = opts.id;
363
- if (opts.override !== void 0) {
364
- const text = readFileSync2(opts.override, "utf-8");
365
- let parsed;
366
- try {
367
- parsed = yamlParse(text);
368
- } catch (err) {
369
- fail(`invalid override YAML/JSON at ${opts.override}: ${String(err)}`, 2);
370
- }
371
- body.override = interpolateEnv(parsed, envRecord());
372
- }
408
+ if (opts.at !== void 0) body.at = opts.at;
373
409
  const c = buildClient4();
374
410
  await c.ensureRunning({ allowSpawn: false });
375
- const r = await c.request("POST", `/v1/workspaces/${srcId}/clone`, {
376
- body: JSON.stringify(body)
377
- });
411
+ const r = await c.request("POST", "/v1/workspaces/clone", { body: JSON.stringify(body) });
378
412
  emit(await handleResponse(r), formatWorkspaceDetail);
379
413
  });
380
- ws.command("snapshot").description("Snapshot a workspace to a tar file.").argument("<id>").argument("<output>", "Path to write the .tar to").action(async (id, output) => {
414
+ ws.command("commit").description("Commit the workspace's current state as a version.").argument("<id>").option("-m, --message <msg>", "Version message", "").option("-b, --branch <branch>", "Branch to commit on", "main").action(async (id, opts) => {
381
415
  const c = buildClient4();
382
416
  await c.ensureRunning({ allowSpawn: false });
383
- const r = await c.request("GET", `/v1/workspaces/${id}/snapshot`);
384
- if (r.status >= 400) {
385
- fail(`daemon error ${String(r.status)}: ${await r.text()}`, 2);
386
- }
387
- const buf = Buffer.from(await r.arrayBuffer());
388
- writeFileSync(output, buf);
417
+ const r = await c.request("POST", `/v1/workspaces/${id}/commit`, {
418
+ body: JSON.stringify({ message: opts.message, branch: opts.branch })
419
+ });
389
420
  emit(
390
- { workspaceId: id, path: output, bytes: buf.length },
391
- (d) => `Snapshot ${d.workspaceId} -> ${d.path} (${d.bytes.toLocaleString()} bytes).`
421
+ await handleResponse(r),
422
+ (d) => `Committed ${d.version.slice(0, 12)} on ${d.branch}.`
392
423
  );
393
424
  });
394
- ws.command("load").description("Load a workspace from a tar file.").argument("<tar>", "Path to a .tar produced by `mirage workspace snapshot`").option("--id <id>", "Explicit workspace id").option("--override <path>", "Partial config YAML/JSON for per-mount overrides").action(async (tarPath, opts) => {
395
- if (!existsSync2(tarPath)) fail(`tar file not found: ${tarPath}`, 2);
396
- const tarBuf = readFileSync2(tarPath);
397
- const form = new FormData();
398
- form.append("tar", new Blob([tarBuf], { type: "application/x-tar" }), basename(tarPath));
399
- if (opts.id !== void 0) form.append("id", opts.id);
400
- if (opts.override !== void 0) {
401
- const overrideText = readFileSync2(opts.override, "utf-8");
402
- let parsed;
403
- try {
404
- parsed = yamlParse(overrideText);
405
- } catch (err) {
406
- fail(`invalid override YAML/JSON at ${opts.override}: ${String(err)}`, 2);
407
- }
408
- form.append("override", JSON.stringify(interpolateEnv(parsed, envRecord())));
425
+ ws.command("branch").description("Create a branch at another branch's current version.").argument("<id>").argument("<name>").option("--from <branch>", "Branch to fork from", "main").action(async (id, name, opts) => {
426
+ const c = buildClient4();
427
+ await c.ensureRunning({ allowSpawn: false });
428
+ const r = await c.request("POST", `/v1/workspaces/${id}/branch`, {
429
+ body: JSON.stringify({ name, fromBranch: opts.from })
430
+ });
431
+ emit(
432
+ await handleResponse(r),
433
+ (d) => `Created branch ${d.branch} at ${d.version.slice(0, 12)}.`
434
+ );
435
+ });
436
+ ws.command("log").description("List a workspace's versions (newest first).").argument("<id>").option("-b, --branch <branch>", "Branch", "main").action(async (id, opts) => {
437
+ const c = buildClient4();
438
+ await c.ensureRunning({ allowSpawn: false });
439
+ const r = await c.request("GET", `/v1/workspaces/${id}/versions?branch=${opts.branch}`);
440
+ emit(await handleResponse(r), formatVersionLog);
441
+ });
442
+ ws.command("diff").description("Show changed files (git-style): live vs HEAD, live vs <a>, or <a> vs <b>.").argument("<id>").argument("[a]", "Base ref; omit to use live state").argument("[b]", "Compare ref; omit to use live state").option("-b, --branch <branch>", "Branch", "main").action(
443
+ async (id, a, b, opts) => {
444
+ const params = new URLSearchParams({ branch: opts.branch });
445
+ if (a !== void 0) params.set("a", a);
446
+ if (b !== void 0) params.set("b", b);
447
+ const c = buildClient4();
448
+ await c.ensureRunning({ allowSpawn: false });
449
+ const r = await c.request("GET", `/v1/workspaces/${id}/diff?${params.toString()}`);
450
+ emit(await handleResponse(r), formatDiff);
409
451
  }
452
+ );
453
+ ws.command("checkout").description("Restore a workspace in place to one of its versions.").argument("<id>").argument("<ref>", "Version id or branch to restore").action(async (id, ref) => {
454
+ const c = buildClient4();
455
+ await c.ensureRunning({ allowSpawn: false });
456
+ const r = await c.request("POST", `/v1/workspaces/${id}/checkout`, {
457
+ body: JSON.stringify({ ref })
458
+ });
459
+ emit(await handleResponse(r), formatWorkspaceDetail);
460
+ });
461
+ ws.command("snapshot").description(
462
+ "Snapshot a workspace to a tar file. The path is resolved to an absolute path and the daemon writes the tar."
463
+ ).argument("<id>").argument("<output>", "Path to write the .tar to").action(async (id, output) => {
464
+ const c = buildClient4();
465
+ await c.ensureRunning({ allowSpawn: false });
466
+ const r = await c.request("POST", `/v1/workspaces/${id}/snapshot`, {
467
+ body: JSON.stringify({ path: resolve(output) })
468
+ });
469
+ const d = await handleResponse(r);
470
+ emit(d, (x) => `Snapshot ${x.id} -> ${x.path} (${x.size.toLocaleString()} bytes).`);
471
+ });
472
+ ws.command("load").description("Load a workspace from a tar file.").argument("<tar>", "Path to a .tar produced by `mirage workspace snapshot`").argument("[config]", "Workspace YAML/JSON config").option("--id <id>", "Explicit workspace id").action(async (tarPath, configPath, opts) => {
473
+ if (!existsSync2(tarPath)) fail(`tar file not found: ${tarPath}`, 2);
474
+ const body = { path: resolve(tarPath) };
475
+ if (opts.id !== void 0) body.id = opts.id;
476
+ if (configPath !== void 0) body.override = loadConfigArgument(configPath);
410
477
  const c = buildClient4();
411
478
  await c.ensureRunning({ allowSpawn: true });
412
- const r = await c.requestMultipart("POST", "/v1/workspaces/load", form);
413
- if (r.status >= 400) fail(`load failed: ${await r.text()}`, 2);
479
+ const r = await c.request("POST", "/v1/workspaces/load", { body: JSON.stringify(body) });
414
480
  emit(await handleResponse(r), formatWorkspaceDetail);
415
481
  });
416
482
  }
417
483
 
418
484
  // src/main.ts
485
+ function resolveVersion() {
486
+ let dir = dirname(fileURLToPath(import.meta.url));
487
+ for (let i = 0; i < 6; i++) {
488
+ try {
489
+ const pkg = JSON.parse(readFileSync4(join2(dir, "package.json"), "utf8"));
490
+ if (pkg.name === "@struktoai/mirage-cli" && pkg.version) return pkg.version;
491
+ } catch {
492
+ }
493
+ dir = dirname(dir);
494
+ }
495
+ return "0.0.0";
496
+ }
419
497
  function buildProgram() {
420
498
  const program = new Command();
421
- program.name("mirage").description("Mirage daemon CLI: manage workspaces and execute commands.").version("0.0.0");
499
+ program.name("mirage").description("Mirage daemon CLI: manage workspaces and execute commands.").version(resolveVersion());
422
500
  registerWorkspaceCommands(program);
423
501
  registerSessionCommands(program);
424
502
  registerJobCommands(program);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/main.ts","../../src/daemon.ts","../../src/execute.ts","../../src/job.ts","../../src/provision.ts","../../src/session.ts","../../src/workspace.ts","../../src/bin/mirage.ts"],"sourcesContent":["// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { Command } from 'commander'\nimport { registerDaemonCommands } from './daemon.ts'\nimport { registerExecuteCommand } from './execute.ts'\nimport { registerJobCommands } from './job.ts'\nimport { registerProvisionCommand } from './provision.ts'\nimport { registerSessionCommands } from './session.ts'\nimport { registerWorkspaceCommands } from './workspace.ts'\n\nexport function buildProgram(): Command {\n const program = new Command()\n program\n .name('mirage')\n .description('Mirage daemon CLI: manage workspaces and execute commands.')\n .version('0.0.0')\n registerWorkspaceCommands(program)\n registerSessionCommands(program)\n registerJobCommands(program)\n registerExecuteCommand(program)\n registerProvisionCommand(program)\n registerDaemonCommands(program)\n return program\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, fail, formatAge } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\ninterface DaemonStatus {\n running: boolean\n pid: number | null\n url: string\n uptimeS?: number\n workspaces?: number\n}\n\nfunction formatStatus(d: DaemonStatus): string {\n if (!d.running) return `Daemon not running. URL: ${d.url}`\n const parts: string[] = [`Running. PID ${d.pid !== null ? String(d.pid) : '?'}`]\n if (d.uptimeS !== undefined) {\n parts.push(`uptime ${formatAge(Date.now() / 1000 - d.uptimeS)}`)\n }\n if (d.workspaces !== undefined) {\n parts.push(`${String(d.workspaces)} workspace${d.workspaces === 1 ? '' : 's'}`)\n }\n return parts.join(', ') + `. URL: ${d.url}`\n}\n\nfunction formatStop(d: { via?: string; pid?: number }): string {\n const via = d.via ?? '?'\n return `Stopped (via ${via}${d.pid !== undefined ? `, PID ${String(d.pid)}` : ''}).`\n}\n\nfunction formatRestart(d: { spawnedFresh?: boolean }): string {\n if (d.spawnedFresh === true) return 'Restarted (eager spawn).'\n return 'Restarted; next CLI command will auto-spawn.'\n}\n\nfunction formatKill(d: { killed: boolean; pid?: number | null }): string {\n if (d.killed) return `Killed PID ${String(d.pid ?? '?')}.`\n if (d.pid === null || d.pid === undefined) return 'Daemon not running.'\n return `Already gone (PID ${String(d.pid)}).`\n}\n\nfunction pidFilePath(): string {\n return join(homedir(), '.mirage', 'daemon.pid')\n}\n\nfunction readPid(): number | null {\n const p = pidFilePath()\n if (!existsSync(p)) return null\n const text = readFileSync(p, 'utf-8').trim()\n const pid = Number(text)\n return Number.isFinite(pid) && pid > 0 ? pid : null\n}\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (err: unknown) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ESRCH') return false\n if (code === 'EPERM') return true\n return false\n }\n}\n\nfunction buildClient() {\n return makeClient(loadDaemonSettings())\n}\n\nasync function waitForUnreachable(timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n while (Date.now() < deadline) {\n const c = buildClient()\n if (!(await c.isReachable(300))) return true\n await new Promise((r) => setTimeout(r, 200))\n }\n return false\n}\n\nexport function registerDaemonCommands(program: Command): void {\n const d = program.command('daemon').description('Manage the daemon process lifecycle.')\n\n d.command('status')\n .description('Show daemon health, PID, uptime, workspace count.')\n .action(async () => {\n const pid = readPid()\n const c = buildClient()\n const url = c.settings.url\n try {\n const r = await c.request('GET', '/v1/health')\n if (r.status !== 200) {\n emit({ running: false, pid, url } as DaemonStatus, formatStatus)\n process.exit(1)\n }\n const body = (await r.json()) as Record<string, unknown>\n emit({ running: true, pid, url, ...body } as DaemonStatus, formatStatus)\n } catch {\n emit({ running: false, pid, url } as DaemonStatus, formatStatus)\n process.exit(1)\n }\n })\n\n d.command('stop')\n .description('Gracefully stop the daemon.')\n .option('--timeout <s>', 'Seconds to wait for graceful exit', '5')\n .action(async (opts: { timeout: string }) => {\n const timeoutMs = Number(opts.timeout) * 1000\n const c = buildClient()\n let r: Response\n try {\n r = await c.request('POST', '/v1/shutdown')\n } catch (err: unknown) {\n fail(`daemon not reachable: ${String(err)}`)\n }\n if (r.status >= 400) fail(`shutdown failed: ${await r.text()}`, 2)\n if (await waitForUnreachable(timeoutMs)) {\n emit({ stopped: true, via: 'graceful' }, formatStop)\n return\n }\n const pid = readPid()\n if (pid !== null && processAlive(pid)) {\n try {\n process.kill(pid, 'SIGTERM')\n emit({ stopped: true, via: 'sigterm', pid }, formatStop)\n return\n } catch {\n // fall through to fail\n }\n }\n fail(`daemon did not exit within ${opts.timeout}s and no live PID found`, 2)\n })\n\n d.command('restart')\n .description('Stop the daemon. Next CLI command auto-spawns a fresh one.')\n .option('--timeout <s>', 'Seconds to wait for graceful exit', '5')\n .option('--eager', 'Spawn a fresh daemon immediately')\n .action(async (opts: { timeout: string; eager?: boolean }) => {\n const timeoutMs = Number(opts.timeout) * 1000\n try {\n await buildClient().request('POST', '/v1/shutdown')\n } catch {\n // already unreachable; fall through to pid cleanup\n }\n if (!(await waitForUnreachable(timeoutMs))) {\n const pid = readPid()\n if (pid !== null && processAlive(pid)) {\n try {\n process.kill(pid, 'SIGTERM')\n } catch {\n // process may have exited between checks\n }\n }\n }\n if (opts.eager === true) {\n await buildClient().ensureRunning({ allowSpawn: true })\n emit({ restarted: true, spawnedFresh: true }, formatRestart)\n return\n }\n emit(\n {\n restarted: true,\n spawnedFresh: false,\n note: 'next workspace create will auto-spawn',\n },\n formatRestart,\n )\n })\n\n d.command('kill')\n .description('SIGKILL the daemon. Last resort -- skips graceful shutdown.')\n .action(() => {\n const pid = readPid()\n if (pid === null) {\n emit({ killed: false, reason: 'no daemon running', pid: null }, formatKill)\n return\n }\n if (!processAlive(pid)) {\n emit({ killed: false, reason: 'process already gone', pid }, formatKill)\n return\n }\n try {\n process.kill(pid, 'SIGKILL')\n } catch {\n emit({ killed: false, reason: 'process gone', pid }, formatKill)\n return\n }\n emit({ killed: true, pid }, formatKill)\n })\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nexport function registerExecuteCommand(program: Command): void {\n program\n .command('execute')\n .description('Execute a command.')\n .requiredOption('-w, --workspace <id>', 'Workspace id')\n .requiredOption('-c, --command <command>', 'Shell command to execute')\n .option('-s, --session <id>', 'Session id')\n .option('--bg', 'Background; return job_id immediately')\n .action(\n async (opts: { workspace: string; command: string; session?: string; bg?: boolean }) => {\n const body: Record<string, unknown> = { command: opts.command, provision: false }\n if (opts.session !== undefined) body.sessionId = opts.session\n const path =\n `/v1/workspaces/${opts.workspace}/execute` + (opts.bg === true ? '?background=true' : '')\n const c = makeClient(loadDaemonSettings())\n await c.ensureRunning({ allowSpawn: false })\n emit(await handleResponse(await c.request('POST', path, { body: JSON.stringify(body) })))\n },\n )\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nfunction buildClient() {\n return makeClient(loadDaemonSettings())\n}\n\nexport function registerJobCommands(program: Command): void {\n const job = program.command('job').description('Manage daemon jobs.')\n\n job\n .command('list')\n .option('-w, --workspace <id>')\n .action(async (opts: { workspace?: string }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const path =\n '/v1/jobs' + (opts.workspace !== undefined ? `?workspaceId=${opts.workspace}` : '')\n emit(await handleResponse(await c.request('GET', path)))\n })\n\n job\n .command('get')\n .argument('<id>')\n .action(async (id: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(await handleResponse(await c.request('GET', `/v1/jobs/${id}`)))\n })\n\n job\n .command('wait')\n .argument('<id>')\n .option('--timeout <s>')\n .action(async (id: string, opts: { timeout?: string }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const body: Record<string, unknown> = {}\n if (opts.timeout !== undefined) body.timeoutS = Number(opts.timeout)\n emit(\n await handleResponse(\n await c.request('POST', `/v1/jobs/${id}/wait`, { body: JSON.stringify(body) }),\n ),\n )\n })\n\n job\n .command('cancel')\n .argument('<id>')\n .action(async (id: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(await handleResponse(await c.request('DELETE', `/v1/jobs/${id}`)))\n })\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nexport function registerProvisionCommand(program: Command): void {\n program\n .command('provision')\n .description('Estimate cost / preview a command without running it.')\n .requiredOption('-w, --workspace <id>', 'Workspace id')\n .requiredOption('-c, --command <command>', 'Shell command to estimate')\n .option('-s, --session <id>', 'Session id')\n .action(async (opts: { workspace: string; command: string; session?: string }) => {\n const body: Record<string, unknown> = { command: opts.command, provision: true }\n if (opts.session !== undefined) body.sessionId = opts.session\n const c = makeClient(loadDaemonSettings())\n await c.ensureRunning({ allowSpawn: false })\n emit(\n await handleResponse(\n await c.request('POST', `/v1/workspaces/${opts.workspace}/execute`, {\n body: JSON.stringify(body),\n }),\n ),\n )\n })\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nfunction buildClient() {\n return makeClient(loadDaemonSettings())\n}\n\nexport function registerSessionCommands(program: Command): void {\n const sess = program.command('session').description('Manage workspace sessions.')\n\n sess\n .command('create')\n .argument('<wsId>')\n .option('--id <sessionId>')\n .action(async (wsId: string, opts: { id?: string }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const body: Record<string, unknown> = {}\n if (opts.id !== undefined) body.sessionId = opts.id\n emit(\n await handleResponse(\n await c.request('POST', `/v1/workspaces/${wsId}/sessions`, {\n body: JSON.stringify(body),\n }),\n ),\n )\n })\n\n sess\n .command('list')\n .argument('<wsId>')\n .action(async (wsId: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(await handleResponse(await c.request('GET', `/v1/workspaces/${wsId}/sessions`)))\n })\n\n sess\n .command('delete')\n .argument('<wsId>')\n .argument('<sessionId>')\n .action(async (wsId: string, sessionId: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(\n await handleResponse(\n await c.request('DELETE', `/v1/workspaces/${wsId}/sessions/${sessionId}`),\n ),\n )\n })\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport type { Command } from 'commander'\nimport { interpolateEnv, loadWorkspaceConfig } from '@struktoai/mirage-server'\nimport { parse as yamlParse } from 'yaml'\nimport { makeClient } from './client.ts'\nimport { emit, fail, formatAge, formatTable, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nfunction buildClient() {\n return makeClient(loadDaemonSettings())\n}\n\nfunction envRecord(): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(process.env)) {\n if (typeof v === 'string') out[k] = v\n }\n return out\n}\n\ninterface WorkspaceBrief {\n id: string\n mode: string\n mountCount: number\n sessionCount: number\n createdAt: number\n}\n\ninterface MountSummary {\n prefix: string\n resource: string\n mode: string\n}\n\ninterface SessionSummary {\n sessionId: string\n cwd: string\n}\n\ninterface Internals {\n cacheBytes: number\n cacheEntries: number\n historyLength: number\n inFlightJobs: number\n}\n\ninterface WorkspaceDetail {\n id: string\n mode: string\n createdAt: number\n mounts?: MountSummary[]\n sessions?: SessionSummary[]\n internals?: Internals | null\n}\n\nfunction formatWorkspaceList(items: WorkspaceBrief[]): string {\n if (items.length === 0) return 'No active workspaces.'\n const rows = items.map((w) => [\n w.id,\n w.mode,\n String(w.mountCount),\n String(w.sessionCount),\n formatAge(w.createdAt),\n ])\n return formatTable(['ID', 'MODE', 'MOUNTS', 'SESSIONS', 'AGE'], rows)\n}\n\nfunction formatWorkspaceDetail(d: WorkspaceDetail): string {\n const lines: string[] = [\n `ID: ${d.id}`,\n `Mode: ${d.mode}`,\n `Created: ${formatAge(d.createdAt)} ago`,\n ]\n if (d.mounts !== undefined && d.mounts.length > 0) {\n const rows = d.mounts.map((m) => [m.prefix, m.resource, m.mode])\n lines.push('', 'Mounts:')\n for (const ln of formatTable(['PREFIX', 'RESOURCE', 'MODE'], rows).split('\\n')) {\n lines.push(' ' + ln)\n }\n }\n if (d.sessions !== undefined && d.sessions.length > 0) {\n const rows = d.sessions.map((s) => [s.sessionId, s.cwd])\n lines.push('', 'Sessions:')\n for (const ln of formatTable(['SESSION', 'CWD'], rows).split('\\n')) {\n lines.push(' ' + ln)\n }\n }\n if (d.internals != null) {\n lines.push('', 'Internals:')\n for (const k of ['cacheBytes', 'cacheEntries', 'historyLength', 'inFlightJobs'] as const) {\n lines.push(` ${k.padEnd(16)} ${String(d.internals[k])}`)\n }\n }\n return lines.join('\\n')\n}\n\nexport function registerWorkspaceCommands(program: Command): void {\n const ws = program.command('workspace').description('Manage workspaces.')\n\n ws.command('create')\n .description('Create a workspace; daemon auto-spawns if not running.')\n .argument('<config>', 'YAML/JSON workspace config')\n .option('--id <id>', 'Explicit workspace id')\n .action(async (configPath: string, opts: { id?: string }) => {\n const cfg = loadWorkspaceConfig(configPath)\n const body: { config: unknown; id?: string } = { config: cfg }\n if (opts.id !== undefined) body.id = opts.id\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: true })\n const r = await c.request('POST', '/v1/workspaces', { body: JSON.stringify(body) })\n emit((await handleResponse(r)) as WorkspaceDetail, formatWorkspaceDetail)\n })\n\n ws.command('list')\n .description('List active workspaces.')\n .action(async () => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(\n (await handleResponse(await c.request('GET', '/v1/workspaces'))) as WorkspaceBrief[],\n formatWorkspaceList,\n )\n })\n\n ws.command('get')\n .description('Show full details for one workspace.')\n .argument('<id>')\n .option('--verbose', 'Include cache/dirty/history internals')\n .action(async (id: string, opts: { verbose?: boolean }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const path = `/v1/workspaces/${id}` + (opts.verbose === true ? '?verbose=true' : '')\n emit(\n (await handleResponse(await c.request('GET', path))) as WorkspaceDetail,\n formatWorkspaceDetail,\n )\n })\n\n ws.command('delete')\n .description('Stop and remove a workspace.')\n .argument('<id>')\n .action(async (id: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(\n (await handleResponse(await c.request('DELETE', `/v1/workspaces/${id}`))) as {\n id: string\n },\n (d) => `Deleted workspace ${d.id}.`,\n )\n })\n\n ws.command('clone')\n .description('Clone a workspace; defaults to fresh local backings + shared remotes.')\n .argument('<srcId>')\n .option('--id <id>')\n .option('--override <path>', 'Partial config JSON/YAML for per-mount overrides')\n .action(async (srcId: string, opts: { id?: string; override?: string }) => {\n const body: Record<string, unknown> = {}\n if (opts.id !== undefined) body.id = opts.id\n if (opts.override !== undefined) {\n const text = readFileSync(opts.override, 'utf-8')\n let parsed: unknown\n try {\n parsed = yamlParse(text)\n } catch (err: unknown) {\n fail(`invalid override YAML/JSON at ${opts.override}: ${String(err)}`, 2)\n }\n body.override = interpolateEnv(parsed, envRecord())\n }\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('POST', `/v1/workspaces/${srcId}/clone`, {\n body: JSON.stringify(body),\n })\n emit((await handleResponse(r)) as WorkspaceDetail, formatWorkspaceDetail)\n })\n\n ws.command('snapshot')\n .description('Snapshot a workspace to a tar file.')\n .argument('<id>')\n .argument('<output>', 'Path to write the .tar to')\n .action(async (id: string, output: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('GET', `/v1/workspaces/${id}/snapshot`)\n if (r.status >= 400) {\n fail(`daemon error ${String(r.status)}: ${await r.text()}`, 2)\n }\n const buf = Buffer.from(await r.arrayBuffer())\n writeFileSync(output, buf)\n emit(\n { workspaceId: id, path: output, bytes: buf.length },\n (d) => `Snapshot ${d.workspaceId} -> ${d.path} (${d.bytes.toLocaleString()} bytes).`,\n )\n })\n\n ws.command('load')\n .description('Load a workspace from a tar file.')\n .argument('<tar>', 'Path to a .tar produced by `mirage workspace snapshot`')\n .option('--id <id>', 'Explicit workspace id')\n .option('--override <path>', 'Partial config YAML/JSON for per-mount overrides')\n .action(async (tarPath: string, opts: { id?: string; override?: string }) => {\n if (!existsSync(tarPath)) fail(`tar file not found: ${tarPath}`, 2)\n const tarBuf = readFileSync(tarPath)\n const form = new FormData()\n form.append('tar', new Blob([tarBuf], { type: 'application/x-tar' }), basename(tarPath))\n if (opts.id !== undefined) form.append('id', opts.id)\n if (opts.override !== undefined) {\n const overrideText = readFileSync(opts.override, 'utf-8')\n let parsed: unknown\n try {\n parsed = yamlParse(overrideText)\n } catch (err: unknown) {\n fail(`invalid override YAML/JSON at ${opts.override}: ${String(err)}`, 2)\n }\n form.append('override', JSON.stringify(interpolateEnv(parsed, envRecord())))\n }\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: true })\n const r = await c.requestMultipart('POST', '/v1/workspaces/load', form)\n if (r.status >= 400) fail(`load failed: ${await r.text()}`, 2)\n emit((await handleResponse(r)) as WorkspaceDetail, formatWorkspaceDetail)\n })\n}\n","#!/usr/bin/env node\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { buildProgram } from '../main.ts'\n\nconst ALIASES: Record<string, string> = {\n '--workspace_id': '--workspace',\n '--session_id': '--session',\n}\n\nfunction rewriteArgv(argv: string[]): string[] {\n return argv.map((arg) => {\n for (const [from, to] of Object.entries(ALIASES)) {\n if (arg === from) return to\n if (arg.startsWith(from + '=')) return to + arg.slice(from.length)\n }\n return arg\n })\n}\n\nbuildProgram()\n .parseAsync(rewriteArgv(process.argv))\n .catch((err: unknown) => {\n console.error(err)\n process.exit(1)\n })\n"],"mappings":";;;;;;;;;;;;AAcA,SAAS,eAAe;;;ACAxB,SAAS,YAAY,oBAAoB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A,WAAK,OAAO,YAAY,KAAK,UAAU,eAAe,QAAQ,UAAU,CAAC,CAAC,CAAC;AAAA,IAC7E;AACA,UAAM,IAAID,aAAY;AACtB,UAAM,EAAE,cAAc,EAAE,YAAY,KAAK,CAAC;AAC1C,UAAM,IAAI,MAAM,EAAE,iBAAiB,QAAQ,uBAAuB,IAAI;AACtE,QAAI,EAAE,UAAU,IAAK,MAAK,gBAAgB,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC;AAC7D,SAAM,MAAM,eAAe,CAAC,GAAuB,qBAAqB;AAAA,EAC1E,CAAC;AACL;;;ANzNO,SAAS,eAAwB;AACtC,QAAM,UAAU,IAAI,QAAQ;AAC5B,UACG,KAAK,QAAQ,EACb,YAAY,4DAA4D,EACxE,QAAQ,OAAO;AAClB,4BAA0B,OAAO;AACjC,0BAAwB,OAAO;AAC/B,sBAAoB,OAAO;AAC3B,yBAAuB,OAAO;AAC9B,2BAAyB,OAAO;AAChC,yBAAuB,OAAO;AAC9B,SAAO;AACT;;;AOlBA,IAAM,UAAkC;AAAA,EACtC,kBAAkB;AAAA,EAClB,gBAAgB;AAClB;AAEA,SAAS,YAAY,MAA0B;AAC7C,SAAO,KAAK,IAAI,CAAC,QAAQ;AACvB,eAAW,CAAC,MAAM,EAAE,KAAK,OAAO,QAAQ,OAAO,GAAG;AAChD,UAAI,QAAQ,KAAM,QAAO;AACzB,UAAI,IAAI,WAAW,OAAO,GAAG,EAAG,QAAO,KAAK,IAAI,MAAM,KAAK,MAAM;AAAA,IACnE;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAEA,aAAa,EACV,WAAW,YAAY,QAAQ,IAAI,CAAC,EACpC,MAAM,CAAC,QAAiB;AACvB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["buildClient","buildClient","existsSync","readFileSync","buildClient","readFileSync","existsSync"]}
1
+ {"version":3,"sources":["../../src/main.ts","../../src/daemon.ts","../../src/execute.ts","../../src/job.ts","../../src/provision.ts","../../src/session.ts","../../src/workspace.ts","../../src/bin/mirage.ts"],"sourcesContent":["// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { readFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { Command } from 'commander'\nimport { registerDaemonCommands } from './daemon.ts'\nimport { registerExecuteCommand } from './execute.ts'\nimport { registerJobCommands } from './job.ts'\nimport { registerProvisionCommand } from './provision.ts'\nimport { registerSessionCommands } from './session.ts'\nimport { registerWorkspaceCommands } from './workspace.ts'\n\nfunction resolveVersion(): string {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (let i = 0; i < 6; i++) {\n try {\n const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as {\n name?: string\n version?: string\n }\n if (pkg.name === '@struktoai/mirage-cli' && pkg.version) return pkg.version\n } catch {\n // package.json absent at this level: keep walking up to the package root\n }\n dir = dirname(dir)\n }\n return '0.0.0'\n}\n\nexport function buildProgram(): Command {\n const program = new Command()\n program\n .name('mirage')\n .description('Mirage daemon CLI: manage workspaces and execute commands.')\n .version(resolveVersion())\n registerWorkspaceCommands(program)\n registerSessionCommands(program)\n registerJobCommands(program)\n registerExecuteCommand(program)\n registerProvisionCommand(program)\n registerDaemonCommands(program)\n return program\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, fail, formatAge } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\ninterface DaemonStatus {\n running: boolean\n pid: number | null\n url: string\n uptimeS?: number\n workspaces?: number\n}\n\nfunction formatStatus(d: DaemonStatus): string {\n if (!d.running) return `Daemon not running. URL: ${d.url}`\n const parts: string[] = [`Running. PID ${d.pid !== null ? String(d.pid) : '?'}`]\n if (d.uptimeS !== undefined) {\n parts.push(`uptime ${formatAge(Date.now() / 1000 - d.uptimeS)}`)\n }\n if (d.workspaces !== undefined) {\n parts.push(`${String(d.workspaces)} workspace${d.workspaces === 1 ? '' : 's'}`)\n }\n return parts.join(', ') + `. URL: ${d.url}`\n}\n\nfunction formatStop(d: { via?: string; pid?: number }): string {\n const via = d.via ?? '?'\n return `Stopped (via ${via}${d.pid !== undefined ? `, PID ${String(d.pid)}` : ''}).`\n}\n\nfunction formatRestart(d: { spawnedFresh?: boolean }): string {\n if (d.spawnedFresh === true) return 'Restarted (eager spawn).'\n return 'Restarted; next CLI command will auto-spawn.'\n}\n\nfunction formatKill(d: { killed: boolean; pid?: number | null }): string {\n if (d.killed) return `Killed PID ${String(d.pid ?? '?')}.`\n if (d.pid === null || d.pid === undefined) return 'Daemon not running.'\n return `Already gone (PID ${String(d.pid)}).`\n}\n\nfunction pidFilePath(): string {\n return join(homedir(), '.mirage', 'daemon.pid')\n}\n\nfunction readPid(): number | null {\n const p = pidFilePath()\n if (!existsSync(p)) return null\n const text = readFileSync(p, 'utf-8').trim()\n const pid = Number(text)\n return Number.isFinite(pid) && pid > 0 ? pid : null\n}\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (err: unknown) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ESRCH') return false\n if (code === 'EPERM') return true\n return false\n }\n}\n\nfunction buildClient() {\n return makeClient(loadDaemonSettings())\n}\n\nasync function waitForUnreachable(timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n while (Date.now() < deadline) {\n const c = buildClient()\n if (!(await c.isReachable(300))) return true\n await new Promise((r) => setTimeout(r, 200))\n }\n return false\n}\n\nexport function registerDaemonCommands(program: Command): void {\n const d = program.command('daemon').description('Manage the daemon process lifecycle.')\n\n d.command('status')\n .description('Show daemon health, PID, uptime, workspace count.')\n .action(async () => {\n const pid = readPid()\n const c = buildClient()\n const url = c.settings.url\n try {\n const r = await c.request('GET', '/v1/health')\n if (r.status !== 200) {\n emit({ running: false, pid, url } as DaemonStatus, formatStatus)\n process.exit(1)\n }\n const body = (await r.json()) as Record<string, unknown>\n emit({ running: true, pid, url, ...body } as DaemonStatus, formatStatus)\n } catch {\n emit({ running: false, pid, url } as DaemonStatus, formatStatus)\n process.exit(1)\n }\n })\n\n d.command('stop')\n .description('Gracefully stop the daemon.')\n .option('--timeout <s>', 'Seconds to wait for graceful exit', '5')\n .action(async (opts: { timeout: string }) => {\n const timeoutMs = Number(opts.timeout) * 1000\n const c = buildClient()\n let r: Response\n try {\n r = await c.request('POST', '/v1/shutdown')\n } catch (err: unknown) {\n fail(`daemon not reachable: ${String(err)}`)\n }\n if (r.status >= 400) fail(`shutdown failed: ${await r.text()}`, 2)\n if (await waitForUnreachable(timeoutMs)) {\n emit({ stopped: true, via: 'graceful' }, formatStop)\n return\n }\n const pid = readPid()\n if (pid !== null && processAlive(pid)) {\n try {\n process.kill(pid, 'SIGTERM')\n emit({ stopped: true, via: 'sigterm', pid }, formatStop)\n return\n } catch {\n // fall through to fail\n }\n }\n fail(`daemon did not exit within ${opts.timeout}s and no live PID found`, 2)\n })\n\n d.command('restart')\n .description('Stop the daemon. Next CLI command auto-spawns a fresh one.')\n .option('--timeout <s>', 'Seconds to wait for graceful exit', '5')\n .option('--eager', 'Spawn a fresh daemon immediately')\n .action(async (opts: { timeout: string; eager?: boolean }) => {\n const timeoutMs = Number(opts.timeout) * 1000\n try {\n await buildClient().request('POST', '/v1/shutdown')\n } catch {\n // already unreachable; fall through to pid cleanup\n }\n if (!(await waitForUnreachable(timeoutMs))) {\n const pid = readPid()\n if (pid !== null && processAlive(pid)) {\n try {\n process.kill(pid, 'SIGTERM')\n } catch {\n // process may have exited between checks\n }\n }\n }\n if (opts.eager === true) {\n await buildClient().ensureRunning({ allowSpawn: true })\n emit({ restarted: true, spawnedFresh: true }, formatRestart)\n return\n }\n emit(\n {\n restarted: true,\n spawnedFresh: false,\n note: 'next workspace create will auto-spawn',\n },\n formatRestart,\n )\n })\n\n d.command('kill')\n .description('SIGKILL the daemon. Last resort -- skips graceful shutdown.')\n .action(() => {\n const pid = readPid()\n if (pid === null) {\n emit({ killed: false, reason: 'no daemon running', pid: null }, formatKill)\n return\n }\n if (!processAlive(pid)) {\n emit({ killed: false, reason: 'process already gone', pid }, formatKill)\n return\n }\n try {\n process.kill(pid, 'SIGKILL')\n } catch {\n emit({ killed: false, reason: 'process gone', pid }, formatKill)\n return\n }\n emit({ killed: true, pid }, formatKill)\n })\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { readFileSync } from 'node:fs'\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, exitCodeFromResponse, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nexport function registerExecuteCommand(program: Command): void {\n program\n .command('execute')\n .description('Execute a command.')\n .requiredOption('-w, --workspace <id>', 'Workspace id')\n .requiredOption('-c, --command <command>', 'Shell command to execute')\n .option('-s, --session <id>', 'Session id')\n .option('--bg', 'Background; return job_id immediately')\n .action(\n async (opts: { workspace: string; command: string; session?: string; bg?: boolean }) => {\n const body: Record<string, unknown> = { command: opts.command, provision: false }\n if (opts.session !== undefined) body.sessionId = opts.session\n if (opts.bg !== true && !process.stdin.isTTY) {\n body.stdinBase64 = readFileSync(0).toString('base64')\n }\n const path =\n `/v1/workspaces/${opts.workspace}/execute` + (opts.bg === true ? '?background=true' : '')\n const c = makeClient(loadDaemonSettings())\n await c.ensureRunning({ allowSpawn: false })\n const response = await handleResponse(\n await c.request('POST', path, { body: JSON.stringify(body) }),\n )\n emit(response)\n process.exit(exitCodeFromResponse(response))\n },\n )\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, exitCodeFromResponse, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nfunction buildClient() {\n return makeClient(loadDaemonSettings())\n}\n\nexport function registerJobCommands(program: Command): void {\n const job = program.command('job').description('Manage daemon jobs.')\n\n job\n .command('list')\n .option('-w, --workspace <id>')\n .action(async (opts: { workspace?: string }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const path =\n '/v1/jobs' + (opts.workspace !== undefined ? `?workspaceId=${opts.workspace}` : '')\n emit(await handleResponse(await c.request('GET', path)))\n })\n\n job\n .command('get')\n .argument('<id>')\n .action(async (id: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const response = await handleResponse(await c.request('GET', `/v1/jobs/${id}`))\n emit(response)\n process.exit(exitCodeFromResponse(response))\n })\n\n job\n .command('wait')\n .argument('<id>')\n .option('--timeout <s>')\n .action(async (id: string, opts: { timeout?: string }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const body: Record<string, unknown> = {}\n if (opts.timeout !== undefined) body.timeoutS = Number(opts.timeout)\n const response = await handleResponse(\n await c.request('POST', `/v1/jobs/${id}/wait`, { body: JSON.stringify(body) }),\n )\n emit(response)\n process.exit(exitCodeFromResponse(response))\n })\n\n job\n .command('cancel')\n .argument('<id>')\n .action(async (id: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(await handleResponse(await c.request('DELETE', `/v1/jobs/${id}`)))\n })\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nexport function registerProvisionCommand(program: Command): void {\n program\n .command('provision')\n .description('Estimate cost / preview a command without running it.')\n .requiredOption('-w, --workspace <id>', 'Workspace id')\n .requiredOption('-c, --command <command>', 'Shell command to estimate')\n .option('-s, --session <id>', 'Session id')\n .action(async (opts: { workspace: string; command: string; session?: string }) => {\n const body: Record<string, unknown> = { command: opts.command, provision: true }\n if (opts.session !== undefined) body.sessionId = opts.session\n const c = makeClient(loadDaemonSettings())\n await c.ensureRunning({ allowSpawn: false })\n emit(\n await handleResponse(\n await c.request('POST', `/v1/workspaces/${opts.workspace}/execute`, {\n body: JSON.stringify(body),\n }),\n ),\n )\n })\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport type { Command } from 'commander'\nimport { makeClient } from './client.ts'\nimport { emit, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nfunction buildClient() {\n return makeClient(loadDaemonSettings())\n}\n\nexport function registerSessionCommands(program: Command): void {\n const sess = program.command('session').description('Manage workspace sessions.')\n\n sess\n .command('create')\n .argument('<wsId>')\n .option('--id <sessionId>')\n .option(\n '-m, --mount <prefix>',\n 'restrict session to this mount prefix; repeatable',\n (value: string, prev: string[]) => prev.concat([value]),\n [] as string[],\n )\n .action(async (wsId: string, opts: { id?: string; mount?: string[] }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const body: Record<string, unknown> = {}\n if (opts.id !== undefined) body.sessionId = opts.id\n if (opts.mount !== undefined && opts.mount.length > 0) {\n body.allowedMounts = opts.mount\n }\n emit(\n await handleResponse(\n await c.request('POST', `/v1/workspaces/${wsId}/sessions`, {\n body: JSON.stringify(body),\n }),\n ),\n )\n })\n\n sess\n .command('list')\n .argument('<wsId>')\n .action(async (wsId: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(await handleResponse(await c.request('GET', `/v1/workspaces/${wsId}/sessions`)))\n })\n\n sess\n .command('delete')\n .argument('<wsId>')\n .argument('<sessionId>')\n .action(async (wsId: string, sessionId: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(\n await handleResponse(\n await c.request('DELETE', `/v1/workspaces/${wsId}/sessions/${sessionId}`),\n ),\n )\n })\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { Command } from 'commander'\nimport { interpolateEnv, loadWorkspaceConfig } from '@struktoai/mirage-server'\nimport { parse as yamlParse } from 'yaml'\nimport { makeClient } from './client.ts'\nimport { emit, fail, formatAge, formatTable, handleResponse } from './output.ts'\nimport { loadDaemonSettings } from './settings.ts'\n\nfunction buildClient() {\n return makeClient(loadDaemonSettings())\n}\n\nfunction envRecord(): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(process.env)) {\n if (typeof v === 'string') out[k] = v\n }\n return out\n}\n\nfunction loadConfigArgument(path: string): unknown {\n if (!existsSync(path)) fail(`config file not found: ${path}`, 2)\n const text = readFileSync(path, 'utf-8')\n try {\n return interpolateEnv(yamlParse(text), envRecord())\n } catch (err: unknown) {\n fail(`invalid config YAML/JSON at ${path}: ${String(err)}`, 2)\n }\n}\n\ninterface WorkspaceBrief {\n id: string\n mode: string\n mountCount: number\n sessionCount: number\n createdAt: number\n}\n\ninterface MountSummary {\n prefix: string\n resource: string\n mode: string\n}\n\ninterface SessionSummary {\n sessionId: string\n cwd: string\n}\n\ninterface Internals {\n cacheBytes: number\n cacheEntries: number\n historyLength: number\n inFlightJobs: number\n}\n\ninterface WorkspaceDetail {\n id: string\n mode: string\n createdAt: number\n mounts?: MountSummary[]\n sessions?: SessionSummary[]\n internals?: Internals | null\n}\n\nfunction formatWorkspaceList(items: WorkspaceBrief[]): string {\n if (items.length === 0) return 'No active workspaces.'\n const rows = items.map((w) => [\n w.id,\n w.mode,\n String(w.mountCount),\n String(w.sessionCount),\n formatAge(w.createdAt),\n ])\n return formatTable(['ID', 'MODE', 'MOUNTS', 'SESSIONS', 'AGE'], rows)\n}\n\nfunction formatWorkspaceDetail(d: WorkspaceDetail): string {\n const lines: string[] = [\n `ID: ${d.id}`,\n `Mode: ${d.mode}`,\n `Created: ${formatAge(d.createdAt)} ago`,\n ]\n if (d.mounts !== undefined && d.mounts.length > 0) {\n const rows = d.mounts.map((m) => [m.prefix, m.resource, m.mode])\n lines.push('', 'Mounts:')\n for (const ln of formatTable(['PREFIX', 'RESOURCE', 'MODE'], rows).split('\\n')) {\n lines.push(' ' + ln)\n }\n }\n if (d.sessions !== undefined && d.sessions.length > 0) {\n const rows = d.sessions.map((s) => [s.sessionId, s.cwd])\n lines.push('', 'Sessions:')\n for (const ln of formatTable(['SESSION', 'CWD'], rows).split('\\n')) {\n lines.push(' ' + ln)\n }\n }\n if (d.internals != null) {\n lines.push('', 'Internals:')\n for (const k of ['cacheBytes', 'cacheEntries', 'historyLength', 'inFlightJobs'] as const) {\n lines.push(` ${k.padEnd(16)} ${String(d.internals[k])}`)\n }\n }\n return lines.join('\\n')\n}\n\ninterface VersionLogItem {\n id: string\n message: string\n}\n\ninterface DiffResult {\n added: string[]\n modified: string[]\n deleted: string[]\n}\n\nfunction formatVersionLog(items: VersionLogItem[]): string {\n if (items.length === 0) return 'No versions.'\n return formatTable(\n ['VERSION', 'MESSAGE'],\n items.map((v) => [v.id.slice(0, 12), v.message]),\n )\n}\n\nfunction formatDiff(changes: DiffResult): string {\n const lines: string[] = []\n for (const kind of ['added', 'modified', 'deleted'] as const) {\n for (const path of changes[kind]) lines.push(`${kind.padEnd(9)} ${path}`)\n }\n return lines.length > 0 ? lines.join('\\n') : 'No changes.'\n}\n\nexport function registerWorkspaceCommands(program: Command): void {\n const ws = program.command('workspace').description('Manage workspaces.')\n\n ws.command('create')\n .description('Create a workspace; daemon auto-spawns if not running.')\n .argument('<config>', 'YAML/JSON workspace config')\n .option('--id <id>', 'Explicit workspace id')\n .action(async (configPath: string, opts: { id?: string }) => {\n const cfg = loadWorkspaceConfig(configPath)\n const body: { config: unknown; id?: string } = { config: cfg }\n if (opts.id !== undefined) body.id = opts.id\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: true })\n const r = await c.request('POST', '/v1/workspaces', { body: JSON.stringify(body) })\n emit((await handleResponse(r)) as WorkspaceDetail, formatWorkspaceDetail)\n })\n\n ws.command('list')\n .description('List active workspaces.')\n .action(async () => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(\n (await handleResponse(await c.request('GET', '/v1/workspaces'))) as WorkspaceBrief[],\n formatWorkspaceList,\n )\n })\n\n ws.command('get')\n .description('Show full details for one workspace.')\n .argument('<id>')\n .option('--verbose', 'Include cache/dirty/history internals')\n .action(async (id: string, opts: { verbose?: boolean }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const path = `/v1/workspaces/${id}` + (opts.verbose === true ? '?verbose=true' : '')\n emit(\n (await handleResponse(await c.request('GET', path))) as WorkspaceDetail,\n formatWorkspaceDetail,\n )\n })\n\n ws.command('delete')\n .description('Stop and remove a workspace.')\n .argument('<id>')\n .action(async (id: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n emit(\n (await handleResponse(await c.request('DELETE', `/v1/workspaces/${id}`))) as {\n id: string\n },\n (d) => `Deleted workspace ${d.id}.`,\n )\n })\n\n ws.command('clone')\n .description('Clone a workspace, optionally from one of its past versions.')\n .argument('<srcId>')\n .option('--id <id>', 'Explicit id for the clone')\n .option('--at <ref>', 'Clone from a past version (id or branch) not the live state')\n .action(async (srcId: string, opts: { id?: string; at?: string }) => {\n const body: Record<string, unknown> = { sourceId: srcId }\n if (opts.id !== undefined) body.id = opts.id\n if (opts.at !== undefined) body.at = opts.at\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('POST', '/v1/workspaces/clone', { body: JSON.stringify(body) })\n emit((await handleResponse(r)) as WorkspaceDetail, formatWorkspaceDetail)\n })\n\n ws.command('commit')\n .description(\"Commit the workspace's current state as a version.\")\n .argument('<id>')\n .option('-m, --message <msg>', 'Version message', '')\n .option('-b, --branch <branch>', 'Branch to commit on', 'main')\n .action(async (id: string, opts: { message: string; branch: string }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('POST', `/v1/workspaces/${id}/commit`, {\n body: JSON.stringify({ message: opts.message, branch: opts.branch }),\n })\n emit(\n (await handleResponse(r)) as { version: string; branch: string },\n (d) => `Committed ${d.version.slice(0, 12)} on ${d.branch}.`,\n )\n })\n\n ws.command('branch')\n .description(\"Create a branch at another branch's current version.\")\n .argument('<id>')\n .argument('<name>')\n .option('--from <branch>', 'Branch to fork from', 'main')\n .action(async (id: string, name: string, opts: { from: string }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('POST', `/v1/workspaces/${id}/branch`, {\n body: JSON.stringify({ name, fromBranch: opts.from }),\n })\n emit(\n (await handleResponse(r)) as { branch: string; version: string },\n (d) => `Created branch ${d.branch} at ${d.version.slice(0, 12)}.`,\n )\n })\n\n ws.command('log')\n .description(\"List a workspace's versions (newest first).\")\n .argument('<id>')\n .option('-b, --branch <branch>', 'Branch', 'main')\n .action(async (id: string, opts: { branch: string }) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('GET', `/v1/workspaces/${id}/versions?branch=${opts.branch}`)\n emit((await handleResponse(r)) as VersionLogItem[], formatVersionLog)\n })\n\n ws.command('diff')\n .description('Show changed files (git-style): live vs HEAD, live vs <a>, or <a> vs <b>.')\n .argument('<id>')\n .argument('[a]', 'Base ref; omit to use live state')\n .argument('[b]', 'Compare ref; omit to use live state')\n .option('-b, --branch <branch>', 'Branch', 'main')\n .action(\n async (\n id: string,\n a: string | undefined,\n b: string | undefined,\n opts: { branch: string },\n ) => {\n const params = new URLSearchParams({ branch: opts.branch })\n if (a !== undefined) params.set('a', a)\n if (b !== undefined) params.set('b', b)\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('GET', `/v1/workspaces/${id}/diff?${params.toString()}`)\n emit((await handleResponse(r)) as DiffResult, formatDiff)\n },\n )\n\n ws.command('checkout')\n .description('Restore a workspace in place to one of its versions.')\n .argument('<id>')\n .argument('<ref>', 'Version id or branch to restore')\n .action(async (id: string, ref: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('POST', `/v1/workspaces/${id}/checkout`, {\n body: JSON.stringify({ ref }),\n })\n emit((await handleResponse(r)) as WorkspaceDetail, formatWorkspaceDetail)\n })\n\n ws.command('snapshot')\n .description(\n 'Snapshot a workspace to a tar file. The path is resolved to an absolute path and the daemon writes the tar.',\n )\n .argument('<id>')\n .argument('<output>', 'Path to write the .tar to')\n .action(async (id: string, output: string) => {\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: false })\n const r = await c.request('POST', `/v1/workspaces/${id}/snapshot`, {\n body: JSON.stringify({ path: resolve(output) }),\n })\n const d = (await handleResponse(r)) as { id: string; path: string; size: number }\n emit(d, (x) => `Snapshot ${x.id} -> ${x.path} (${x.size.toLocaleString()} bytes).`)\n })\n\n ws.command('load')\n .description('Load a workspace from a tar file.')\n .argument('<tar>', 'Path to a .tar produced by `mirage workspace snapshot`')\n .argument('[config]', 'Workspace YAML/JSON config')\n .option('--id <id>', 'Explicit workspace id')\n .action(async (tarPath: string, configPath: string | undefined, opts: { id?: string }) => {\n if (!existsSync(tarPath)) fail(`tar file not found: ${tarPath}`, 2)\n const body: { path: string; id?: string; override?: unknown } = { path: resolve(tarPath) }\n if (opts.id !== undefined) body.id = opts.id\n if (configPath !== undefined) body.override = loadConfigArgument(configPath)\n const c = buildClient()\n await c.ensureRunning({ allowSpawn: true })\n const r = await c.request('POST', '/v1/workspaces/load', { body: JSON.stringify(body) })\n emit((await handleResponse(r)) as WorkspaceDetail, formatWorkspaceDetail)\n })\n}\n","#!/usr/bin/env node\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { buildProgram } from '../main.ts'\n\nconst ALIASES: Record<string, string> = {\n '--workspace_id': '--workspace',\n '--session_id': '--session',\n}\n\nfunction rewriteArgv(argv: string[]): string[] {\n return argv.map((arg) => {\n for (const [from, to] of Object.entries(ALIASES)) {\n if (arg === from) return to\n if (arg.startsWith(from + '=')) return to + arg.slice(from.length)\n }\n return arg\n })\n}\n\nbuildProgram()\n .parseAsync(rewriteArgv(process.argv))\n .catch((err: unknown) => {\n console.error(err)\n process.exit(1)\n })\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAS,SAAS,QAAAC,aAAY;AAC9B,SAAS,qBAA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AU,IAAI,QAAQ;AAC5B,UACG,KAAK,QAAQ,EACb,YAAY,4DAA4D,EACxE,QAAQ,eAAe,CAAC;AAC3B,4BAA0B,OAAO;AACjC,0BAAwB,OAAO;AAC/B,sBAAoB,OAAO;AAC3B,yBAAuB,OAAO;AAC9B,2BAAyB,OAAO;AAChC,yBAAuB,OAAO;AAC9B,SAAO;AACT;;;AOtCA,IAAM,UAAkC;AAAA,EACtC,kBAAkB;AAAA,EAClB,gBAAgB;AAClB;AAEA,SAAS,YAAY,MAA0B;AAC7C,SAAO,KAAK,IAAI,CAAC,QAAQ;AACvB,eAAW,CAAC,MAAM,EAAE,KAAK,OAAO,QAAQ,OAAO,GAAG;AAChD,UAAI,QAAQ,KAAM,QAAO;AACzB,UAAI,IAAI,WAAW,OAAO,GAAG,EAAG,QAAO,KAAK,IAAI,MAAM,KAAK,MAAM;AAAA,IACnE;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAEA,aAAa,EACV,WAAW,YAAY,QAAQ,IAAI,CAAC,EACpC,MAAM,CAAC,QAAiB;AACvB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["readFileSync","join","readFileSync","readFileSync","buildClient","buildClient","existsSync","readFileSync","buildClient","existsSync","readFileSync","readFileSync","join"]}
@@ -4,6 +4,26 @@ import { existsSync, mkdirSync, openSync } from "fs";
4
4
  import { createRequire } from "module";
5
5
  import { homedir } from "os";
6
6
  import { join } from "path";
7
+ import { AuthMode, DEFAULT_TOKEN_FILE, ensureTokenFile } from "@struktoai/mirage-server";
8
+
9
+ // src/env.ts
10
+ import {
11
+ ENV_AUTH_MODE,
12
+ ENV_AUTH_TOKEN,
13
+ ENV_DAEMON_PORT,
14
+ ENV_IDLE_GRACE_SECONDS,
15
+ ENV_JWT_ALG,
16
+ ENV_JWT_AUDIENCE,
17
+ ENV_JWT_AUTHORIZED_PARTIES,
18
+ ENV_JWT_CLOCK_SKEW,
19
+ ENV_JWT_ISSUER,
20
+ ENV_JWT_PUBKEY,
21
+ ENV_JWT_PUBKEY_FILE
22
+ } from "@struktoai/mirage-server";
23
+ var ENV_DAEMON_URL = "MIRAGE_DAEMON_URL";
24
+ var ENV_TOKEN = "MIRAGE_TOKEN";
25
+
26
+ // src/client.ts
7
27
  var requireFromHere = createRequire(import.meta.url);
8
28
  var DEFAULT_REQUEST_TIMEOUT_MS = 6e4;
9
29
  var DaemonClient = class {
@@ -95,10 +115,13 @@ var DaemonClient = class {
95
115
  for (const [k, v] of Object.entries(process.env)) {
96
116
  if (typeof v === "string") env[k] = v;
97
117
  }
98
- env.MIRAGE_DAEMON_PORT = String(this.portFromUrl());
99
- env.MIRAGE_IDLE_GRACE_SECONDS = String(this.settings.idleGraceSeconds);
100
- if (this.settings.authToken !== "") env.MIRAGE_AUTH_TOKEN = this.settings.authToken;
101
- if (this.settings.persistDir !== "") env.MIRAGE_PERSIST_DIR = this.settings.persistDir;
118
+ env[ENV_DAEMON_PORT] = String(this.portFromUrl());
119
+ env[ENV_IDLE_GRACE_SECONDS] = String(this.settings.idleGraceSeconds);
120
+ if (this.settings.authToken === "") {
121
+ this.settings.authToken = ensureTokenFile(DEFAULT_TOKEN_FILE);
122
+ }
123
+ env[ENV_AUTH_TOKEN] = this.settings.authToken;
124
+ env[ENV_AUTH_MODE] ??= AuthMode.Local;
102
125
  const logDir = join(homedir(), ".mirage");
103
126
  mkdirSync(logDir, { recursive: true });
104
127
  const out = openSync(join(logDir, "daemon.log"), "a");
@@ -131,6 +154,7 @@ function makeClient(settings) {
131
154
  import { existsSync as existsSync2, readFileSync } from "fs";
132
155
  import { homedir as homedir2 } from "os";
133
156
  import { join as join2 } from "path";
157
+ import { DEFAULT_TOKEN_FILE as DEFAULT_TOKEN_FILE2, readTokenFile } from "@struktoai/mirage-server";
134
158
  var DEFAULT_DAEMON_URL = "http://127.0.0.1:8765";
135
159
  function defaultConfigPath() {
136
160
  return join2(homedir2(), ".mirage", "config.toml");
@@ -169,15 +193,22 @@ function loadDaemonSettings(options = {}) {
169
193
  const table = readDaemonTable(path);
170
194
  const settings = {
171
195
  url: table.url ?? DEFAULT_DAEMON_URL,
172
- persistDir: table.persist_dir ?? "",
173
196
  authToken: table.auth_token ?? "",
174
197
  idleGraceSeconds: Number(table.idle_grace_seconds ?? "30")
175
198
  };
176
- if (env.MIRAGE_DAEMON_URL !== void 0 && env.MIRAGE_DAEMON_URL !== "") {
177
- settings.url = env.MIRAGE_DAEMON_URL;
199
+ const envUrl = env[ENV_DAEMON_URL];
200
+ if (envUrl !== void 0 && envUrl !== "") {
201
+ settings.url = envUrl;
178
202
  }
179
- if (env.MIRAGE_TOKEN !== void 0 && env.MIRAGE_TOKEN !== "") {
180
- settings.authToken = env.MIRAGE_TOKEN;
203
+ const envToken = env[ENV_TOKEN];
204
+ if (envToken !== void 0 && envToken !== "") {
205
+ settings.authToken = envToken;
206
+ }
207
+ if (settings.authToken === "") {
208
+ const fileToken = readTokenFile(options.tokenFile ?? DEFAULT_TOKEN_FILE2);
209
+ if (fileToken !== void 0 && fileToken !== "") {
210
+ settings.authToken = fileToken;
211
+ }
181
212
  }
182
213
  return settings;
183
214
  }
@@ -194,6 +225,18 @@ function fail(message, exitCode = 1) {
194
225
  process.stderr.write(message + "\n");
195
226
  process.exit(exitCode);
196
227
  }
228
+ function exitCodeFromResponse(r) {
229
+ if (typeof r !== "object" || r === null) return 0;
230
+ const obj = r;
231
+ const inner = obj.kind === "io" ? obj : obj.result ?? null;
232
+ if (inner !== null && inner.kind === "io" && typeof inner.exitCode === "number" && Number.isFinite(inner.exitCode)) {
233
+ return Math.min(255, Math.max(0, Math.trunc(inner.exitCode)));
234
+ }
235
+ if (typeof obj.status === "string" && (obj.status === "failed" || obj.status === "canceled")) {
236
+ return 2;
237
+ }
238
+ return 0;
239
+ }
197
240
  async function handleResponse(r) {
198
241
  if (r.status >= 400) {
199
242
  let detail = await r.text();
@@ -245,8 +288,9 @@ export {
245
288
  loadDaemonSettings,
246
289
  emit,
247
290
  fail,
291
+ exitCodeFromResponse,
248
292
  handleResponse,
249
293
  formatAge,
250
294
  formatTable
251
295
  };
252
- //# sourceMappingURL=chunk-42V4PGGP.js.map
296
+ //# sourceMappingURL=chunk-IMRNFGEA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/env.ts","../src/settings.ts","../src/output.ts"],"sourcesContent":["// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { spawn } from 'node:child_process'\nimport { existsSync, mkdirSync, openSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { AuthMode, DEFAULT_TOKEN_FILE, ensureTokenFile } from '@struktoai/mirage-server'\n\nimport { ENV_AUTH_MODE, ENV_AUTH_TOKEN, ENV_DAEMON_PORT, ENV_IDLE_GRACE_SECONDS } from './env.ts'\nimport type { DaemonSettings } from './settings.ts'\n\nconst requireFromHere = createRequire(import.meta.url)\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 60_000\n\nexport class DaemonClient {\n readonly settings: DaemonSettings\n\n constructor(settings: DaemonSettings) {\n this.settings = settings\n }\n\n private headers(extra?: Record<string, string>): Record<string, string> {\n const h: Record<string, string> = { ...extra }\n if (this.settings.authToken !== '') h.Authorization = `Bearer ${this.settings.authToken}`\n return h\n }\n\n async request(\n method: string,\n path: string,\n init: RequestInit & { timeoutMs?: number } = {},\n ): Promise<Response> {\n const { timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, ...rest } = init\n const headers: Record<string, string> = {\n ...this.headers(),\n ...((rest.headers ?? {}) as Record<string, string>),\n }\n if (rest.body !== undefined && headers['Content-Type'] === undefined) {\n headers['Content-Type'] = 'application/json'\n }\n const ctrl = new AbortController()\n const t = setTimeout(() => {\n ctrl.abort()\n }, timeoutMs)\n try {\n return await fetch(this.settings.url + path, {\n ...rest,\n method,\n headers,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(t)\n }\n }\n\n async requestMultipart(method: string, path: string, form: FormData): Promise<Response> {\n const ctrl = new AbortController()\n const t = setTimeout(() => {\n ctrl.abort()\n }, DEFAULT_REQUEST_TIMEOUT_MS)\n try {\n return await fetch(this.settings.url + path, {\n method,\n headers: this.headers(),\n body: form,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(t)\n }\n }\n\n async isReachable(timeoutMs = 500): Promise<boolean> {\n const ctrl = new AbortController()\n const t = setTimeout(() => {\n ctrl.abort()\n }, timeoutMs)\n try {\n const r = await fetch(this.settings.url + '/v1/health', {\n headers: this.headers(),\n signal: ctrl.signal,\n })\n return r.status === 200\n } catch {\n return false\n } finally {\n clearTimeout(t)\n }\n }\n\n async ensureRunning(opts: { allowSpawn?: boolean; timeoutMs?: number } = {}): Promise<void> {\n const allowSpawn = opts.allowSpawn ?? true\n const timeoutMs = opts.timeoutMs ?? 5000\n if (await this.isReachable()) return\n if (!allowSpawn) {\n throw new Error(\n `daemon not reachable at ${this.settings.url}; run \\`mirage workspace create CONFIG.yaml\\``,\n )\n }\n this.spawnDaemon()\n const deadline = Date.now() + timeoutMs\n while (Date.now() < deadline) {\n if (await this.isReachable(300)) return\n await new Promise((r) => setTimeout(r, 100))\n }\n throw new Error(`daemon spawned but did not answer /v1/health within ${String(timeoutMs)}ms`)\n }\n\n private spawnDaemon(): void {\n const env: Record<string, string> = {}\n for (const [k, v] of Object.entries(process.env)) {\n if (typeof v === 'string') env[k] = v\n }\n env[ENV_DAEMON_PORT] = String(this.portFromUrl())\n env[ENV_IDLE_GRACE_SECONDS] = String(this.settings.idleGraceSeconds)\n if (this.settings.authToken === '') {\n this.settings.authToken = ensureTokenFile(DEFAULT_TOKEN_FILE)\n }\n env[ENV_AUTH_TOKEN] = this.settings.authToken\n env[ENV_AUTH_MODE] ??= AuthMode.Local\n const logDir = join(homedir(), '.mirage')\n mkdirSync(logDir, { recursive: true })\n const out = openSync(join(logDir, 'daemon.log'), 'a')\n const daemonEntry = requireFromHere.resolve('@struktoai/mirage-server/bin/daemon')\n if (!existsSync(daemonEntry)) {\n throw new Error(\n `daemon binary not found at ${daemonEntry}; reinstall @struktoai/mirage-server`,\n )\n }\n const child = spawn(process.execPath, [daemonEntry], {\n env,\n detached: true,\n stdio: ['ignore', out, out],\n })\n child.on('error', (err) => {\n console.error('failed to spawn daemon:', err)\n })\n child.unref()\n }\n\n private portFromUrl(): number {\n const u = new URL(this.settings.url)\n return Number(u.port) || 8765\n }\n}\n\nexport function makeClient(settings: DaemonSettings): DaemonClient {\n return new DaemonClient(settings)\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nexport {\n ENV_AUTH_MODE,\n ENV_AUTH_TOKEN,\n ENV_DAEMON_PORT,\n ENV_IDLE_GRACE_SECONDS,\n ENV_JWT_ALG,\n ENV_JWT_AUDIENCE,\n ENV_JWT_AUTHORIZED_PARTIES,\n ENV_JWT_CLOCK_SKEW,\n ENV_JWT_ISSUER,\n ENV_JWT_PUBKEY,\n ENV_JWT_PUBKEY_FILE,\n} from '@struktoai/mirage-server'\n\nexport const ENV_DAEMON_URL = 'MIRAGE_DAEMON_URL'\nexport const ENV_TOKEN = 'MIRAGE_TOKEN'\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { DEFAULT_TOKEN_FILE, readTokenFile } from '@struktoai/mirage-server'\n\nimport { ENV_DAEMON_URL, ENV_TOKEN } from './env.ts'\n\nexport const DEFAULT_DAEMON_URL = 'http://127.0.0.1:8765'\n\nexport interface DaemonSettings {\n url: string\n authToken: string\n idleGraceSeconds: number\n}\n\nexport interface LoadOptions {\n env?: Record<string, string | undefined>\n configPath?: string\n tokenFile?: string\n}\n\nfunction defaultConfigPath(): string {\n return join(homedir(), '.mirage', 'config.toml')\n}\n\nfunction parseValue(raw: string): string {\n if (raw.startsWith('\"') && raw.endsWith('\"')) return raw.slice(1, -1)\n return raw\n}\n\nfunction readDaemonTable(path: string): Record<string, string> {\n if (!existsSync(path)) return {}\n const text = readFileSync(path, 'utf-8')\n const out: Record<string, string> = {}\n let inDaemon = false\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed === '' || trimmed.startsWith('#')) continue\n if (trimmed === '[daemon]') {\n inDaemon = true\n continue\n }\n if (trimmed.startsWith('[')) {\n inDaemon = false\n continue\n }\n if (!inDaemon) continue\n const eq = trimmed.indexOf('=')\n if (eq < 0) continue\n const key = trimmed.slice(0, eq).trim()\n out[key] = parseValue(trimmed.slice(eq + 1).trim())\n }\n return out\n}\n\nexport function loadDaemonSettings(options: LoadOptions = {}): DaemonSettings {\n const env = options.env ?? (process.env as Record<string, string | undefined>)\n const path = options.configPath ?? defaultConfigPath()\n const table = readDaemonTable(path)\n const settings: DaemonSettings = {\n url: table.url ?? DEFAULT_DAEMON_URL,\n authToken: table.auth_token ?? '',\n idleGraceSeconds: Number(table.idle_grace_seconds ?? '30'),\n }\n const envUrl = env[ENV_DAEMON_URL]\n if (envUrl !== undefined && envUrl !== '') {\n settings.url = envUrl\n }\n const envToken = env[ENV_TOKEN]\n if (envToken !== undefined && envToken !== '') {\n settings.authToken = envToken\n }\n if (settings.authToken === '') {\n const fileToken = readTokenFile(options.tokenFile ?? DEFAULT_TOKEN_FILE)\n if (fileToken !== undefined && fileToken !== '') {\n settings.authToken = fileToken\n }\n }\n return settings\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nexport type Formatter<T = unknown> = (obj: T) => string\n\nexport function emit<T = unknown>(obj: T, human?: Formatter<T>): void {\n if (human !== undefined && process.stdout.isTTY) {\n process.stdout.write(human(obj) + '\\n')\n return\n }\n process.stdout.write(JSON.stringify(obj, null, 2) + '\\n')\n}\n\nexport function fail(message: string, exitCode = 1): never {\n process.stderr.write(message + '\\n')\n process.exit(exitCode)\n}\n\nexport function exitCodeFromResponse(r: unknown): number {\n if (typeof r !== 'object' || r === null) return 0\n const obj = r as Record<string, unknown>\n const inner =\n obj.kind === 'io' ? obj : ((obj.result as Record<string, unknown> | null | undefined) ?? null)\n if (\n inner !== null &&\n inner.kind === 'io' &&\n typeof inner.exitCode === 'number' &&\n Number.isFinite(inner.exitCode)\n ) {\n return Math.min(255, Math.max(0, Math.trunc(inner.exitCode)))\n }\n if (typeof obj.status === 'string' && (obj.status === 'failed' || obj.status === 'canceled')) {\n return 2\n }\n return 0\n}\n\nexport async function handleResponse(r: Response): Promise<unknown> {\n if (r.status >= 400) {\n let detail = await r.text()\n try {\n const parsed = JSON.parse(detail) as { detail?: string }\n if (parsed.detail !== undefined) detail = parsed.detail\n } catch {\n // body wasn't JSON; fall through with the raw text as detail\n }\n fail(`daemon error ${String(r.status)}: ${detail}`, 2)\n }\n if (r.status === 204) return {}\n const text = await r.text()\n if (text === '') return {}\n return JSON.parse(text) as unknown\n}\n\nexport function formatAge(epoch: number, now: number = Date.now() / 1000): string {\n const delta = Math.max(0, now - epoch)\n if (delta < 60) return `${String(Math.floor(delta))}s`\n if (delta < 3600) return `${String(Math.floor(delta / 60))}m`\n if (delta < 86400) return `${String(Math.floor(delta / 3600))}h`\n return `${String(Math.floor(delta / 86400))}d`\n}\n\nexport function formatTable(headers: string[], rows: (string | undefined)[][]): string {\n if (rows.length === 0) return headers.join(' ')\n const norm: string[][] = rows.map((row) => row.map((c) => c ?? ''))\n const widths = headers.map((h) => h.length)\n for (const row of norm) {\n for (let i = 0; i < row.length; i++) {\n widths[i] = Math.max(widths[i] ?? 0, row[i]?.length ?? 0)\n }\n }\n const pad = (s: string, w: number) => s + ' '.repeat(Math.max(0, w - s.length))\n const out: string[] = []\n out.push(\n headers\n .map((h, i) => pad(h, widths[i] ?? h.length))\n .join(' ')\n .replace(/\\s+$/, ''),\n )\n for (const row of norm) {\n out.push(\n row\n .map((c, i) => pad(c, widths[i] ?? c.length))\n .join(' ')\n .replace(/\\s+$/, ''),\n )\n }\n return out.join('\\n')\n}\n"],"mappings":";AAcA,SAAS,aAAa;AACtB,SAAS,YAAY,WAAW,gBAAgB;AAChD,SAAS,qBAAqB;AAC9B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AG,IAAI,EAAE,MAAM,CAAC;AAC9E,QAAM,MAAgB,CAAC;AACvB,MAAI;AAAA,IACF,QACG,IAAI,CAAC,GAAG,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,EAC3C,KAAK,IAAI,EACT,QAAQ,QAAQ,EAAE;AAAA,EACvB;AACA,aAAW,OAAO,MAAM;AACtB,QAAI;AAAA,MACF,IACG,IAAI,CAAC,GAAG,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,EAC3C,KAAK,IAAI,EACT,QAAQ,QAAQ,EAAE;AAAA,IACvB;AAAA,EACF;AACA,SAAO,IAAI,KAAK,IAAI;AACtB;","names":["existsSync","homedir","join","DEFAULT_TOKEN_FILE","join","homedir","existsSync","DEFAULT_TOKEN_FILE"]}
package/dist/index.d.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  declare const DEFAULT_DAEMON_URL = "http://127.0.0.1:8765";
2
2
  interface DaemonSettings {
3
3
  url: string;
4
- persistDir: string;
5
4
  authToken: string;
6
5
  idleGraceSeconds: number;
7
6
  }
8
7
  interface LoadOptions {
9
8
  env?: Record<string, string | undefined>;
10
9
  configPath?: string;
10
+ tokenFile?: string;
11
11
  }
12
12
  declare function loadDaemonSettings(options?: LoadOptions): DaemonSettings;
13
13
 
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  handleResponse,
7
7
  loadDaemonSettings,
8
8
  makeClient
9
- } from "./chunk-42V4PGGP.js";
9
+ } from "./chunk-IMRNFGEA.js";
10
10
  export {
11
11
  DEFAULT_DAEMON_URL,
12
12
  DaemonClient,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@struktoai/mirage-cli",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "A Unified Virtual Filesystem For AI Agents",
5
5
  "keywords": [
6
6
  "bash",
@@ -42,13 +42,16 @@
42
42
  "dependencies": {
43
43
  "commander": "^14.0.0",
44
44
  "yaml": "^2.6.0",
45
- "@struktoai/mirage-server": "0.0.1"
45
+ "@struktoai/mirage-server": "0.0.2"
46
+ },
47
+ "optionalDependencies": {
48
+ "@zkochan/fuse-native": "^0.1.0"
46
49
  },
47
50
  "devDependencies": {
48
51
  "@types/node": "^22.0.0",
49
52
  "tsup": "^8.5.0",
50
53
  "typescript": "^6.0.0",
51
- "vitest": "^3.0.0"
54
+ "vitest": "^3.2.6"
52
55
  },
53
56
  "scripts": {
54
57
  "build": "tsup",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/client.ts","../src/settings.ts","../src/output.ts"],"sourcesContent":["// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { spawn } from 'node:child_process'\nimport { existsSync, mkdirSync, openSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { DaemonSettings } from './settings.ts'\n\nconst requireFromHere = createRequire(import.meta.url)\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 60_000\n\nexport class DaemonClient {\n readonly settings: DaemonSettings\n\n constructor(settings: DaemonSettings) {\n this.settings = settings\n }\n\n private headers(extra?: Record<string, string>): Record<string, string> {\n const h: Record<string, string> = { ...extra }\n if (this.settings.authToken !== '') h.Authorization = `Bearer ${this.settings.authToken}`\n return h\n }\n\n async request(\n method: string,\n path: string,\n init: RequestInit & { timeoutMs?: number } = {},\n ): Promise<Response> {\n const { timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, ...rest } = init\n const headers: Record<string, string> = {\n ...this.headers(),\n ...((rest.headers ?? {}) as Record<string, string>),\n }\n if (rest.body !== undefined && headers['Content-Type'] === undefined) {\n headers['Content-Type'] = 'application/json'\n }\n const ctrl = new AbortController()\n const t = setTimeout(() => {\n ctrl.abort()\n }, timeoutMs)\n try {\n return await fetch(this.settings.url + path, {\n ...rest,\n method,\n headers,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(t)\n }\n }\n\n async requestMultipart(method: string, path: string, form: FormData): Promise<Response> {\n const ctrl = new AbortController()\n const t = setTimeout(() => {\n ctrl.abort()\n }, DEFAULT_REQUEST_TIMEOUT_MS)\n try {\n return await fetch(this.settings.url + path, {\n method,\n headers: this.headers(),\n body: form,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(t)\n }\n }\n\n async isReachable(timeoutMs = 500): Promise<boolean> {\n const ctrl = new AbortController()\n const t = setTimeout(() => {\n ctrl.abort()\n }, timeoutMs)\n try {\n const r = await fetch(this.settings.url + '/v1/health', {\n headers: this.headers(),\n signal: ctrl.signal,\n })\n return r.status === 200\n } catch {\n return false\n } finally {\n clearTimeout(t)\n }\n }\n\n async ensureRunning(opts: { allowSpawn?: boolean; timeoutMs?: number } = {}): Promise<void> {\n const allowSpawn = opts.allowSpawn ?? true\n const timeoutMs = opts.timeoutMs ?? 5000\n if (await this.isReachable()) return\n if (!allowSpawn) {\n throw new Error(\n `daemon not reachable at ${this.settings.url}; run \\`mirage workspace create CONFIG.yaml\\``,\n )\n }\n this.spawnDaemon()\n const deadline = Date.now() + timeoutMs\n while (Date.now() < deadline) {\n if (await this.isReachable(300)) return\n await new Promise((r) => setTimeout(r, 100))\n }\n throw new Error(`daemon spawned but did not answer /v1/health within ${String(timeoutMs)}ms`)\n }\n\n private spawnDaemon(): void {\n const env: Record<string, string> = {}\n for (const [k, v] of Object.entries(process.env)) {\n if (typeof v === 'string') env[k] = v\n }\n env.MIRAGE_DAEMON_PORT = String(this.portFromUrl())\n env.MIRAGE_IDLE_GRACE_SECONDS = String(this.settings.idleGraceSeconds)\n if (this.settings.authToken !== '') env.MIRAGE_AUTH_TOKEN = this.settings.authToken\n if (this.settings.persistDir !== '') env.MIRAGE_PERSIST_DIR = this.settings.persistDir\n const logDir = join(homedir(), '.mirage')\n mkdirSync(logDir, { recursive: true })\n const out = openSync(join(logDir, 'daemon.log'), 'a')\n const daemonEntry = requireFromHere.resolve('@struktoai/mirage-server/bin/daemon')\n if (!existsSync(daemonEntry)) {\n throw new Error(\n `daemon binary not found at ${daemonEntry}; reinstall @struktoai/mirage-server`,\n )\n }\n const child = spawn(process.execPath, [daemonEntry], {\n env,\n detached: true,\n stdio: ['ignore', out, out],\n })\n child.on('error', (err) => {\n console.error('failed to spawn daemon:', err)\n })\n child.unref()\n }\n\n private portFromUrl(): number {\n const u = new URL(this.settings.url)\n return Number(u.port) || 8765\n }\n}\n\nexport function makeClient(settings: DaemonSettings): DaemonClient {\n return new DaemonClient(settings)\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nexport const DEFAULT_DAEMON_URL = 'http://127.0.0.1:8765'\n\nexport interface DaemonSettings {\n url: string\n persistDir: string\n authToken: string\n idleGraceSeconds: number\n}\n\nexport interface LoadOptions {\n env?: Record<string, string | undefined>\n configPath?: string\n}\n\nfunction defaultConfigPath(): string {\n return join(homedir(), '.mirage', 'config.toml')\n}\n\nfunction parseValue(raw: string): string {\n if (raw.startsWith('\"') && raw.endsWith('\"')) return raw.slice(1, -1)\n return raw\n}\n\nfunction readDaemonTable(path: string): Record<string, string> {\n if (!existsSync(path)) return {}\n const text = readFileSync(path, 'utf-8')\n const out: Record<string, string> = {}\n let inDaemon = false\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed === '' || trimmed.startsWith('#')) continue\n if (trimmed === '[daemon]') {\n inDaemon = true\n continue\n }\n if (trimmed.startsWith('[')) {\n inDaemon = false\n continue\n }\n if (!inDaemon) continue\n const eq = trimmed.indexOf('=')\n if (eq < 0) continue\n const key = trimmed.slice(0, eq).trim()\n out[key] = parseValue(trimmed.slice(eq + 1).trim())\n }\n return out\n}\n\nexport function loadDaemonSettings(options: LoadOptions = {}): DaemonSettings {\n const env = options.env ?? (process.env as Record<string, string | undefined>)\n const path = options.configPath ?? defaultConfigPath()\n const table = readDaemonTable(path)\n const settings: DaemonSettings = {\n url: table.url ?? DEFAULT_DAEMON_URL,\n persistDir: table.persist_dir ?? '',\n authToken: table.auth_token ?? '',\n idleGraceSeconds: Number(table.idle_grace_seconds ?? '30'),\n }\n if (env.MIRAGE_DAEMON_URL !== undefined && env.MIRAGE_DAEMON_URL !== '') {\n settings.url = env.MIRAGE_DAEMON_URL\n }\n if (env.MIRAGE_TOKEN !== undefined && env.MIRAGE_TOKEN !== '') {\n settings.authToken = env.MIRAGE_TOKEN\n }\n return settings\n}\n","// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========\n\nexport type Formatter<T = unknown> = (obj: T) => string\n\nexport function emit<T = unknown>(obj: T, human?: Formatter<T>): void {\n if (human !== undefined && process.stdout.isTTY) {\n process.stdout.write(human(obj) + '\\n')\n return\n }\n process.stdout.write(JSON.stringify(obj, null, 2) + '\\n')\n}\n\nexport function fail(message: string, exitCode = 1): never {\n process.stderr.write(message + '\\n')\n process.exit(exitCode)\n}\n\nexport async function handleResponse(r: Response): Promise<unknown> {\n if (r.status >= 400) {\n let detail = await r.text()\n try {\n const parsed = JSON.parse(detail) as { detail?: string }\n if (parsed.detail !== undefined) detail = parsed.detail\n } catch {\n // body wasn't JSON; fall through with the raw text as detail\n }\n fail(`daemon error ${String(r.status)}: ${detail}`, 2)\n }\n if (r.status === 204) return {}\n const text = await r.text()\n if (text === '') return {}\n return JSON.parse(text) as unknown\n}\n\nexport function formatAge(epoch: number, now: number = Date.now() / 1000): string {\n const delta = Math.max(0, now - epoch)\n if (delta < 60) return `${String(Math.floor(delta))}s`\n if (delta < 3600) return `${String(Math.floor(delta / 60))}m`\n if (delta < 86400) return `${String(Math.floor(delta / 3600))}h`\n return `${String(Math.floor(delta / 86400))}d`\n}\n\nexport function formatTable(headers: string[], rows: (string | undefined)[][]): string {\n if (rows.length === 0) return headers.join(' ')\n const norm: string[][] = rows.map((row) => row.map((c) => c ?? ''))\n const widths = headers.map((h) => h.length)\n for (const row of norm) {\n for (let i = 0; i < row.length; i++) {\n widths[i] = Math.max(widths[i] ?? 0, row[i]?.length ?? 0)\n }\n }\n const pad = (s: string, w: number) => s + ' '.repeat(Math.max(0, w - s.length))\n const out: string[] = []\n out.push(\n headers\n .map((h, i) => pad(h, widths[i] ?? h.length))\n .join(' ')\n .replace(/\\s+$/, ''),\n )\n for (const row of norm) {\n out.push(\n row\n .map((c, i) => pad(c, widths[i] ?? c.length))\n .join(' ')\n .replace(/\\s+$/, ''),\n )\n }\n return out.join('\\n')\n}\n"],"mappings":";AAcA,SAAS,aAAa;AACtB,SAAS,YAAY,WAA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