mindwire 0.1.52 → 0.1.53

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
@@ -16,6 +16,11 @@ protocol; this package is a thin, dependency-free client over its REST + SSE sur
16
16
 
17
17
  ## Install
18
18
 
19
+ Connect saved bots to Slack, Microsoft Teams, Discord, or Telegram through
20
+ `mw.integrations`: chat with streamed replies, run commands, trigger tasks, or send notifications.
21
+ Connections are shared with the app and Go SDK. See the
22
+ [messaging integrations guide](https://mindwire.sh/docs/guides/integrations) for setup and examples.
23
+
19
24
  ```bash
20
25
  npm i mindwire
21
26
  # or: bun add mindwire / pnpm add mindwire
@@ -38,7 +43,7 @@ If macOS rejects the login, the CLI lets you retry the password or check Screen
38
43
  Sharing permissions. Canceling or entering a wrong password keeps the existing
39
44
  desktop setup and active connections unchanged.
40
45
  Opening a workspace or checking status does not enable screen access. See the
41
- [desktop contract](../../daemon/DESKTOP.md#personal-mac-desktop) for platform support,
46
+ [desktop contract](../../packages/daemon/DESKTOP.md#personal-mac-desktop) for platform support,
42
47
  permissions and the shared input protocol. Existing installations need a release
43
48
  advertising `health().localDesktopVersion >= 1`.
44
49
 
@@ -112,7 +117,7 @@ and native transcripts. Use `deleteChat()` for an explicit transcript purge.
112
117
 
113
118
  Check `health().workspaceMetadataVersion` before enabling registry features on an
114
119
  older daemon. `workspace.import()` imports legacy IDs once; existing records and
115
- deletion markers win. See the [registry contract](../../daemon/WORKSPACES.md) for
120
+ deletion markers win. See the [registry contract](../../packages/daemon/WORKSPACES.md) for
116
121
  migration and recovery. The embedded Go SDK exposes the same operations through
117
122
  `client.Workspace`, using the same SQLite implementation.
118
123
 
@@ -153,6 +158,93 @@ blocks running chats/overlapping projects and recovers removal across restarts.
153
158
  Cancellation returns 409 after the `deleting` phase; cleanup then affects only the
154
159
  owned quarantine, even if someone recreates the original directory.
155
160
 
161
+ Create a plain harness profile with `mw.bots.create({ agentId, projectId, name, raw: true })`
162
+ (Go: `Bot.Raw`). Requires `health().botsVersion >= 7`. It keeps a named conversation
163
+ group and the existing harness authentication, settings and native tools, without
164
+ Mindwire bot instructions, memory, knowledge, skills or bot MCP tools. `raw` is
165
+ creation-only; create a separate profile to change modes without carrying an old
166
+ persona into a resumed conversation.
167
+
168
+ With `botsVersion >= 8`, bots belong to a workspace and can work in any of its
169
+ projects. `projectId` is only their optional default working folder. Start a chat
170
+ in another project with `mw.bots.createChat(bot.id, { projectId })` (Go:
171
+ `Bots.CreateChat(bot.ID, chatID, title, projectID)`). The profile, memory and skills
172
+ stay shared; each chat retains its own project, native session and permissions.
173
+ Deleting a project clears a matching default folder while preserving the bot and
174
+ its conversations in other projects.
175
+
176
+ ### Bot skills
177
+
178
+ Bots keep standing identity in `instructions`, durable facts in `memory`, and
179
+ reference material in `knowledge`. Assign reusable workflows separately with
180
+ `skills`, an array containing complete portable `SKILL.md` documents:
181
+
182
+ ```ts
183
+ import { readFile } from "node:fs/promises";
184
+
185
+ await mw.bots.update(bot.id, {
186
+ expectedRevision: bot.revision,
187
+ skills: [await readFile("./skills/reports/SKILL.md", "utf8")],
188
+ });
189
+ ```
190
+
191
+ Requires `health().botsVersion >= 6`. The Go equivalent is `BotEdit.Skills`.
192
+ Each document needs YAML `name` and `description` frontmatter and a Markdown body.
193
+ Limits are 16 skills, 32 KiB each, 128 KiB total, with unique names. The portable
194
+ frontmatter supports `license`, `compatibility` and string-valued `metadata`;
195
+ native permission overrides, hooks and dynamic shell substitutions are rejected. Omit `skills` when updating
196
+ unrelated fields; an explicit empty array removes assignments.
197
+
198
+ The daemon supplies a private bundle for the current turn. Codex discovers it
199
+ through process-scoped extra roots; Claude loads it through `--plugin-dir`.
200
+ Other harnesses load the same content through `skills_list` / `skills_read` on
201
+ the existing scoped tool bridge. Older Codex versions without extra-root support
202
+ also use that fallback. Only skill metadata enters standing context; bodies are
203
+ read on demand. Assignments retain the turn's starting revision. Skills grant no
204
+ additional permissions and never alter global harness configuration. Product
205
+ presets and skill content belong to the client; the Go core supplies the generic
206
+ validation, storage, delivery and permission checks.
207
+
208
+ ### Applications and scheduled work
209
+
210
+ `mw.apps` saves application resources on their owning host. Clients can present
211
+ these as shortcuts, launchers or other application catalogs. Consumer bot presets
212
+ and General-mode UI are outside the Go registry; no new AI runtime is created.
213
+
214
+ ```ts
215
+ const { app } = await mw.apps.register({
216
+ projectId, name: "Reports", icon: "chart.bar", url: "http://127.0.0.1:3000",
217
+ startupCommand: "./scripts/ensure-reports.sh", healthPath: "/health",
218
+ });
219
+ await mw.apps.open(app.id); // bounded readiness check/startup; returns the saved URL
220
+ await mw.apps.channels(); // labels/IDs only, no provider credentials
221
+ await mw.apps.notifications(app.id); // protected credentialFile path on the computer
222
+ await mw.apps.saveSchedule(app.id, {
223
+ name: "Morning report", localTime: "09:00", timeZone: "Europe/London",
224
+ weekdays: [1, 2, 3, 4, 5], command: "./scripts/build-report.sh",
225
+ title: "Reports", body: "Your morning report is ready.",
226
+ });
227
+ const schedules = await mw.apps.schedules(app.id);
228
+ ```
229
+
230
+ Check `health().appsVersion >= 1`. Phone delivery must already be configured.
231
+ Schedules persist across restarts and run while the owning computer is awake;
232
+ notifications retry without rerunning a completed command. Backend credentials
233
+ can only send as one app through its saved destinations. See the
234
+ [Apps contract](../../docs/apple/Apps.md) for native tools, private forwarding,
235
+ calendar rules, removal and recovery. The Go SDK shares `client.Apps` for saved
236
+ records, readiness, notification delivery and schedules; backend credential files
237
+ are provisioned through the running daemon's HTTP/native tool service.
238
+
239
+ The standalone daemon explicitly owns scheduling. The embedded Go SDK does not
240
+ run scheduled commands merely because a client is constructed; opt in with
241
+ `mindwire.Options{RunScheduledJobs: true}` when hosting a long-lived runtime.
242
+ Native agent tools request owner approval before enabling background commands,
243
+ using the existing interaction stream. Direct owner API/SDK requests explicitly
244
+ authorize their work. Pausing remains available when notifications are muted or
245
+ unconfigured. Commands use the host OS permissions; the working directory does
246
+ not provide a sandbox.
247
+
156
248
  ## Targets — where the daemon runs
157
249
 
158
250
  **One `new Mindwire` = one instance = one daemon = one environment.** Every agent that instance runs
@@ -289,3 +381,6 @@ bun test # client + SSE parser tests (mocked fetch)
289
381
  ```
290
382
 
291
383
  License: Apache-2.0.
384
+
385
+
386
+ Public hosting adapters can check `health().appsVersion >= 2`, then call `mw.apps.preparePublication(appId)` (Go: `client.Apps.PreparePublication(ctx, appID)`). This validates a port or static build plan without deploying it. After the adapter confirms hosting, save its HTTPS link using `apps.update(..., { expectedRevision, publicUrl })`. The original private URL stays intact. Provider credentials and billing belong in the host application, outside the generic runtime.
package/dist/apps.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ import type { Mindwire } from "./client.js";
2
+ import type { WorkspaceSnapshot } from "./workspace.js";
3
+ /** An application resource saved on its owning host. */
4
+ export interface AppShortcut {
5
+ id: string;
6
+ workspaceId: string;
7
+ projectId: string;
8
+ botId?: string;
9
+ name: string;
10
+ icon?: string;
11
+ url: string;
12
+ startupCommand?: string;
13
+ healthPath?: string;
14
+ archived: boolean;
15
+ createdAt: string;
16
+ revision: number;
17
+ channelIds?: string[];
18
+ notificationsMuted: boolean;
19
+ automation?: boolean;
20
+ staticDirectory?: string;
21
+ publicUrl?: string;
22
+ }
23
+ export type AppShortcutCreate = Pick<AppShortcut, "projectId" | "name" | "url"> & Partial<Pick<AppShortcut, "id" | "botId" | "icon" | "startupCommand" | "healthPath" | "automation" | "channelIds" | "notificationsMuted" | "staticDirectory" | "publicUrl">>;
24
+ export type AppShortcutEdit = {
25
+ expectedRevision: number;
26
+ } & Partial<Pick<AppShortcut, "name" | "icon" | "url" | "startupCommand" | "healthPath" | "archived" | "channelIds" | "notificationsMuted" | "staticDirectory" | "publicUrl">>;
27
+ export interface AppShortcutMutation {
28
+ app: AppShortcut;
29
+ snapshot: WorkspaceSnapshot;
30
+ }
31
+ export interface AppPublication {
32
+ app: AppShortcut;
33
+ kind: "port" | "static";
34
+ port?: number;
35
+ directory?: string;
36
+ }
37
+ export interface AppNotificationChannel {
38
+ id: string;
39
+ name: string;
40
+ type: string;
41
+ }
42
+ export interface AppScheduleSpec {
43
+ id?: string;
44
+ expectedRevision?: number;
45
+ name: string;
46
+ runAt?: string;
47
+ intervalSeconds?: number;
48
+ localTime?: string;
49
+ timeZone?: string;
50
+ weekdays?: number[];
51
+ command?: string;
52
+ title?: string;
53
+ body?: string;
54
+ enabled?: boolean;
55
+ }
56
+ export interface AppSchedule extends Omit<AppScheduleSpec, "id"> {
57
+ id: string;
58
+ appId: string;
59
+ revision: number;
60
+ active: boolean;
61
+ state: string;
62
+ nextRunAt?: string;
63
+ retryAt?: string;
64
+ lastRunAt?: string;
65
+ lastError?: string;
66
+ attempts: number;
67
+ }
68
+ export declare class AppsApi {
69
+ private readonly mw;
70
+ constructor(mw: Mindwire);
71
+ list(): Promise<AppShortcut[]>;
72
+ get(id: string): Promise<AppShortcut>;
73
+ register(input: AppShortcutCreate): Promise<AppShortcutMutation>;
74
+ update(id: string, input: AppShortcutEdit): Promise<AppShortcutMutation>;
75
+ /** Ensures readiness on the owning computer; the client opens the returned URL. */
76
+ open(id: string): Promise<AppShortcut>;
77
+ /** Validates a plan for the owner's hosting adapter; does not deploy or charge. */
78
+ preparePublication(id: string): Promise<AppPublication>;
79
+ channels(): Promise<AppNotificationChannel[]>;
80
+ notifications(id: string, options?: {
81
+ channelIds?: string[];
82
+ rotate?: boolean;
83
+ }): Promise<AppShortcutMutation & {
84
+ credentialFile: string;
85
+ }>;
86
+ revokeNotificationAccess(id: string): Promise<{
87
+ revoked: boolean;
88
+ }>;
89
+ schedules(id: string): Promise<AppSchedule[]>;
90
+ saveSchedule(id: string, schedule: AppScheduleSpec): Promise<AppSchedule>;
91
+ deleteSchedule(id: string, scheduleId: string): Promise<{
92
+ removed: boolean;
93
+ }>;
94
+ }
package/dist/bots.d.ts ADDED
@@ -0,0 +1,168 @@
1
+ import type { Mindwire } from "./client.js";
2
+ import type { WorkspaceRecord, WorkspaceSnapshot, WorkspaceChat, WorkspaceAgent, WorkspaceProject } from "./workspace.js";
3
+ import type { Run } from "./types.js";
4
+ export interface BotKnowledge {
5
+ id: string;
6
+ title: string;
7
+ content: string;
8
+ }
9
+ export interface Bot extends WorkspaceRecord {
10
+ agentId: string;
11
+ /** Default folder for new chats. The bot belongs to workspaceId and can work in its other projects. */
12
+ projectId: string;
13
+ name: string;
14
+ /** Saved palette-character ID; omitted/empty keeps the automatic avatar. */
15
+ icon?: string;
16
+ purpose: string;
17
+ instructions: string;
18
+ memory: string;
19
+ knowledge: BotKnowledge[];
20
+ /** Portable SKILL.md documents, loaded on demand. Requires botsVersion >= 6. */
21
+ skills?: string[] | null;
22
+ /** Creation-only plain harness: no Mindwire bot context, tools or skills. Requires botsVersion >= 7. */
23
+ raw?: boolean;
24
+ isMaster: boolean;
25
+ archived: boolean;
26
+ /** Applies to this bot's current and future chats, independent of its base engine. */
27
+ notificationsMuted?: boolean;
28
+ }
29
+ export interface BotInput {
30
+ icon?: string;
31
+ id?: string;
32
+ agentId: string;
33
+ projectId?: string;
34
+ name: string;
35
+ purpose?: string;
36
+ instructions?: string;
37
+ memory?: string;
38
+ knowledge?: BotKnowledge[];
39
+ skills?: string[];
40
+ /** Keep native harness behavior. Cannot be changed after creation or combined with bot context. */
41
+ raw?: boolean;
42
+ }
43
+ export interface BotEdit {
44
+ /** Base agent for future chats; existing chats retain their original engine. Requires botsVersion >= 5. */
45
+ agentId?: string;
46
+ icon?: string;
47
+ expectedRevision: number;
48
+ name?: string;
49
+ purpose?: string;
50
+ instructions?: string;
51
+ memory?: string;
52
+ knowledge?: BotKnowledge[];
53
+ archived?: boolean;
54
+ /** Replaces assigned SKILL.md documents; omit to preserve existing skills. */
55
+ skills?: string[];
56
+ notificationsMuted?: boolean;
57
+ }
58
+ export interface BotMutation {
59
+ bot: Bot;
60
+ snapshot: WorkspaceSnapshot;
61
+ }
62
+ export interface BotTaskInput {
63
+ requestId: string;
64
+ message: string;
65
+ }
66
+ export interface BotTaskRequest extends BotTaskInput {
67
+ chatId?: string;
68
+ title?: string;
69
+ projectId?: string;
70
+ }
71
+ export interface BotTask {
72
+ botId: string;
73
+ chatId: string;
74
+ run: Run;
75
+ messages?: {
76
+ role: string;
77
+ text: string;
78
+ createdAt: string;
79
+ }[];
80
+ output?: string;
81
+ historyError?: string;
82
+ interactions?: {
83
+ id: string;
84
+ kind: string;
85
+ title?: string;
86
+ detail?: string;
87
+ needsResponse: boolean;
88
+ }[];
89
+ tools?: {
90
+ name: string;
91
+ status?: string;
92
+ }[];
93
+ cancelRequested?: boolean;
94
+ }
95
+ export type BotPeerRoute = {
96
+ kind: "ssh";
97
+ host: string;
98
+ port: number;
99
+ } | {
100
+ kind: "websocket";
101
+ url: string;
102
+ };
103
+ export interface BotPeerIdentity {
104
+ workspaceId: string;
105
+ publicKey: string;
106
+ hostKeyFingerprint: string;
107
+ port?: number;
108
+ sshPort?: number;
109
+ routes?: BotPeerRoute[];
110
+ }
111
+ export interface BotPeerInput {
112
+ name: string;
113
+ publicKey: string;
114
+ hostKeyFingerprint: string;
115
+ routes: BotPeerRoute[];
116
+ enabled?: boolean;
117
+ }
118
+ export interface BotPeer extends BotPeerInput {
119
+ workspaceId: string;
120
+ }
121
+ export interface BotPeerCheck {
122
+ workspaceId: string;
123
+ reachable: boolean;
124
+ error?: string;
125
+ addressRecovery?: boolean;
126
+ }
127
+ /** Saved bot identities, native tasks, and explicitly paired bot-control peers. */
128
+ export declare class BotsApi {
129
+ private readonly mw;
130
+ constructor(mw: Mindwire);
131
+ list(options?: {
132
+ projectId?: string;
133
+ archived?: boolean;
134
+ }): Promise<Bot[]>;
135
+ get(id: string): Promise<Bot>;
136
+ ensure(agentId: string, projectId: string): Promise<BotMutation>;
137
+ create(input: BotInput): Promise<BotMutation>;
138
+ update(id: string, edit: BotEdit): Promise<BotMutation>;
139
+ chats(id: string): Promise<WorkspaceChat[]>;
140
+ createChat(id: string, input?: {
141
+ chatId?: string;
142
+ title?: string;
143
+ projectId?: string;
144
+ }): Promise<{
145
+ chatId: string;
146
+ snapshot: WorkspaceSnapshot;
147
+ }>;
148
+ agents(): Promise<{
149
+ agents: WorkspaceAgent[];
150
+ projects: WorkspaceProject[];
151
+ }>;
152
+ tasks(id: string): Promise<BotTask[]>;
153
+ /** Keep requestId stable when retrying a task after a lost acknowledgement. */
154
+ delegate(id: string, input: BotTaskRequest): Promise<BotTask>;
155
+ task(id: string, runId: string): Promise<BotTask>;
156
+ input(id: string, runId: string, input: BotTaskInput): Promise<BotTask>;
157
+ cancel(id: string, runId: string): Promise<BotTask>;
158
+ peerIdentity(): Promise<BotPeerIdentity>;
159
+ startPeerListener(port?: number): Promise<BotPeerIdentity>;
160
+ peers(): Promise<BotPeer[]>;
161
+ pair(workspaceId: string, input: BotPeerInput): Promise<BotPeer>;
162
+ revokePeer(workspaceId: string): Promise<{
163
+ ok: boolean;
164
+ }>;
165
+ /** Bounded peer handshake/discovery; does not start a bot task. */
166
+ checkPeer(workspaceId: string): Promise<BotPeerCheck>;
167
+ private taskPath;
168
+ }
@@ -1,4 +1,4 @@
1
- import { websocketURL, readJSON, writeJSON, acquireProcessLock, computerClient, versionAtLeast } from './chunk-4XL565EU.js';
1
+ import { websocketURL, readJSON, writeJSON, acquireProcessLock, computerClient, versionAtLeast } from './chunk-O5DWL7MH.js';
2
2
  import { join } from 'path';
3
3
  import { setTimeout } from 'timers/promises';
4
4
 
@@ -10,12 +10,6 @@ function connectionInfo(relay, host) {
10
10
  if (relay.kind === "none") return { provider: "direct", address: host ? "persistent" : "network" };
11
11
  return { provider: relay.kind, address: ["cloudflare", "ngrok"].includes(relay.kind) && !relay.url ? "temporary" : "persistent" };
12
12
  }
13
- function connectionDescription(info) {
14
- const name = { oblien: "Oblien", cloudflare: "Cloudflare", ngrok: "ngrok", custom: "Your tunnel", direct: "Direct SSH / VPN" }[info.provider];
15
- if (info.address === "temporary") return `${name} \xB7 temporary address. For reconnect after a restart, run mindwire connection to choose a persistent address.`;
16
- if (info.address === "network") return `${name} \xB7 reachable network required. Use a VPN hostname for access across networks.`;
17
- return `${name} \xB7 persistent address. Saved phones retry automatically when this computer is online.`;
18
- }
19
13
 
20
14
  // src/computer/directory-http.ts
21
15
  var DirectoryRequestError = class extends Error {
@@ -301,6 +295,6 @@ function updateProgress(update) {
301
295
  return `${update.version} \xB7 ${phase[update.status]}`;
302
296
  }
303
297
 
304
- export { activeUpdate, connectionAddress, connectionDescription, connectionInfo, disableAddressDiscovery, discoveryDescription, discoveryPreference, enableAddressDiscovery, queueServiceUpdate, reconcileAddressDiscovery, saveDiscoveryPreference, updateComputer, updateProgress };
305
- //# sourceMappingURL=chunk-RTMQJIKW.js.map
306
- //# sourceMappingURL=chunk-RTMQJIKW.js.map
298
+ export { activeUpdate, connectionAddress, connectionInfo, disableAddressDiscovery, discoveryDescription, discoveryPreference, enableAddressDiscovery, queueServiceUpdate, reconcileAddressDiscovery, saveDiscoveryPreference, updateComputer, updateProgress };
299
+ //# sourceMappingURL=chunk-MZ4OTZFH.js.map
300
+ //# sourceMappingURL=chunk-MZ4OTZFH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/computer/provider-info.ts","../src/computer/directory-http.ts","../src/computer/discovery.ts","../src/computer/service-update.ts"],"names":["delay","join"],"mappings":";;;;;AAKO,SAAS,iBAAA,CAAkB,OAAqB,IAAA,EAAuB;AAC5E,EAAA,OAAO,KAAA,CAAM,IAAA,KAAS,MAAA,GAAS,CAAA,IAAA,EAAO,QAAQ,SAAS,CAAA,CAAA,GACnD,KAAA,CAAM,GAAA,GAAM,aAAa,KAAA,CAAM,GAAG,CAAA,GAAI,CAAA,UAAA,EAAa,MAAM,IAAI,CAAA,CAAA;AACnE;AAGO,SAAS,cAAA,CAAe,OAAqB,IAAA,EAAuC;AACzF,EAAA,IAAI,KAAA,CAAM,IAAA,KAAS,MAAA,EAAQ,OAAO,EAAE,UAAU,QAAA,EAAU,OAAA,EAAS,IAAA,GAAO,YAAA,GAAe,SAAA,EAAU;AACjG,EAAA,OAAO,EA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EAAY,0BAAA;AAAA,IAC1D,QAAA,EAAU,WAAA;AAAA,IAAa,MAAA,EAAQ;AAAA,GACjC;AACA,EAAA,OAAO,GAAG,MAAA,CAAO,OAAO,SAAM,KAAA,CAAM,MAAA,CAAO,MAAM,CAAC,CAAA,CAAA;AACpD","file":"chunk-MZ4OTZFH.js","sourcesContent":["import type { ComputerConnectionInfo } from \"../computer.js\";\nimport type { RelayOptions } from \"./relay.js\";\nimport { websocketURL } from \"./relay.js\";\n\n/** Credential renewal does not change the address already saved by the phone. */\nexport function connectionAddress(relay: RelayOptions, host?: string): string {\n return relay.kind === \"none\" ? `ssh:${host ?? \"network\"}`\n : relay.url ? websocketURL(relay.url) : `temporary:${relay.kind}`;\n}\n\n/** Public, non-secret metadata. Route/SSH identity is independent of provider credentials. */\nexport function connectionInfo(relay: RelayOptions, host?: string): ComputerConnectionInfo {\n if (relay.kind === \"none\") return { provider: \"direct\", address: host ? \"persistent\" : \"network\" };\n return { provider: relay.kind, address: [\"cloudflare\", \"ngrok\"].includes(relay.kind) && !relay.url ? \"temporary\" : \"persistent\" };\n}\n\nexport function connectionDescription(info: ComputerConnectionInfo): string {\n const name = { oblien: \"Oblien\", cloudflare: \"Cloudflare\", ngrok: \"ngrok\", custom: \"Your tunnel\", direct: \"Direct SSH / VPN\" }[info.provider];\n if (info.address === \"temporary\") return `${name} · temporary address. For reconnect after a restart, run mindwire connection to choose a persistent address.`;\n if (info.address === \"network\") return `${name} · reachable network required. Use a VPN hostname for access across networks.`;\n return `${name} · persistent address. Saved phones retry automatically when this computer is online.`;\n}\n","export class DirectoryRequestError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n readonly retryAfter = 0,\n ) {\n super(\n status === 0\n ? \"Couldn't reach the address directory securely. Check its HTTPS address and retry.\"\n : `The address directory rejected the request (${code}).`,\n );\n }\n}\n\n/** Bounded, same-origin requests. No redirects, cookie jar or retained credentials. */\nexport async function directoryRequest<T>(url: string, path: string, body: unknown, signal?: AbortSignal): Promise<T> {\n let response: Response;\n try {\n response = await fetch(url + path, {\n method: \"POST\",\n redirect: \"error\",\n signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(10_000)]) : AbortSignal.timeout(10_000),\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n },\n body: JSON.stringify(body),\n });\n } catch {\n signal?.throwIfAborted();\n throw new DirectoryRequestError(0, \"unreachable\");\n }\n const reader = response.body?.getReader();\n const chunks: Uint8Array[] = [];\n let length = 0;\n try {\n if (reader)\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.byteLength;\n if (length > 64 * 1024) throw new Error(\"The address directory returned an oversized response.\");\n chunks.push(value);\n }\n } finally {\n void reader?.cancel().catch(() => {});\n }\n let data: unknown;\n try {\n data = JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n } catch {\n throw new DirectoryRequestError(response.status, \"invalid_response\");\n }\n if (!response.ok) {\n const error = (data as { error?: unknown } | null)?.error;\n const code = typeof error === \"string\" ? error : (error as { code?: unknown } | null)?.code;\n const retryAfter = Number(response.headers.get(\"Retry-After\"));\n throw new DirectoryRequestError(\n response.status,\n typeof code === \"string\" && /^[a-z_]{1,64}$/.test(code) ? code : \"directory_error\",\n Number.isFinite(retryAfter) ? Math.max(0, Math.min(60, retryAfter)) : 0,\n );\n }\n return data as T;\n}\n","import { join } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { Mindwire } from \"../client.js\";\nimport type { ComputerDiscoveryStatus } from \"../computer.js\";\nimport { acquireProcessLock } from \"./lock.js\";\nimport type { SetupPrompt } from \"./setup-prompt.js\";\nimport { directoryRequest, DirectoryRequestError } from \"./directory-http.js\";\nimport { readJSON, writeJSON, type ComputerConfig } from \"./lifecycle.js\";\n\nexport const DIRECTORY_API_PATH = \"/api/computer-directory/v1\";\nexport const DIRECTORY_URL = `https://console.mindwire.sh${DIRECTORY_API_PATH}`;\n\nexport interface DiscoveryPreference { enabled: boolean; url?: string }\nexport const discoveryPreference = (directory: string) =>\n readJSON<DiscoveryPreference>(join(directory, \"computer-discovery-preference.json\"));\n\n/** Desired setup is durable even if enrollment is temporarily offline. The\n * daemon remains the authority for signed publications and phone access. */\nexport async function saveDiscoveryPreference(directory: string, value: DiscoveryPreference): Promise<void> {\n const preference = { ...value, url: value.url ? directoryURL(value.url) : undefined };\n await writeJSON(join(directory, \"computer-discovery-preference.json\"), preference);\n}\n\nexport function directoryURL(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(\"Enter the directory's HTTPS API URL.\");\n }\n if (\n value.length > 2048 ||\n /[\\s\\x00]/.test(value) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash ||\n (url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)))\n ) {\n throw new Error(\"Use an HTTPS directory URL without credentials, a query, or a fragment.\");\n }\n if (url.pathname === \"/\") url.pathname = DIRECTORY_API_PATH;\n if (url.pathname.endsWith(\"/\") || url.pathname.includes(\"//\") || url.pathname.includes(\"%\")) {\n throw new Error(\"Use the exact directory API URL without a trailing slash.\");\n }\n return url.href;\n}\n\nexport async function enableAddressDiscovery(options: {\n directory: string;\n computer: Mindwire;\n prompt: SetupPrompt;\n url?: string;\n waitForPublication?: boolean;\n signal?: AbortSignal;\n reconcile?: boolean;\n}): Promise<ComputerDiscoveryStatus> {\n const lock = await acquireProcessLock(join(options.directory, \"discovery-setup.lock\"), { signal: options.signal });\n try {\n let status: ComputerDiscoveryStatus;\n try {\n status = await options.computer.computer.discovery();\n } catch (error) {\n if ((error as { status?: number }).status === 404)\n throw new Error(\"Update the Mindwire service before enabling automatic address recovery.\");\n throw error;\n }\n const preference = await discoveryPreference(options.directory);\n if (options.reconcile && preference?.enabled === false) return status;\n // Preserve a saved private directory across upgrades. Credentials belonging\n // to another provider are never read by this flow.\n const url = directoryURL(\n options.url ?? process.env.MINDWIRE_DIRECTORY_URL ?? status.url ?? preference?.url ?? DIRECTORY_URL,\n );\n if (\n status.url &&\n status.url !== url &&\n (status.enabled || (status.sequence ?? 0) !== (status.publishedSequence ?? 0))\n ) {\n throw new Error(\n \"Disable the current directory with mindwire discovery disable and wait for its withdrawal before changing the directory URL.\",\n );\n }\n await saveDiscoveryPreference(options.directory, { enabled: true, url });\n if (!status.enabled || status.url !== url || status.error?.includes(\"enrollment\")) {\n options.prompt.print(`Enabling encrypted address recovery with ${new URL(url).host}…`);\n try {\n const challenge = await directoryRequest<{ challenge: string }>(url, \"/registrations/challenge\", {\n directoryId: status.directoryId,\n }, options.signal);\n if (\n typeof challenge?.challenge !== \"string\" ||\n challenge.challenge.length < 16 ||\n challenge.challenge.length > 2048\n ) {\n throw new Error(\"The address directory returned an invalid enrollment challenge.\");\n }\n const proof = await options.computer.computer.directoryEnrollment(url, challenge.challenge);\n const enrolled = await directoryRequest<{ directoryId: string }>(url, \"/registrations\", proof, options.signal);\n if (enrolled?.directoryId !== status.directoryId)\n throw new Error(\"The directory acknowledged a different computer.\");\n } catch (error) {\n if (error instanceof DirectoryRequestError) {\n if (error.status === 404 || error.status === 501)\n throw new Error(\n \"The address directory isn't available at this URL. Your existing connection still works; retry after the backend is deployed.\",\n );\n if (error.status === 409)\n throw new Error(\n \"This computer's directory registration is revoked or conflicts with its saved identity. Contact the directory operator.\",\n );\n if (error.code === \"account_required\")\n throw new Error(\n \"This directory still requires an account. Update its Mindwire backend to enable key-based registration, or choose another directory with --directory-url.\",\n );\n if (error.status === 401 || error.status === 403)\n throw new Error(\n \"The directory couldn't verify this computer's key or challenge. Retry enrollment.\",\n );\n if (error.status === 429)\n throw new Error(\n \"The directory's registration limit was reached. Retry later or use another directory.\",\n );\n if (error.status === 503)\n throw new Error(\n \"The directory is temporarily unavailable or at capacity. Your existing connection still works.\",\n );\n }\n throw error;\n }\n status = await options.computer.computer.configureDiscovery(true, url);\n }\n if (options.waitForPublication === false) return status;\n const deadline = Date.now() + 15_000;\n while (Date.now() < deadline) {\n status = await options.computer.computer.discovery();\n if (status.enabled && status.sequence && status.publishedSequence === status.sequence) return status;\n if (status.error?.includes(\"enrollment\") || status.error?.includes(\"older revision\"))\n throw new Error(status.error);\n await delay(250, undefined, { signal: options.signal });\n }\n throw new Error(\n \"Address recovery is configured and will retry in the background. Run mindwire discovery status to check publication.\",\n );\n } finally {\n await lock?.close();\n }\n}\n\nexport async function disableAddressDiscovery(directory: string, computer: Mindwire, reconcile = false): Promise<ComputerDiscoveryStatus> {\n const lock = await acquireProcessLock(join(directory, \"discovery-setup.lock\"));\n try {\n const status = await computer.computer.discovery();\n const preference = await discoveryPreference(directory);\n if (reconcile && preference?.enabled === true) return status;\n await saveDiscoveryPreference(directory, { enabled: false, url: status.url ?? preference?.url });\n if (!status.enabled) return status;\n return await computer.computer.configureDiscovery(false);\n } finally { await lock?.close(); }\n}\n\n/** Runs once after startup and retries failed enrollment in the controller. A\n * healthy setup makes only a local status read: publication/renewal stays in Go.\n * Direct/VPN/custom connections never opt into a hosted directory implicitly. */\nexport async function reconcileAddressDiscovery(options: {\n directory: string; config: ComputerConfig; computer: Mindwire; signal?: AbortSignal;\n}): Promise<void> {\n const preference = await discoveryPreference(options.directory);\n const { discovery: status } = await options.computer.computer.info();\n const automatic = options.config.relay.kind === \"cloudflare\" && !options.config.relay.url;\n const enabled = preference?.enabled ?? (status?.enabled || automatic && !status?.url);\n if (!enabled) {\n if (preference?.enabled === false && status?.enabled) await disableAddressDiscovery(options.directory, options.computer, true);\n return;\n }\n if (!status) throw new Error(\"Update the Mindwire service to enable automatic reconnection.\");\n const url = directoryURL(preference?.url ?? process.env.MINDWIRE_DIRECTORY_URL ?? status.url ?? DIRECTORY_URL);\n if (status.enabled && status.url === url && !status.error?.includes(\"enrollment\")) return;\n await enableAddressDiscovery({ ...options, url, waitForPublication: false, reconcile: true,\n prompt: { print() {}, open() {}, question: async () => { throw new Error(\"Unexpected interactive setup.\"); },\n secret: async () => { throw new Error(\"Unexpected interactive setup.\"); } } });\n}\n\nexport function discoveryDescription(status: ComputerDiscoveryStatus | undefined): string {\n if (!status?.enabled) return \"Automatic address recovery is off. Enable it with mindwire discovery enable.\";\n if (status.error) return status.error;\n return status.sequence && status.publishedSequence === status.sequence\n ? \"Encrypted address recovery is on. Saved phones can find this computer when its tunnel address changes.\"\n : \"Publishing the computer's encrypted address…\";\n}\n","import { join } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { ComputerUpdate } from \"../computer.js\";\nimport type { Mindwire } from \"../client.js\";\nimport { computerClient, readJSON } from \"./lifecycle.js\";\nimport { versionAtLeast } from \"../version.js\";\n\ntype UpdateClient = Pick<Mindwire, \"health\" | \"computer\">;\nexport function activeUpdate(update: ComputerUpdate | undefined): update is ComputerUpdate {\n return !!update && [\"queued\", \"downloading\", \"waiting\", \"restarting\"].includes(update.status);\n}\n\n/** The daemon arbitrates requests. Join an earlier version before requesting the\n * next; promoting a request never creates a second download or bypasses its lease. */\nexport async function queueServiceUpdate(client: UpdateClient, version: string, force = false): Promise<ComputerUpdate> {\n for (let attempt = 0; ; attempt++) {\n const previous = await client.computer.updateStatus();\n if (activeUpdate(previous) && (!force || previous.force)) return previous;\n try {\n return await client.computer.requestUpdate(activeUpdate(previous) ? previous.version : version, { force });\n } catch (error) {\n if ((error as { status?: number }).status !== 409 || attempt >= 2) throw error;\n // Another caller won admission. Read the authoritative request and join it.\n }\n }\n}\n\nexport interface ServiceUpdateResult { version: string; complete: boolean; update?: ComputerUpdate }\n\n/** A CLI may close after queuing: the controller owns download/restart. Human\n * callers get a bounded result, including the exact older request being joined. */\nexport async function updateComputer(options: {\n directory: string; version: string; force?: boolean; allowDowngrade?: boolean;\n onProgress?: (update: ComputerUpdate) => void; signal?: AbortSignal; timeoutMs?: number;\n connect?: () => Promise<UpdateClient>;\n}):\nPromise<ServiceUpdateResult> {\n const version = options.version.replace(/^v/, \"\");\n if (!/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error(\"Enter a Mindwire release version, such as 0.1.38.\");\n const connect = options.connect ?? (() => computerClient(options.directory));\n const deadline = Date.now() + (options.timeoutMs ?? 120_000);\n let requested: ComputerUpdate | undefined, last = \"\";\n for (;;) {\n options.signal?.throwIfAborted();\n if (!requested) {\n const client = await connect();\n const installed = (await client.health()).version.replace(/^v/, \"\");\n if (installed === version || !options.allowDowngrade && versionAtLeast(installed, version))\n return { version: installed, complete: true };\n requested = await queueServiceUpdate(client, version, options.force);\n }\n // Progress survives the short API outage during restart. Only the daemon\n // accepts new requests; this read never changes or clears its status.\n const update = await readJSON<ComputerUpdate>(join(options.directory, \"computer-update.json\")) ?? requested;\n if (update.id !== requested.id) {\n // A concurrent update completed/advanced first. Recheck the live service.\n requested = undefined;\n } else {\n const key = `${update.id}:${update.status}`;\n if (last !== key) { last = key; options.onProgress?.(update); }\n if (update.status === \"failed\") throw new Error(update.error ?? \"The service update failed. Run mindwire inspect for details.\");\n if (update.status === \"complete\") {\n requested = undefined;\n if (Date.now() < deadline) continue;\n } else if (!options.force && update.status === \"waiting\") {\n return { version, complete: false, update };\n }\n }\n if (Date.now() >= deadline) return { version, complete: false, update };\n await delay(500, undefined, { signal: options.signal });\n }\n}\n\nexport function updateProgress(update: ComputerUpdate): string {\n const phase: Record<ComputerUpdate[\"status\"], string> = {\n idle: \"Ready\", queued: \"Queued\", downloading: \"Downloading verified release…\",\n waiting: \"Waiting for active work to finish\", restarting: \"Restarting service…\",\n complete: \"Installed\", failed: \"Update failed\",\n };\n return `${update.version} · ${phase[update.status]}`;\n}\n"]}