my-durable 0.0.36 → 0.0.38
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 +1 -0
- package/apps/dpi-backend/src/doctor.ts +426 -0
- package/apps/dpi-backend/src/routes.ts +7 -0
- package/apps/dpi-backend/src/store.ts +121 -0
- package/apps/dpi-backend/src/vitals.ts +94 -0
- package/apps/dpi-backend/src/zip.ts +117 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-D4M8tCcs.js +81 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-BxJGBCW9.css → index-xOvj8ub1.css} +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +12 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Composer.vue +74 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/HostPanel.vue +224 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +74 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +184 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NewSessionDialog.vue +41 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TopBar.vue +68 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +17 -1
- package/apps/dpi-sdk/src/api.ts +41 -0
- package/apps/dpi-sdk/src/client.ts +17 -0
- package/apps/dpi-sdk/src/protocol/rest-routes.ts +3 -0
- package/bin/dpi.mjs +11 -0
- package/docs/host-project-checklist.md +214 -0
- package/package.json +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DKJspajj.js +0 -81
package/README.md
CHANGED
|
@@ -22,6 +22,7 @@ dpi device install # OS service: systemd --user + linger (Linux) · LaunchA
|
|
|
22
22
|
# run `dpi device start` after login
|
|
23
23
|
dpi device uninstall
|
|
24
24
|
dpi tui # terminal admin client
|
|
25
|
+
dpi doctor # one-shot health check (node, healthz, start dirs, model probe, hub); exit 1 on a failed check
|
|
25
26
|
dpi --help # commands, flags and environment variables
|
|
26
27
|
dpi update --check # is a newer published version available?
|
|
27
28
|
dpi update # install it (npm i -g my-durable@latest)
|
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dpi doctor` — one-shot health check for THIS machine's device.
|
|
3
|
+
*
|
|
4
|
+
* Five checks, each printed as ok / warn / fail / skip with a one-line detail:
|
|
5
|
+
*
|
|
6
|
+
* 1. node — the one hard block in the project (>= 22.19.0, the
|
|
7
|
+
* engines floor; the comparison is `satisfiesEngine` from
|
|
8
|
+
* bin/update.mjs so both surfaces cannot drift).
|
|
9
|
+
* 2. healthz — is the device daemon actually answering on its port.
|
|
10
|
+
* 3. start_dirs — every configured start dir must exist and be writable;
|
|
11
|
+
* a device whose sessions cannot write is a broken device.
|
|
12
|
+
* 4. model probe — the local-only `/v1/device/probe-model` route. A dead
|
|
13
|
+
* provider is a WARN, never a fail: the UI rotates past
|
|
14
|
+
* dead providers, and doctor is not a provider pager.
|
|
15
|
+
* 5. hub — the paired/configured hub's /healthz, only when this
|
|
16
|
+
* device has a hub at all (otherwise `skip`).
|
|
17
|
+
*
|
|
18
|
+
* Exit code: 1 when any check FAILED, 0 otherwise (warnings included).
|
|
19
|
+
* Everything is injectable (env, fetch, fs, node version) so the unit tests run
|
|
20
|
+
* against fakes and never touch the network or the real filesystem.
|
|
21
|
+
*/
|
|
22
|
+
import { accessSync, constants as fsConstants, existsSync, readFileSync } from "node:fs";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { join, resolve } from "node:path";
|
|
25
|
+
// Reuse the updater's engine comparison instead of a second semver implementation.
|
|
26
|
+
import { satisfiesEngine } from "../../../bin/update.mjs";
|
|
27
|
+
|
|
28
|
+
export type DoctorStatus = "ok" | "warn" | "fail" | "skip";
|
|
29
|
+
|
|
30
|
+
export interface DoctorCheck {
|
|
31
|
+
id: string;
|
|
32
|
+
label: string;
|
|
33
|
+
status: DoctorStatus;
|
|
34
|
+
/** One line, already human shaped — the printer adds nothing but the marker. */
|
|
35
|
+
detail: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface DoctorReport {
|
|
39
|
+
checks: DoctorCheck[];
|
|
40
|
+
/** False when at least one check FAILED (warnings do not fail a report). */
|
|
41
|
+
ok: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The floor from package.json `engines` — declared here so a test can lower it. */
|
|
45
|
+
export const REQUIRED_NODE = ">=22.19.0";
|
|
46
|
+
|
|
47
|
+
/** The check ids in report order — stable for machine consumers.
|
|
48
|
+
* (start dirs carry an index suffix when more than one is configured.) */
|
|
49
|
+
export const DOCTOR_HEALTH_IDS = ["node", "healthz", "start_dir", "model_probe", "hub"] as const;
|
|
50
|
+
|
|
51
|
+
/** Narrow fetch surface: fakes stay three lines, no Response mock needed. */
|
|
52
|
+
export interface HttpResponse {
|
|
53
|
+
ok: boolean;
|
|
54
|
+
status: number;
|
|
55
|
+
json(): Promise<unknown>;
|
|
56
|
+
}
|
|
57
|
+
export type FetchLike = (
|
|
58
|
+
url: string,
|
|
59
|
+
init?: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal },
|
|
60
|
+
) => Promise<HttpResponse>;
|
|
61
|
+
|
|
62
|
+
export interface DoctorIo {
|
|
63
|
+
env: Record<string, string | undefined>;
|
|
64
|
+
nodeVersion: string;
|
|
65
|
+
fetchImpl: FetchLike;
|
|
66
|
+
/** fs.accessSync-shaped: throws when the path is missing or not writable. */
|
|
67
|
+
access: (path: string, mode?: number) => void;
|
|
68
|
+
exists: (path: string) => boolean;
|
|
69
|
+
readFile: (path: string) => string;
|
|
70
|
+
homedir: () => string;
|
|
71
|
+
/** healthz timeout. */
|
|
72
|
+
timeoutMs: number;
|
|
73
|
+
/** The hub may be across an ocean and behind TLS — a loopback-sized timeout would lie. */
|
|
74
|
+
hubTimeoutMs: number;
|
|
75
|
+
/** probe-model timeout: it runs one throwaway turn, so it is not a health ping. */
|
|
76
|
+
probeTimeoutMs: number;
|
|
77
|
+
requiredNode: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const realFetch: FetchLike = async (url, init) => fetch(url, init as RequestInit);
|
|
81
|
+
|
|
82
|
+
export const defaultDoctorIo = (): DoctorIo => ({
|
|
83
|
+
env: process.env,
|
|
84
|
+
nodeVersion: process.versions.node,
|
|
85
|
+
fetchImpl: realFetch,
|
|
86
|
+
access: (path, mode) => accessSync(path, mode),
|
|
87
|
+
exists: existsSync,
|
|
88
|
+
readFile: (path) => readFileSync(path, "utf8"),
|
|
89
|
+
homedir,
|
|
90
|
+
timeoutMs: 3_000,
|
|
91
|
+
/** The hub may be across an ocean, behind TLS and a cold proxy — 8s keeps the
|
|
92
|
+
* check honest without turning flaky latency into daily warnings. */
|
|
93
|
+
hubTimeoutMs: 8_000,
|
|
94
|
+
probeTimeoutMs: 60_000,
|
|
95
|
+
requiredNode: REQUIRED_NODE,
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// --------------------------------------------------------------- config bits
|
|
99
|
+
|
|
100
|
+
/** `~` / `~/x` expansion — same rule as config.ts and daemon.ts. */
|
|
101
|
+
export const expand = (p: string, hd: string = homedir()): string =>
|
|
102
|
+
p === "~" ? hd : p.startsWith("~/") ? join(hd, p.slice(2)) : p;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The start dirs exactly as `config.ts` sees them: ":"-separated, expanded and
|
|
106
|
+
* resolved. Doctor must report the dirs the DEVICE uses, so the rule is copied
|
|
107
|
+
* rather than invented (a comma is not a separator for the device either).
|
|
108
|
+
*/
|
|
109
|
+
export const parseStartDirs = (raw: string, hd: string = homedir()): string[] =>
|
|
110
|
+
raw
|
|
111
|
+
.split(":")
|
|
112
|
+
.filter(Boolean)
|
|
113
|
+
.map((p) => resolve(expand(p, hd)));
|
|
114
|
+
|
|
115
|
+
/** KEY=VALUE lines of backend.env (the daemon's own file, no shell quoting). */
|
|
116
|
+
export function readEnvFile(text: string): Record<string, string> {
|
|
117
|
+
const out: Record<string, string> = {};
|
|
118
|
+
for (const line of text.split(/\r?\n/)) {
|
|
119
|
+
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
|
|
120
|
+
if (!m) continue;
|
|
121
|
+
out[m[1]] = m[2].trim().replace(/^(['"])(.*)\1$/, "$2");
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** "provider/modelId" → the two halves probe-model wants. OpenRouter ids carry their own slash. */
|
|
127
|
+
export function splitModel(
|
|
128
|
+
defaultModel: string,
|
|
129
|
+
models?: ReadonlyArray<{ provider: string; id: string }>,
|
|
130
|
+
): { provider: string; modelId: string } | undefined {
|
|
131
|
+
const exact = models?.find((m) => `${m.provider}/${m.id}` === defaultModel);
|
|
132
|
+
if (exact) return { provider: exact.provider, modelId: exact.id };
|
|
133
|
+
const i = defaultModel.indexOf("/");
|
|
134
|
+
if (i <= 0 || i === defaultModel.length - 1) return undefined;
|
|
135
|
+
return { provider: defaultModel.slice(0, i), modelId: defaultModel.slice(i + 1) };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Why a request failed, in words an operator can act on. */
|
|
139
|
+
export function describeError(error: unknown, ms: number): string {
|
|
140
|
+
const e = error as { name?: string; message?: string; cause?: { code?: string; message?: string } };
|
|
141
|
+
const cause = e?.cause?.code ?? e?.cause?.message;
|
|
142
|
+
if (e?.name === "TimeoutError" || e?.name === "AbortError") return `timed out after ${ms}ms`;
|
|
143
|
+
const message = e?.message ?? String(error);
|
|
144
|
+
if (!cause || message.includes(cause)) return message;
|
|
145
|
+
return `${message} (${cause})`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ------------------------------------------------------------------- checks
|
|
149
|
+
|
|
150
|
+
interface Merged {
|
|
151
|
+
/** process env wins over the env file, like loadConfig's `process.loadEnvFile`. */
|
|
152
|
+
env: Record<string, string | undefined>;
|
|
153
|
+
home: string;
|
|
154
|
+
envFile: string;
|
|
155
|
+
token: string;
|
|
156
|
+
baseUrl: string;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function mergedConfig(io: DoctorIo): Merged {
|
|
160
|
+
const hd = io.homedir();
|
|
161
|
+
// `||` not `??`: an empty DPI_HOME/DPI_ENV_FILE means "unset", never the cwd.
|
|
162
|
+
const home = resolve(expand(io.env.DPI_HOME || join(hd, ".dpi"), hd));
|
|
163
|
+
const envFile = resolve(expand(io.env.DPI_ENV_FILE || join(home, "backend.env"), hd));
|
|
164
|
+
let fileEnv: Record<string, string> = {};
|
|
165
|
+
if (io.exists(envFile)) {
|
|
166
|
+
try {
|
|
167
|
+
fileEnv = readEnvFile(io.readFile(envFile));
|
|
168
|
+
} catch {
|
|
169
|
+
/* unreadable env file: fall back to process env */
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const env: Record<string, string | undefined> = { ...fileEnv, ...io.env };
|
|
173
|
+
const host = env.DPI_HOST || "127.0.0.1";
|
|
174
|
+
// A device listening on every interface is still reached over loopback here.
|
|
175
|
+
const probeHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
|
|
176
|
+
const port = Number(env.DPI_PORT || "4780");
|
|
177
|
+
return {
|
|
178
|
+
env,
|
|
179
|
+
home,
|
|
180
|
+
envFile,
|
|
181
|
+
token: env.DPI_TOKEN || "",
|
|
182
|
+
baseUrl: `http://${probeHost}:${Number.isInteger(port) && port > 0 ? port : 4780}`,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const authHeaders = (token: string): Record<string, string> =>
|
|
187
|
+
token ? { authorization: `Bearer ${token}` } : {};
|
|
188
|
+
|
|
189
|
+
async function getJson(
|
|
190
|
+
io: DoctorIo,
|
|
191
|
+
url: string,
|
|
192
|
+
headers: Record<string, string>,
|
|
193
|
+
ms: number,
|
|
194
|
+
): Promise<{ ok: true; status: number; body: Record<string, unknown> } | { ok: false; detail: string }> {
|
|
195
|
+
let res: HttpResponse;
|
|
196
|
+
try {
|
|
197
|
+
res = await io.fetchImpl(url, { headers, signal: AbortSignal.timeout(ms) });
|
|
198
|
+
} catch (error) {
|
|
199
|
+
return { ok: false, detail: `${url} unreachable — ${describeError(error, ms)}` };
|
|
200
|
+
}
|
|
201
|
+
let body: Record<string, unknown> = {};
|
|
202
|
+
try {
|
|
203
|
+
body = (await res.json()) as Record<string, unknown>;
|
|
204
|
+
} catch {
|
|
205
|
+
/* non-JSON */
|
|
206
|
+
}
|
|
207
|
+
return { ok: true, status: res.status, body };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** 1. node — the only hard block. */
|
|
211
|
+
function nodeCheck(io: DoctorIo): DoctorCheck {
|
|
212
|
+
const required = io.requiredNode;
|
|
213
|
+
const status: DoctorStatus = satisfiesEngine(io.nodeVersion, required) ? "ok" : "fail";
|
|
214
|
+
return {
|
|
215
|
+
id: "node",
|
|
216
|
+
label: `node ${io.nodeVersion}`,
|
|
217
|
+
status,
|
|
218
|
+
detail:
|
|
219
|
+
status === "ok"
|
|
220
|
+
? `satisfies engines node ${required}`
|
|
221
|
+
: `below engines node ${required} — upgrade Node (nvm install --lts / winget upgrade OpenJS.NodeJS.LTS)`,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** 3. start dirs — one check per dir so the failing one is named. */
|
|
226
|
+
function startDirChecks(io: DoctorIo, cfg: Merged): DoctorCheck[] {
|
|
227
|
+
const raw = cfg.env.DPI_START_DIRS || "~/dpi-work";
|
|
228
|
+
const dirs = parseStartDirs(raw, io.homedir());
|
|
229
|
+
if (!dirs.length)
|
|
230
|
+
return [{ id: "start_dirs", label: "start dirs", status: "warn", detail: "DPI_START_DIRS is empty — no cwd is browsable or writable" }];
|
|
231
|
+
return dirs.map((dir, i) => {
|
|
232
|
+
const check = (status: DoctorStatus, detail: string): DoctorCheck => ({
|
|
233
|
+
id: `start_dir${dirs.length > 1 ? `_${i + 1}` : ""}`,
|
|
234
|
+
label: `start dir ${dir}`,
|
|
235
|
+
status,
|
|
236
|
+
detail,
|
|
237
|
+
});
|
|
238
|
+
if (!io.exists(dir)) return check("fail", "missing — create it or fix DPI_START_DIRS");
|
|
239
|
+
try {
|
|
240
|
+
io.access(dir, fsConstants.W_OK);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
return check("fail", `not writable — ${describeError(error, 0)}`);
|
|
243
|
+
}
|
|
244
|
+
return check("ok", "writable");
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** 4. model probe — the device's own default model, through the local-only route. */
|
|
249
|
+
async function probeCheck(io: DoctorIo, cfg: Merged, reachable: boolean): Promise<DoctorCheck> {
|
|
250
|
+
const id = "model_probe";
|
|
251
|
+
if (!reachable) return { id, label: "model probe", status: "skip", detail: "device unreachable" };
|
|
252
|
+
if (!cfg.token) return { id, label: "model probe", status: "skip", detail: `no DPI_TOKEN (looked in ${cfg.envFile})` };
|
|
253
|
+
|
|
254
|
+
const headers = authHeaders(cfg.token);
|
|
255
|
+
const device = await getJson(io, `${cfg.baseUrl}/v1/device`, headers, Math.min(io.timeoutMs * 2, 10_000));
|
|
256
|
+
if (!device.ok) return { id, label: "model probe", status: "warn", detail: device.detail };
|
|
257
|
+
if (device.status !== 200)
|
|
258
|
+
return {
|
|
259
|
+
id,
|
|
260
|
+
label: "model probe",
|
|
261
|
+
status: "warn",
|
|
262
|
+
detail: `GET /v1/device → ${device.status}${device.status === 401 ? " (token mismatch?)" : ""}`,
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
const defaultModel = typeof device.body.defaultModel === "string" ? device.body.defaultModel : "";
|
|
266
|
+
const models = Array.isArray(device.body.models)
|
|
267
|
+
? (device.body.models as Array<{ provider: string; id: string }>).filter((m) => m && m.provider && m.id)
|
|
268
|
+
: undefined;
|
|
269
|
+
const target = defaultModel ? splitModel(defaultModel, models) : undefined;
|
|
270
|
+
const label = `model probe ${defaultModel || "(no default)"}`;
|
|
271
|
+
if (!target) return { id, label, status: "warn", detail: "device reports no usable defaultModel" };
|
|
272
|
+
|
|
273
|
+
let res: HttpResponse;
|
|
274
|
+
try {
|
|
275
|
+
res = await io.fetchImpl(`${cfg.baseUrl}/v1/device/probe-model`, {
|
|
276
|
+
method: "POST",
|
|
277
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
278
|
+
body: JSON.stringify(target),
|
|
279
|
+
signal: AbortSignal.timeout(io.probeTimeoutMs),
|
|
280
|
+
});
|
|
281
|
+
} catch (error) {
|
|
282
|
+
return { id, label, status: "warn", detail: describeError(error, io.probeTimeoutMs) };
|
|
283
|
+
}
|
|
284
|
+
let body: Record<string, unknown> = {};
|
|
285
|
+
try {
|
|
286
|
+
body = (await res.json()) as Record<string, unknown>;
|
|
287
|
+
} catch {
|
|
288
|
+
/* non-JSON */
|
|
289
|
+
}
|
|
290
|
+
if (!res.ok) return { id, label, status: "warn", detail: `probe-model → ${res.status}` };
|
|
291
|
+
const detail = typeof body.detail === "string" && body.detail ? body.detail : body.ok === true ? "answered" : "no answer";
|
|
292
|
+
// A dead provider is a WARN by design: the FE rotates past it, the device is fine.
|
|
293
|
+
return { id, label, status: body.ok === true ? "ok" : "warn", detail: detail.slice(0, 160) };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** 5. hub — only when this device actually has one. */
|
|
297
|
+
async function hubCheck(io: DoctorIo, cfg: Merged): Promise<DoctorCheck> {
|
|
298
|
+
const id = "hub";
|
|
299
|
+
let origin = (cfg.env.DPI_HUB_URL ?? "").trim().replace(/\/+$/, "");
|
|
300
|
+
const source = origin ? "DPI_HUB_URL" : "pairing.json";
|
|
301
|
+
if (!origin) {
|
|
302
|
+
const file = join(cfg.home, "pairing.json");
|
|
303
|
+
try {
|
|
304
|
+
if (io.exists(file)) {
|
|
305
|
+
const paired = JSON.parse(io.readFile(file)) as { hubOrigin?: unknown };
|
|
306
|
+
if (typeof paired.hubOrigin === "string") origin = paired.hubOrigin.trim().replace(/\/+$/, "");
|
|
307
|
+
}
|
|
308
|
+
} catch {
|
|
309
|
+
/* unreadable/garbled pairing file: report as not configured */
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (!origin) return { id, label: "hub", status: "skip", detail: "no hub configured (no DPI_HUB_URL, no saved pairing)" };
|
|
313
|
+
|
|
314
|
+
const label = `hub ${origin}`;
|
|
315
|
+
const url = `${origin}/healthz`;
|
|
316
|
+
const ms = Math.max(io.hubTimeoutMs, io.timeoutMs);
|
|
317
|
+
let res: HttpResponse;
|
|
318
|
+
try {
|
|
319
|
+
res = await io.fetchImpl(url, { signal: AbortSignal.timeout(ms) });
|
|
320
|
+
} catch (error) {
|
|
321
|
+
return { id, label, status: "warn", detail: `${url} unreachable — ${describeError(error, ms)} (${source})` };
|
|
322
|
+
}
|
|
323
|
+
if (!res.ok) return { id, label, status: "warn", detail: `${url} → ${res.status} (${source})` };
|
|
324
|
+
return { id, label, status: "ok", detail: `${url} answered (${source})` };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** 2. healthz — is the daemon there at all. */
|
|
328
|
+
async function healthzCheck(
|
|
329
|
+
io: DoctorIo,
|
|
330
|
+
cfg: Merged,
|
|
331
|
+
): Promise<{ check: DoctorCheck; reachable: boolean }> {
|
|
332
|
+
const url = `${cfg.baseUrl}/healthz`;
|
|
333
|
+
const label = `healthz ${url}`;
|
|
334
|
+
let res: HttpResponse;
|
|
335
|
+
try {
|
|
336
|
+
res = await io.fetchImpl(url, { signal: AbortSignal.timeout(io.timeoutMs) });
|
|
337
|
+
} catch (error) {
|
|
338
|
+
return {
|
|
339
|
+
check: { id: "healthz", label, status: "fail", detail: `unreachable — ${describeError(error, io.timeoutMs)} (is the device running? "dpi device start")` },
|
|
340
|
+
reachable: false,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
if (!res.ok) return { check: { id: "healthz", label, status: "fail", detail: `responded ${res.status}` }, reachable: false };
|
|
344
|
+
return { check: { id: "healthz", label, status: "ok", detail: "device answered" }, reachable: true };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// ------------------------------------------------------------------- driver
|
|
348
|
+
|
|
349
|
+
/** Run every check. Warnings never make `ok` false; only a FAIL does. */
|
|
350
|
+
export async function runDoctor(opts: Partial<DoctorIo> = {}): Promise<DoctorReport> {
|
|
351
|
+
const io: DoctorIo = { ...defaultDoctorIo(), ...opts };
|
|
352
|
+
const cfg = mergedConfig(io);
|
|
353
|
+
|
|
354
|
+
const checks: DoctorCheck[] = [nodeCheck(io)];
|
|
355
|
+
const health = await healthzCheck(io, cfg);
|
|
356
|
+
checks.push(health.check);
|
|
357
|
+
checks.push(...startDirChecks(io, cfg));
|
|
358
|
+
checks.push(await probeCheck(io, cfg, health.reachable));
|
|
359
|
+
checks.push(await hubCheck(io, cfg));
|
|
360
|
+
|
|
361
|
+
return { checks, ok: checks.every((c) => c.status !== "fail") };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** 1 when anything FAILED, 0 otherwise — the only thing that touches process.exit. */
|
|
365
|
+
export const exitCode = (report: DoctorReport): 0 | 1 => (report.ok ? 0 : 1);
|
|
366
|
+
|
|
367
|
+
const MARK: Record<DoctorStatus, string> = { ok: "ok ", warn: "warn", fail: "fail", skip: "skip" };
|
|
368
|
+
|
|
369
|
+
/** Human lines. `quiet` keeps warnings and failures (and always the verdict). */
|
|
370
|
+
export function formatReport(report: DoctorReport, opts: { quiet?: boolean } = {}): string[] {
|
|
371
|
+
const shown = opts.quiet ? report.checks.filter((c) => c.status === "warn" || c.status === "fail") : report.checks;
|
|
372
|
+
const lines = shown.map((c) => `${MARK[c.status]} ${c.label} — ${c.detail}`);
|
|
373
|
+
const failed = report.checks.filter((c) => c.status === "fail").length;
|
|
374
|
+
const warned = report.checks.filter((c) => c.status === "warn").length;
|
|
375
|
+
if (report.ok) {
|
|
376
|
+
const counts = `${report.checks.length} checks`;
|
|
377
|
+
const tail = warned ? `${warned} warning${warned === 1 ? "" : "s"}` : "all good";
|
|
378
|
+
if (!lines.length) lines.push(`doctor: OK — ${counts}, ${tail}`);
|
|
379
|
+
else lines.push("", `doctor: OK — ${counts}, ${tail}`);
|
|
380
|
+
return lines;
|
|
381
|
+
}
|
|
382
|
+
lines.push("", `doctor: ${failed} check${failed === 1 ? "" : "s"} failed${warned ? `, ${warned} warning${warned === 1 ? "" : "s"}` : ""}`);
|
|
383
|
+
return lines;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export interface DoctorCliDeps extends Partial<DoctorIo> {
|
|
387
|
+
print?: (line: string) => void;
|
|
388
|
+
printErr?: (line: string) => void;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* `dpi doctor [--json] [--quiet]` — parse, run, print, return the exit code.
|
|
393
|
+
* Kept here (not in bin/dpi.mjs) so the exit-code derivation is unit-testable.
|
|
394
|
+
*/
|
|
395
|
+
export async function doctorCli(argv: string[] = [], deps: DoctorCliDeps = {}): Promise<0 | 1> {
|
|
396
|
+
const print = deps.print ?? ((line: string) => process.stdout.write(`${line}\n`));
|
|
397
|
+
const printErr = deps.printErr ?? ((line: string) => process.stderr.write(`${line}\n`));
|
|
398
|
+
const json = argv.includes("--json");
|
|
399
|
+
const quiet = argv.includes("--quiet") || argv.includes("-q");
|
|
400
|
+
const unknown = argv.filter((a) => !["--json", "--quiet", "-q", "--help", "-h"].includes(a));
|
|
401
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
402
|
+
print(DOCTOR_HELP);
|
|
403
|
+
return 0;
|
|
404
|
+
}
|
|
405
|
+
if (unknown.length) {
|
|
406
|
+
printErr(`dpi doctor: unknown flag '${unknown[0]}'\n\n${DOCTOR_HELP}`);
|
|
407
|
+
return 1;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const { print: _p, printErr: _e, ...io } = deps;
|
|
411
|
+
const report = await runDoctor(io);
|
|
412
|
+
if (json) print(JSON.stringify(report, null, 2));
|
|
413
|
+
else for (const line of formatReport(report, { quiet })) print(line);
|
|
414
|
+
return exitCode(report);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export const DOCTOR_HELP = `dpi doctor [--json] [--quiet]
|
|
418
|
+
|
|
419
|
+
One-shot health check for this machine's device: node >= 22.19.0, healthz,
|
|
420
|
+
start-dir writability, the default-model probe and the hub's /healthz.
|
|
421
|
+
|
|
422
|
+
--json machine-readable { checks: [{ id, label, status, detail }], ok }
|
|
423
|
+
--quiet print only warnings and failures
|
|
424
|
+
|
|
425
|
+
Exit code: 1 when a check fails, 0 otherwise (warnings are not failures).
|
|
426
|
+
`;
|
|
@@ -119,6 +119,8 @@ export function v1(
|
|
|
119
119
|
const modelId = String(req.body?.modelId ?? "");
|
|
120
120
|
res.json(await store.probeModel(provider, modelId));
|
|
121
121
|
}));
|
|
122
|
+
// Host health (uptime/load/memory/disk) — one-shot, the UIs ask when looked at.
|
|
123
|
+
r.get("/device/vitals", route(async (_req, res) => res.json(await store.vitals())));
|
|
122
124
|
r.get("/tree", route(async (_req, res) => res.json(await store.tree())));
|
|
123
125
|
r.get("/events", (req, res, next) => {
|
|
124
126
|
try {
|
|
@@ -171,11 +173,16 @@ export function v1(
|
|
|
171
173
|
// ---------------------------------------------------------- sessions
|
|
172
174
|
r.get("/sessions", route(async (_req, res) => res.json((await store.tree()).sessions)));
|
|
173
175
|
r.post("/sessions", create, route(async (req, res) => res.status(201).json(await store.create(req.body ?? {}))));
|
|
176
|
+
// Literal route, so it must precede `/sessions/:s` (Express matches in order).
|
|
177
|
+
// Names/cwds/models only — transcript search needs an FTS index, not a LIKE scan.
|
|
178
|
+
r.get("/sessions/search", route(async (req, res) => res.json(store.searchSessions(String(req.query.q ?? "")))));
|
|
174
179
|
r.get("/sessions/:s", route(async (_req, res) => res.json(await store.sessionSummary(L(res).row))));
|
|
175
180
|
r.patch("/sessions/:s", route(async (req, res) => res.json(await store.rename(L(res).row, req.body?.name))));
|
|
176
181
|
r.get("/sessions/:s/compaction", route(async (_req, res) => res.json(store.compactionOf(L(res).row.id))));
|
|
177
182
|
r.patch("/sessions/:s/compaction", route(async (req, res) => res.json(store.setCompaction(L(res).row, req.body ?? {}))));
|
|
178
183
|
r.delete("/sessions/:s", route(async (_req, res) => res.json(await store.archive(L(res).row))));
|
|
184
|
+
// One downloadable .zip: manifest + session record + every agent's transcript/config.
|
|
185
|
+
r.get("/sessions/:s/export", route(async (_req, res) => res.json(await store.exportSession(L(res).row))));
|
|
179
186
|
r.get("/sessions/:s/events", route(async (_req, res) => sessionStream(store, L(res).row, res)));
|
|
180
187
|
// The zcode flagship, adapted: which files has THIS session's agent touched?
|
|
181
188
|
// Powers "commit session changes" in the git panel.
|
|
@@ -13,6 +13,8 @@ import type {
|
|
|
13
13
|
ModelInfo,
|
|
14
14
|
Page,
|
|
15
15
|
SendResult,
|
|
16
|
+
SessionSearchMatch,
|
|
17
|
+
SessionSearchResult,
|
|
16
18
|
SessionSummary,
|
|
17
19
|
TaskNode,
|
|
18
20
|
TaskOutcome,
|
|
@@ -33,6 +35,8 @@ import { ApiFault, invalid, notFound } from "./errors.js";
|
|
|
33
35
|
import { git, gitDirtyMarks, onGitDirty } from "./git.js";
|
|
34
36
|
import { DatabaseSync } from "node:sqlite";
|
|
35
37
|
import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
|
|
38
|
+
import { deviceVitals, type DeviceVitals } from "./vitals.js";
|
|
39
|
+
import { zipSync, type ZipEntry } from "./zip.js";
|
|
36
40
|
import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
|
|
37
41
|
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
38
42
|
import { join, dirname, relative, resolve } from "node:path";
|
|
@@ -109,6 +113,30 @@ export interface StoreOptions {
|
|
|
109
113
|
/** Agent documents a client may read or stream, by kind. */
|
|
110
114
|
/** apps/dpi-backend/src → the checkout root. */
|
|
111
115
|
const CODE_DIR = resolve(import.meta.dirname, "../../..");
|
|
116
|
+
|
|
117
|
+
/** Session search result cap: one screen of matches, not a transcript dump. */
|
|
118
|
+
const SEARCH_LIMIT = 50;
|
|
119
|
+
|
|
120
|
+
/** A bundle for a session whose store is closed (archived or restarting) still exports its record. */
|
|
121
|
+
const NOT_OPENED_README = [
|
|
122
|
+
"This bundle was exported while the session's store was closed.",
|
|
123
|
+
"",
|
|
124
|
+
"It contains manifest.json and session.json only. Start the device and re-export",
|
|
125
|
+
"from the running session to include per-agent transcripts and configs.",
|
|
126
|
+
"",
|
|
127
|
+
].join("\n");
|
|
128
|
+
|
|
129
|
+
/** "My session #1" → "my-session-1" for the download name. */
|
|
130
|
+
function slugName(input: string): string {
|
|
131
|
+
const slug = input
|
|
132
|
+
.normalize("NFKD")
|
|
133
|
+
.replace(/[^\w.-]+/g, "-")
|
|
134
|
+
.replace(/^-+|-+$/g, "")
|
|
135
|
+
.slice(0, 60)
|
|
136
|
+
.toLowerCase();
|
|
137
|
+
return slug || "session";
|
|
138
|
+
}
|
|
139
|
+
|
|
112
140
|
const AGENT_DOCS = { [JOB_RUNS_DOC]: JobRuns, "demo.workspace": Workspace } as const;
|
|
113
141
|
export const AGENT_DOC_KINDS = Object.keys(AGENT_DOCS);
|
|
114
142
|
export const DEVICE_DOC_KINDS = ["app.shared-state"];
|
|
@@ -1430,6 +1458,99 @@ export class Store {
|
|
|
1430
1458
|
return { uid: this.uid, name: this.name, sessions, at: Date.now(), ...(git.length ? { git } : {}) };
|
|
1431
1459
|
}
|
|
1432
1460
|
|
|
1461
|
+
// ------------------------------------------- ops: vitals, search, export
|
|
1462
|
+
|
|
1463
|
+
/** One-shot host health (herdr/piggery shape) — asked for, never polled. */
|
|
1464
|
+
async vitals(): Promise<DeviceVitals & { counts: { sessions: number; archived: number } }> {
|
|
1465
|
+
const archived = await readdir(this.archiveDir).catch(() => [] as string[]);
|
|
1466
|
+
return {
|
|
1467
|
+
...deviceVitals(this.options.dataDir, this.startedAt),
|
|
1468
|
+
counts: { sessions: this.list().length, archived: archived.length },
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
/**
|
|
1473
|
+
* Session search over names, cwds and models — the cheap half of paseo's
|
|
1474
|
+
* history search. Transcript text is deliberately NOT scanned: at volume it
|
|
1475
|
+
* needs an FTS index, and a naive LIKE over every entry would make the device
|
|
1476
|
+
* slow exactly when a human is typing.
|
|
1477
|
+
*/
|
|
1478
|
+
searchSessions(rawQuery: string): SessionSearchResult {
|
|
1479
|
+
const query = String(rawQuery ?? "").trim();
|
|
1480
|
+
const needle = query.toLowerCase();
|
|
1481
|
+
if (needle.length < 2) return { query, matches: [] };
|
|
1482
|
+
const matches: SessionSearchMatch[] = [];
|
|
1483
|
+
for (const row of this.list()) {
|
|
1484
|
+
const where: SessionSearchMatch["where"] = [];
|
|
1485
|
+
if (row.name.toLowerCase().includes(needle)) where.push("name");
|
|
1486
|
+
if (row.cwd.toLowerCase().includes(needle)) where.push("cwd");
|
|
1487
|
+
if (row.model.toLowerCase().includes(needle)) where.push("model");
|
|
1488
|
+
if (!where.length) continue;
|
|
1489
|
+
const base = this.sessionSummaryBase(row);
|
|
1490
|
+
matches.push({
|
|
1491
|
+
id: base.id,
|
|
1492
|
+
name: base.name,
|
|
1493
|
+
cwd: base.cwd,
|
|
1494
|
+
model: base.model,
|
|
1495
|
+
createdAt: base.createdAt,
|
|
1496
|
+
dbPath: base.dbPath,
|
|
1497
|
+
...(base.compaction ? { compaction: base.compaction } : {}),
|
|
1498
|
+
where,
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
// Name hits first (what a human means by "search my sessions"), then the newest.
|
|
1502
|
+
matches.sort(
|
|
1503
|
+
(a, b) => Number(b.where.includes("name")) - Number(a.where.includes("name")) || b.createdAt - a.createdAt,
|
|
1504
|
+
);
|
|
1505
|
+
return { query, matches: matches.slice(0, SEARCH_LIMIT) };
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
/**
|
|
1509
|
+
* One downloadable archive of a session: manifest, session record, and every
|
|
1510
|
+
* agent's transcript + config (paseo `exports.ts` shape). Text only, zipped by
|
|
1511
|
+
* our own writer — the device has no archive dependency.
|
|
1512
|
+
*/
|
|
1513
|
+
async exportSession(
|
|
1514
|
+
row: SessionRow,
|
|
1515
|
+
): Promise<{ filename: string; mime: string; bytes: number; base64: string }> {
|
|
1516
|
+
const agents = this.opened.has(row.id) ? await this.agents(row) : [];
|
|
1517
|
+
const files: ZipEntry[] = [];
|
|
1518
|
+
const manifest = {
|
|
1519
|
+
format: "dpi-session-bundle",
|
|
1520
|
+
version: 1,
|
|
1521
|
+
exportedAt: new Date().toISOString(),
|
|
1522
|
+
device: {
|
|
1523
|
+
uid: this.uid,
|
|
1524
|
+
name: this.name,
|
|
1525
|
+
hostname: hostname(),
|
|
1526
|
+
platform: `${platform()} node ${process.version}`,
|
|
1527
|
+
durableVersion: DURABLE_VERSION,
|
|
1528
|
+
},
|
|
1529
|
+
session: { id: row.id, name: row.name, cwd: row.cwd, model: row.model, createdAt: row.createdAt },
|
|
1530
|
+
agents: agents.map((a) => ({ id: a.id, name: a.name, kind: a.kind })),
|
|
1531
|
+
};
|
|
1532
|
+
files.push({ path: "manifest.json", text: `${JSON.stringify(manifest, null, 2)}\n` });
|
|
1533
|
+
files.push({ path: "session.json", text: `${JSON.stringify(this.sessionSummaryBase(row), null, 2)}\n` });
|
|
1534
|
+
const opened = this.opened.get(row.id);
|
|
1535
|
+
for (const agent of agents) {
|
|
1536
|
+
const c = opened ? await opened.harness.conversation(agent.id as ConversationId, ctx) : undefined;
|
|
1537
|
+
if (!c) continue;
|
|
1538
|
+
const dir = `agents/${agent.id}`;
|
|
1539
|
+
files.push({ path: `${dir}/transcript.json`, text: `${JSON.stringify(await this.transcript(c, "json"), null, 2)}\n` });
|
|
1540
|
+
const md = await this.transcript(c, "markdown");
|
|
1541
|
+
if (typeof md.text === "string") files.push({ path: `${dir}/transcript.md`, text: md.text });
|
|
1542
|
+
files.push({ path: `${dir}/config.json`, text: `${JSON.stringify((await this.agentDetail(row, c)).config, null, 2)}\n` });
|
|
1543
|
+
}
|
|
1544
|
+
if (!agents.length) files.push({ path: "README.txt", text: NOT_OPENED_README });
|
|
1545
|
+
const zip = zipSync(files);
|
|
1546
|
+
return {
|
|
1547
|
+
filename: `${slugName(row.name || row.id)}.bundle.zip`,
|
|
1548
|
+
mime: "application/zip",
|
|
1549
|
+
bytes: zip.length,
|
|
1550
|
+
base64: zip.toString("base64"),
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1433
1554
|
// ------------------------------------------------------------ demo extension
|
|
1434
1555
|
|
|
1435
1556
|
async demoState(c: Conversation, body: Record<string, unknown>) {
|