my-durable 0.0.52 → 0.0.54
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/apps/dpi-backend/src/daemon.ts +18 -1
- package/apps/dpi-backend/src/doctor.ts +4 -3
- package/apps/dpi-backend/src/errors.ts +21 -0
- package/apps/dpi-backend/src/notify-sinks.ts +11 -4
- package/apps/dpi-backend/src/pair-cli.ts +45 -32
- package/apps/dpi-backend/src/routes.ts +73 -15
- package/apps/dpi-backend/src/store.ts +57 -7
- package/apps/dpi-playground/apps/dpi-playground-fe/src/client/commands.ts +5 -3
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +2 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/SchedulesPanel.vue +4 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TopBar.vue +3 -1
- package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +24 -0
- package/apps/dpi-tui/src/app.ts +52 -10
- package/apps/dpi-tui/src/commands.ts +3 -1
- package/apps/dpi-tui/src/views.ts +5 -1
- package/bin/dpi.mjs +16 -3
- package/package.json +1 -1
|
@@ -20,12 +20,25 @@ import { openSync, closeSync, existsSync, readFileSync, mkdirSync, rmSync, write
|
|
|
20
20
|
import { homedir } from "node:os";
|
|
21
21
|
import { dirname, join } from "node:path";
|
|
22
22
|
|
|
23
|
-
export type DeviceSub = "run" | "start" | "stop" | "status" | "install" | "uninstall";
|
|
23
|
+
export type DeviceSub = "run" | "start" | "stop" | "status" | "install" | "uninstall" | "help";
|
|
24
|
+
|
|
25
|
+
/** `dpi device --help` — printed without touching the daemon or its home. */
|
|
26
|
+
export const DEVICE_USAGE = `dpi device — the device-side daemon
|
|
27
|
+
|
|
28
|
+
dpi device run the daemon in the foreground
|
|
29
|
+
dpi device start start it detached (no terminal, logs to device.log)
|
|
30
|
+
dpi device stop graceful stop (token-authed shutdown, pid kill as fallback)
|
|
31
|
+
dpi device status health + pid + pairing state
|
|
32
|
+
dpi device install | uninstall OS service (systemd --user / launchd / Startup VBS)
|
|
33
|
+
|
|
34
|
+
Any other word — or none — runs the daemon in the foreground, flags included.
|
|
35
|
+
Environment: DPI_HUB_URL, DPI_HOME (see dpi --help).`;
|
|
24
36
|
|
|
25
37
|
/** First argv word decides: a subcommand runs and exits, anything else = foreground daemon. */
|
|
26
38
|
export function parseDeviceSub(argv: string[]): { sub: DeviceSub; rest: string[] } {
|
|
27
39
|
const subs: DeviceSub[] = ["start", "stop", "status", "install", "uninstall"];
|
|
28
40
|
const [first, ...rest] = argv;
|
|
41
|
+
if (first === "-h" || first === "--help" || first === "help") return { sub: "help", rest: [] };
|
|
29
42
|
return subs.includes(first as DeviceSub)
|
|
30
43
|
? { sub: first as DeviceSub, rest }
|
|
31
44
|
: { sub: "run", rest: argv };
|
|
@@ -425,6 +438,10 @@ async function cmdUninstall(io: Io): Promise<number> {
|
|
|
425
438
|
|
|
426
439
|
export async function runDeviceCommand(sub: DeviceSub, rest: string[], opts: RunOpts = {}): Promise<number> {
|
|
427
440
|
const io = ioOf(opts);
|
|
441
|
+
if (sub === "help") {
|
|
442
|
+
io.print(DEVICE_USAGE);
|
|
443
|
+
return 0;
|
|
444
|
+
}
|
|
428
445
|
if (sub === "start") return cmdStart(io, rest);
|
|
429
446
|
if (sub === "stop") return cmdStop(io);
|
|
430
447
|
if (sub === "status") return cmdStatus(io);
|
|
@@ -427,7 +427,7 @@ export interface DoctorCliDeps extends Partial<DoctorIo> {
|
|
|
427
427
|
* `dpi doctor [--json] [--quiet]` — parse, run, print, return the exit code.
|
|
428
428
|
* Kept here (not in bin/dpi.mjs) so the exit-code derivation is unit-testable.
|
|
429
429
|
*/
|
|
430
|
-
export async function doctorCli(argv: string[] = [], deps: DoctorCliDeps = {}): Promise<0 | 1> {
|
|
430
|
+
export async function doctorCli(argv: string[] = [], deps: DoctorCliDeps = {}): Promise<0 | 1 | 2> {
|
|
431
431
|
const print = deps.print ?? ((line: string) => process.stdout.write(`${line}\n`));
|
|
432
432
|
const printErr = deps.printErr ?? ((line: string) => process.stderr.write(`${line}\n`));
|
|
433
433
|
const json = argv.includes("--json");
|
|
@@ -439,7 +439,7 @@ export async function doctorCli(argv: string[] = [], deps: DoctorCliDeps = {}):
|
|
|
439
439
|
}
|
|
440
440
|
if (unknown.length) {
|
|
441
441
|
printErr(`dpi doctor: unknown flag '${unknown[0]}'\n\n${DOCTOR_HELP}`);
|
|
442
|
-
return
|
|
442
|
+
return 2;
|
|
443
443
|
}
|
|
444
444
|
|
|
445
445
|
const { print: _p, printErr: _e, ...io } = deps;
|
|
@@ -457,5 +457,6 @@ start-dir writability, the default-model probe and the hub's /healthz.
|
|
|
457
457
|
--json machine-readable { checks: [{ id, label, status, detail }], ok }
|
|
458
458
|
--quiet print only warnings and failures
|
|
459
459
|
|
|
460
|
-
Exit
|
|
460
|
+
Exit codes: 0 ok, 1 when a check fails (warnings are not failures),
|
|
461
|
+
2 bad usage — the same code every other subcommand uses.
|
|
461
462
|
`;
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import type { ErrorRequestHandler } from "express";
|
|
2
2
|
import { ConversationBusy, SessionFailed } from "@earendil-works/pi-durable";
|
|
3
3
|
import type { ErrorCode } from "../../dpi-sdk/src/api.js";
|
|
4
|
+
import { ScheduleRegistryError } from "./schedules.js";
|
|
5
|
+
import { GraphError } from "./graphs.js";
|
|
6
|
+
import { NotifySinkError } from "./notify-sinks.js";
|
|
7
|
+
import { ProjectRegistryError } from "./projects.js";
|
|
8
|
+
import { EnvError } from "./env-vars.js";
|
|
4
9
|
|
|
5
10
|
const STATUS: Record<ErrorCode, number> = {
|
|
6
11
|
unauthorized: 401,
|
|
@@ -30,9 +35,25 @@ export class ApiFault extends Error {
|
|
|
30
35
|
export const invalid = (message: string) => new ApiFault("invalid", message);
|
|
31
36
|
export const notFound = (message: string) => new ApiFault("not_found", message);
|
|
32
37
|
|
|
38
|
+
/** Typed registry failures carry their own 4xx code (`invalid`/`not_found`) — map them
|
|
39
|
+
* to the matching status with the message intact, instead of a 500 "internal". */
|
|
40
|
+
const registryFault = (err: unknown): ApiFault | undefined => {
|
|
41
|
+
if (
|
|
42
|
+
err instanceof ScheduleRegistryError ||
|
|
43
|
+
err instanceof GraphError ||
|
|
44
|
+
err instanceof NotifySinkError ||
|
|
45
|
+
err instanceof ProjectRegistryError ||
|
|
46
|
+
err instanceof EnvError
|
|
47
|
+
)
|
|
48
|
+
return err.code === "not_found" ? notFound(err.message) : invalid(err.message);
|
|
49
|
+
return undefined;
|
|
50
|
+
};
|
|
51
|
+
|
|
33
52
|
export const errorMiddleware: ErrorRequestHandler = (err, req, res, _next) => {
|
|
34
53
|
let fault: ApiFault;
|
|
54
|
+
const typed = registryFault(err);
|
|
35
55
|
if (err instanceof ApiFault) fault = err;
|
|
56
|
+
else if (typed) fault = typed;
|
|
36
57
|
else if (err instanceof SessionFailed)
|
|
37
58
|
fault = new ApiFault("unavailable", "The session failed and is closed; it is unavailable until reopened");
|
|
38
59
|
else if (err instanceof ConversationBusy) fault = new ApiFault("busy", "The agent is busy and the input asked to be rejected while busy");
|
|
@@ -586,9 +586,12 @@ export class NotifySinks {
|
|
|
586
586
|
* Add a sink. Validation throws (`NotifySinkError` `invalid`) rather than
|
|
587
587
|
* coercing, so a UI can show the reason: the URL is the one field a typo makes
|
|
588
588
|
* silently useless.
|
|
589
|
+
*
|
|
590
|
+
* `options.allowPrivateHosts` grants this one call on top of the env default
|
|
591
|
+
* (`DPI_NOTIFY_ALLOW_PRIVATE`) — a LAN sink is an explicit per-request opt-in.
|
|
589
592
|
*/
|
|
590
|
-
async create(input: SinkInput): Promise<SinkRecord> {
|
|
591
|
-
const fields = validateInput(input, { allowPrivateHosts: this.allowPrivateHosts });
|
|
593
|
+
async create(input: SinkInput, options: { allowPrivateHosts?: boolean } = {}): Promise<SinkRecord> {
|
|
594
|
+
const fields = validateInput(input, { allowPrivateHosts: this.allowPrivateHosts || options.allowPrivateHosts === true });
|
|
592
595
|
return this.run(async () => {
|
|
593
596
|
const staged = new Map(this.records);
|
|
594
597
|
let id = newSinkId();
|
|
@@ -607,7 +610,11 @@ export class NotifySinks {
|
|
|
607
610
|
* will actually be used. `enabled: false` keeps the record — muting a noisy
|
|
608
611
|
* sink is not the same as forgetting it.
|
|
609
612
|
*/
|
|
610
|
-
async update(
|
|
613
|
+
async update(
|
|
614
|
+
id: string,
|
|
615
|
+
patch: Partial<SinkInput> & { enabled?: boolean },
|
|
616
|
+
options: { allowPrivateHosts?: boolean } = {},
|
|
617
|
+
): Promise<SinkRecord> {
|
|
611
618
|
return this.run(async () => {
|
|
612
619
|
const staged = new Map(this.records);
|
|
613
620
|
const existing = staged.get(id);
|
|
@@ -625,7 +632,7 @@ export class NotifySinks {
|
|
|
625
632
|
else if (existing.priority) merged.priority = existing.priority;
|
|
626
633
|
if ("tags" in patch) merged.tags = patch.tags;
|
|
627
634
|
else if (existing.tags) merged.tags = existing.tags;
|
|
628
|
-
const fields = validateInput(merged, { allowPrivateHosts: this.allowPrivateHosts });
|
|
635
|
+
const fields = validateInput(merged, { allowPrivateHosts: this.allowPrivateHosts || options.allowPrivateHosts === true });
|
|
629
636
|
const next: SinkRecord = { ...existing, ...fields, id: existing.id, createdAt: existing.createdAt };
|
|
630
637
|
next.updatedAt = this.now();
|
|
631
638
|
// A field that validation dropped (empty label, no tags) must not linger from the old record.
|
|
@@ -24,6 +24,8 @@ export interface PairCliDeps {
|
|
|
24
24
|
env?: Record<string, string | undefined>;
|
|
25
25
|
fetchImpl?: typeof fetch;
|
|
26
26
|
print?: (line: string) => void;
|
|
27
|
+
/** Where failures and usage go (stdout stays clean for pipes, like every other subcommand). */
|
|
28
|
+
printErr?: (line: string) => void;
|
|
27
29
|
/** Poll interval while waiting for approval (tests shrink it). */
|
|
28
30
|
pollMs?: number;
|
|
29
31
|
/** Give up waiting after this long (0 = wait forever, the default). */
|
|
@@ -42,6 +44,7 @@ function io(deps: PairCliDeps) {
|
|
|
42
44
|
env: deps.env ?? process.env,
|
|
43
45
|
fetch: deps.fetchImpl ?? fetch,
|
|
44
46
|
print: deps.print ?? ((line: string) => process.stdout.write(`${line}\n`)),
|
|
47
|
+
printErr: deps.printErr ?? ((line: string) => process.stderr.write(`${line}\n`)),
|
|
45
48
|
pollMs: deps.pollMs ?? 1000,
|
|
46
49
|
timeoutMs: deps.timeoutMs ?? 0,
|
|
47
50
|
sleep: deps.sleep ?? realSleep,
|
|
@@ -154,10 +157,10 @@ export async function pairThisDevice(
|
|
|
154
157
|
args: { target?: string; hub?: string; force: boolean },
|
|
155
158
|
deps: PairCliDeps = {},
|
|
156
159
|
): Promise<number> {
|
|
157
|
-
const { env, fetch: f, print, pollMs, timeoutMs, sleep } = io(deps);
|
|
160
|
+
const { env, fetch: f, print, printErr, pollMs, timeoutMs, sleep } = io(deps);
|
|
158
161
|
const local = localTarget(env);
|
|
159
162
|
if (!local.token) {
|
|
160
|
-
|
|
163
|
+
printErr("no local device token — is `dpi device` installed here? (looked in DPI_TOKEN / backend.env)");
|
|
161
164
|
return 1;
|
|
162
165
|
}
|
|
163
166
|
const auth = { authorization: `Bearer ${local.token}`, "content-type": "application/json" };
|
|
@@ -171,7 +174,7 @@ export async function pairThisDevice(
|
|
|
171
174
|
// Device-initiated: no secret to carry between machines.
|
|
172
175
|
body.hub = args.hub;
|
|
173
176
|
} else {
|
|
174
|
-
|
|
177
|
+
printErr("pair needs a code, a pair link, or --hub <origin> to ask the hub itself");
|
|
175
178
|
return 1;
|
|
176
179
|
}
|
|
177
180
|
if (args.force) body.force = true;
|
|
@@ -183,7 +186,7 @@ export async function pairThisDevice(
|
|
|
183
186
|
"pairing start",
|
|
184
187
|
);
|
|
185
188
|
} catch (error) {
|
|
186
|
-
|
|
189
|
+
printErr(`pairing failed: ${(error as Error).message}`);
|
|
187
190
|
return 1;
|
|
188
191
|
}
|
|
189
192
|
|
|
@@ -213,7 +216,7 @@ export async function pairThisDevice(
|
|
|
213
216
|
try {
|
|
214
217
|
now = await jsonOrThrow(await f(`${local.url}/v1/pairing`, { headers: auth }), "pairing status");
|
|
215
218
|
} catch (error) {
|
|
216
|
-
|
|
219
|
+
printErr(`lost the local backend: ${(error as Error).message}`);
|
|
217
220
|
return 1;
|
|
218
221
|
}
|
|
219
222
|
const state = String(now.state ?? "");
|
|
@@ -222,11 +225,11 @@ export async function pairThisDevice(
|
|
|
222
225
|
return 0;
|
|
223
226
|
}
|
|
224
227
|
if (state === "unpaired" || state === "failed") {
|
|
225
|
-
|
|
228
|
+
printErr(`pairing ended: ${String((now as { lastError?: string }).lastError ?? state)}`);
|
|
226
229
|
return 1;
|
|
227
230
|
}
|
|
228
231
|
if (deadline && Date.now() > deadline) {
|
|
229
|
-
|
|
232
|
+
printErr("still waiting for approval — approve it and run `dpi pair` again, or wait longer with --wait");
|
|
230
233
|
return 1;
|
|
231
234
|
}
|
|
232
235
|
}
|
|
@@ -234,11 +237,11 @@ export async function pairThisDevice(
|
|
|
234
237
|
|
|
235
238
|
/** Operator side: mint an offer link for a machine that has no CLI pairing yet. */
|
|
236
239
|
async function pairOffer(deps: PairCliDeps, hubArg?: string): Promise<number> {
|
|
237
|
-
const { env, fetch: f, print } = io(deps);
|
|
240
|
+
const { env, fetch: f, print, printErr } = io(deps);
|
|
238
241
|
const hub = hubTarget(env, deps.hubHome);
|
|
239
242
|
const origin = hubArg ?? hub.origin;
|
|
240
|
-
if (!origin) return
|
|
241
|
-
if (!hub.token) return
|
|
243
|
+
if (!origin) return printErr("offer needs --hub <origin> (or DPI_HUB_URL)"), 1;
|
|
244
|
+
if (!hub.token) return printErr("offer needs the hub admin token (DPI_ADMIN_TOKEN or the hub's admin.token)"), 1;
|
|
242
245
|
try {
|
|
243
246
|
const minted = await jsonOrThrow(
|
|
244
247
|
await f(`${origin}/api/pair/code`, {
|
|
@@ -254,7 +257,7 @@ async function pairOffer(deps: PairCliDeps, hubArg?: string): Promise<number> {
|
|
|
254
257
|
print("paste that link on the machine: dpi pair <link> (or dpi tui --pair <link>)");
|
|
255
258
|
return 0;
|
|
256
259
|
} catch (error) {
|
|
257
|
-
|
|
260
|
+
printErr(`offer failed: ${(error as Error).message}`);
|
|
258
261
|
return 1;
|
|
259
262
|
}
|
|
260
263
|
}
|
|
@@ -306,14 +309,14 @@ async function pendingCodes(origin: string, token: string, f: typeof fetch): Pro
|
|
|
306
309
|
}
|
|
307
310
|
|
|
308
311
|
async function pairList(deps: PairCliDeps, hubArg?: string, watch = false): Promise<number> {
|
|
309
|
-
const { env, fetch: f, print, pollMs, sleep } = io(deps);
|
|
312
|
+
const { env, fetch: f, print, printErr, pollMs, sleep } = io(deps);
|
|
310
313
|
if (watch) {
|
|
311
314
|
// Live: reprint only when the set of waiting machines changes, so the
|
|
312
315
|
// operator sees a device appear (or leave) without re-running the command.
|
|
313
316
|
let previous = "";
|
|
314
317
|
for (;;) {
|
|
315
318
|
const snapshot = await pendingCodesOrError(deps, hubArg);
|
|
316
|
-
if (typeof snapshot === "string") return
|
|
319
|
+
if (typeof snapshot === "string") return printErr(snapshot), 1;
|
|
317
320
|
const key = snapshot.map((c) => `${c.codeId}:${c.phase}:${c.deviceName ?? ""}`).join("|");
|
|
318
321
|
if (key !== previous) {
|
|
319
322
|
previous = key;
|
|
@@ -326,8 +329,8 @@ async function pairList(deps: PairCliDeps, hubArg?: string, watch = false): Prom
|
|
|
326
329
|
}
|
|
327
330
|
const hub = hubTarget(env, deps.hubHome);
|
|
328
331
|
const origin = hubArg ?? hub.origin;
|
|
329
|
-
if (!origin) return
|
|
330
|
-
if (!hub.token) return
|
|
332
|
+
if (!origin) return printErr("list needs --hub <origin> (or DPI_HUB_URL)"), 1;
|
|
333
|
+
if (!hub.token) return printErr("list needs the hub admin token (DPI_ADMIN_TOKEN or the hub's admin.token)"), 1;
|
|
331
334
|
try {
|
|
332
335
|
const codes = await pendingCodes(origin, hub.token, f);
|
|
333
336
|
if (!codes.length) {
|
|
@@ -339,25 +342,25 @@ async function pairList(deps: PairCliDeps, hubArg?: string, watch = false): Prom
|
|
|
339
342
|
for (const c of codes) printPending(c, print);
|
|
340
343
|
return 0;
|
|
341
344
|
} catch (error) {
|
|
342
|
-
|
|
345
|
+
printErr(`list failed: ${(error as Error).message}`);
|
|
343
346
|
return 1;
|
|
344
347
|
}
|
|
345
348
|
}
|
|
346
349
|
|
|
347
350
|
async function pairApprove(deps: PairCliDeps, target?: string, hubArg?: string): Promise<number> {
|
|
348
|
-
const { env, fetch: f, print } = io(deps);
|
|
351
|
+
const { env, fetch: f, print, printErr } = io(deps);
|
|
349
352
|
const hub = hubTarget(env, deps.hubHome);
|
|
350
353
|
const origin = hubArg ?? hub.origin;
|
|
351
|
-
if (!origin) return
|
|
352
|
-
if (!hub.token) return
|
|
353
|
-
if (!target) return
|
|
354
|
+
if (!origin) return printErr("approve needs --hub <origin> (or DPI_HUB_URL)"), 1;
|
|
355
|
+
if (!hub.token) return printErr("approve needs the hub admin token (DPI_ADMIN_TOKEN or the hub's admin.token)"), 1;
|
|
356
|
+
if (!target) return printErr("approve needs a machine name or code id (see: dpi pair list)"), 1;
|
|
354
357
|
try {
|
|
355
358
|
const codes = await pendingCodes(origin, hub.token, f);
|
|
356
359
|
const code =
|
|
357
360
|
codes.find((c) => c.codeId === target) ??
|
|
358
361
|
codes.find((c) => (c.deviceName ?? "").toLowerCase() === target.toLowerCase());
|
|
359
362
|
if (!code) {
|
|
360
|
-
|
|
363
|
+
printErr(`nothing waiting matches “${target}” — run: dpi pair list`);
|
|
361
364
|
return 1;
|
|
362
365
|
}
|
|
363
366
|
// The approval body is the hub's own view of the request; the fingerprint is
|
|
@@ -378,18 +381,18 @@ async function pairApprove(deps: PairCliDeps, target?: string, hubArg?: string):
|
|
|
378
381
|
print(` fingerprint ${code.keyFingerprint ?? "?"}`);
|
|
379
382
|
return 0;
|
|
380
383
|
} catch (error) {
|
|
381
|
-
|
|
384
|
+
printErr(`approve failed: ${(error as Error).message}`);
|
|
382
385
|
return 1;
|
|
383
386
|
}
|
|
384
387
|
}
|
|
385
388
|
|
|
386
389
|
async function pairRevoke(deps: PairCliDeps, target?: string, hubArg?: string): Promise<number> {
|
|
387
|
-
const { env, fetch: f, print } = io(deps);
|
|
390
|
+
const { env, fetch: f, print, printErr } = io(deps);
|
|
388
391
|
const hub = hubTarget(env, deps.hubHome);
|
|
389
392
|
const origin = hubArg ?? hub.origin;
|
|
390
|
-
if (!origin) return
|
|
391
|
-
if (!hub.token) return
|
|
392
|
-
if (!target) return
|
|
393
|
+
if (!origin) return printErr("revoke needs --hub <origin> (or DPI_HUB_URL)"), 1;
|
|
394
|
+
if (!hub.token) return printErr("revoke needs the hub admin token (DPI_ADMIN_TOKEN or the hub's admin.token)"), 1;
|
|
395
|
+
if (!target) return printErr("revoke needs a device name or id (see: dpi devices)"), 1;
|
|
393
396
|
try {
|
|
394
397
|
const net = await jsonOrThrow(
|
|
395
398
|
await f(`${origin}/api/network`, { headers: { authorization: `Bearer ${hub.token}` } }),
|
|
@@ -399,7 +402,7 @@ async function pairRevoke(deps: PairCliDeps, target?: string, hubArg?: string):
|
|
|
399
402
|
const device =
|
|
400
403
|
devices.find((d) => d.id === target) ?? devices.find((d) => d.name.toLowerCase() === target.toLowerCase());
|
|
401
404
|
if (!device) {
|
|
402
|
-
|
|
405
|
+
printErr(`no device matches “${target}” — known: ${devices.map((d) => d.name).join(", ") || "none"}`);
|
|
403
406
|
return 1;
|
|
404
407
|
}
|
|
405
408
|
await jsonOrThrow(
|
|
@@ -413,7 +416,7 @@ async function pairRevoke(deps: PairCliDeps, target?: string, hubArg?: string):
|
|
|
413
416
|
print(`revoked ${device.name} — its next request will be refused`);
|
|
414
417
|
return 0;
|
|
415
418
|
} catch (error) {
|
|
416
|
-
|
|
419
|
+
printErr(`revoke failed: ${(error as Error).message}`);
|
|
417
420
|
return 1;
|
|
418
421
|
}
|
|
419
422
|
}
|
|
@@ -438,11 +441,11 @@ interface HubDevice {
|
|
|
438
441
|
|
|
439
442
|
/** `dpi devices [--watch]` — the paired machines and their live status. */
|
|
440
443
|
export async function listDevices(deps: PairCliDeps = {}, hubArg?: string, watch = false): Promise<number> {
|
|
441
|
-
const { env, fetch: f, print, sleep } = io(deps);
|
|
444
|
+
const { env, fetch: f, print, printErr, sleep } = io(deps);
|
|
442
445
|
const hub = hubTarget(env, deps.hubHome);
|
|
443
446
|
const origin = hubArg ?? hub.origin;
|
|
444
|
-
if (!origin) return
|
|
445
|
-
if (!hub.token) return
|
|
447
|
+
if (!origin) return printErr("devices needs --hub <origin> (or DPI_HUB_URL)"), 1;
|
|
448
|
+
if (!hub.token) return printErr("devices needs the hub admin token (DPI_ADMIN_TOKEN or the hub's admin.token)"), 1;
|
|
446
449
|
let previous = "";
|
|
447
450
|
for (;;) {
|
|
448
451
|
let devices: HubDevice[];
|
|
@@ -453,7 +456,7 @@ export async function listDevices(deps: PairCliDeps = {}, hubArg?: string, watch
|
|
|
453
456
|
);
|
|
454
457
|
devices = (net.devices ?? []) as HubDevice[];
|
|
455
458
|
} catch (error) {
|
|
456
|
-
|
|
459
|
+
printErr(`devices failed: ${(error as Error).message}`);
|
|
457
460
|
return 1;
|
|
458
461
|
}
|
|
459
462
|
const key = devices.map((d) => `${d.id}:${d.status ?? ""}`).join("|");
|
|
@@ -487,3 +490,13 @@ export const PAIR_USAGE = `dpi pair — pairing from the CLI (no browser needed)
|
|
|
487
490
|
Hub admin token: DPI_ADMIN_TOKEN, or the hub's admin.token (DPI_HOME).
|
|
488
491
|
Device token: DPI_TOKEN, or the device's backend.env (DPI_HOME).
|
|
489
492
|
`;
|
|
493
|
+
|
|
494
|
+
export const DEVICES_USAGE = `dpi devices — the paired machines and their live status
|
|
495
|
+
|
|
496
|
+
dpi devices [--hub <origin>] [--watch]
|
|
497
|
+
|
|
498
|
+
--hub <origin> the hub to ask (default: DPI_HUB_URL)
|
|
499
|
+
--watch keep watching: reprint only when a machine or its status changes
|
|
500
|
+
|
|
501
|
+
Needs the hub admin token: DPI_ADMIN_TOKEN, or the hub's admin.token (DPI_HOME).
|
|
502
|
+
`;
|
|
@@ -10,7 +10,7 @@ import type { DevicePairing } from "./pairing.js";
|
|
|
10
10
|
|
|
11
11
|
type Async = (req: Request, res: Response) => Promise<unknown>;
|
|
12
12
|
const route = (fn: Async) => (req: Request, res: Response, next: NextFunction) => fn(req, res).catch(next);
|
|
13
|
-
import { gitOp, gitStatus, gitStatusBatch, type GitOp } from "./git.ts";
|
|
13
|
+
import { gitOp, gitStatus, gitStatusBatch, isNotARepoError, type GitOp } from "./git.ts";
|
|
14
14
|
const GIT_OPS: GitOp[] = ["diff", "log", "log-list", "fetch", "pull", "push", "switch", "branch", "commit", "stage", "unstage", "discard", "diff-file", "stash-push", "stash-pop", "compare", "merge-abort", "show-files", "ignore", "checkpoint", "checkpoints", "rewind", "resolve", "submodule-update", "pr-create", "pr-list", "pr-merge", "pr-checks", "pr-comment", "worktree-list", "worktree-add", "worktree-remove"];
|
|
15
15
|
|
|
16
16
|
interface Locals {
|
|
@@ -26,6 +26,16 @@ const int = (value: unknown, name: string) => {
|
|
|
26
26
|
return n;
|
|
27
27
|
};
|
|
28
28
|
|
|
29
|
+
/** A numeric query/body param: absent → fallback, non-integer or below min → 400,
|
|
30
|
+
* above max → clamped. `Number(query)` alone lets NaN reach SQLite and brick
|
|
31
|
+
* the session, so every limit/waitMs goes through here. */
|
|
32
|
+
const intArg = (raw: unknown, name: string, fallback: number, min: number, max: number) => {
|
|
33
|
+
if (raw === undefined || raw === null || raw === "") return fallback;
|
|
34
|
+
const n = Number(raw);
|
|
35
|
+
if (!Number.isInteger(n) || n < min) throw invalid(`${name} must be an integer from ${min} to ${max}`);
|
|
36
|
+
return Math.min(n, max);
|
|
37
|
+
};
|
|
38
|
+
|
|
29
39
|
export function v1(
|
|
30
40
|
store: Store,
|
|
31
41
|
pairing?: DevicePairing,
|
|
@@ -133,17 +143,43 @@ export function v1(
|
|
|
133
143
|
});
|
|
134
144
|
r.get("/fs/dirs", route(async (req, res) => res.json(await store.browse(String(req.query.path ?? "")))));
|
|
135
145
|
// Git, spoken by the device itself: status for the UIs, ops for the humans.
|
|
136
|
-
// The path must live under a start dir (same rule as every other fs route)
|
|
137
|
-
|
|
146
|
+
// The path must live under a start dir (same rule as every other fs route);
|
|
147
|
+
// an omitted path means the FIRST start dir, never the daemon's own cwd.
|
|
148
|
+
const gitPath = async (raw: unknown) => {
|
|
149
|
+
if (raw === undefined || raw === null) return store.firstStartDir();
|
|
150
|
+
if (typeof raw !== "string" || !raw.trim()) throw invalid("path must be a non-empty string");
|
|
151
|
+
return store.containedPath(raw);
|
|
152
|
+
};
|
|
153
|
+
/** A git failure answers 400 with a bounded message — never raw CLI usage
|
|
154
|
+
* text, never a 500 (B3). */
|
|
155
|
+
const gitFault = (e: unknown, path: string) =>
|
|
156
|
+
isNotARepoError(e)
|
|
157
|
+
? invalid(`not a git repository: ${path}`)
|
|
158
|
+
: invalid(String((e as Error)?.message ?? e).slice(0, 200));
|
|
159
|
+
r.get("/git/status", route(async (req, res) => {
|
|
160
|
+
const path = await gitPath(req.query.path);
|
|
161
|
+
try {
|
|
162
|
+
res.json(await gitStatus(path));
|
|
163
|
+
} catch (e) {
|
|
164
|
+
throw gitFault(e, path);
|
|
165
|
+
}
|
|
166
|
+
}));
|
|
138
167
|
r.post("/git/status-batch", route(async (req, res) => {
|
|
139
|
-
const
|
|
140
|
-
|
|
168
|
+
const raw: string[] = Array.isArray(req.body?.paths) ? req.body.paths.map(String).filter(Boolean).slice(0, 50) : [];
|
|
169
|
+
const paths = await Promise.all(raw.map((p) => store.containedPath(p)));
|
|
170
|
+
try {
|
|
171
|
+
res.json(await gitStatusBatch(paths));
|
|
172
|
+
} catch (e) {
|
|
173
|
+
throw gitFault(e, paths[0] ?? "");
|
|
174
|
+
}
|
|
141
175
|
}));
|
|
142
176
|
r.post("/git", route(async (req, res) => {
|
|
143
177
|
const body = req.body ?? {};
|
|
144
178
|
const op = String(body.op ?? "") as GitOp;
|
|
145
179
|
if (!GIT_OPS.includes(op)) throw invalid(`Unknown git op ${String(body.op ?? "")}`);
|
|
146
|
-
const
|
|
180
|
+
const path = await gitPath(body.path);
|
|
181
|
+
try {
|
|
182
|
+
const out = await gitOp(path, op, {
|
|
147
183
|
ref: body.ref,
|
|
148
184
|
branch: body.branch,
|
|
149
185
|
message: body.message,
|
|
@@ -160,8 +196,11 @@ export function v1(
|
|
|
160
196
|
method: body.method === "merge" ? "merge" : "squash",
|
|
161
197
|
body: typeof body.body === "string" ? body.body : undefined,
|
|
162
198
|
n: Number.isInteger(body.n) ? Number(body.n) : undefined,
|
|
163
|
-
|
|
164
|
-
|
|
199
|
+
});
|
|
200
|
+
res.json(out);
|
|
201
|
+
} catch (e) {
|
|
202
|
+
throw gitFault(e, path);
|
|
203
|
+
}
|
|
165
204
|
}));
|
|
166
205
|
r.get(
|
|
167
206
|
"/docs/:kind",
|
|
@@ -215,6 +254,8 @@ export function v1(
|
|
|
215
254
|
r.put("/device/pi-auth/:provider", route(async (req, res) => {
|
|
216
255
|
const body = req.body ?? {};
|
|
217
256
|
if (typeof body.key !== "string" || !body.key.trim()) throw invalid("key is required");
|
|
257
|
+
// Same bound as pi's own auth.json writer — a paste of the wrong buffer is a 400, not a 500.
|
|
258
|
+
if (body.key.length > 4096) throw invalid("key must be 1–4096 non-whitespace characters");
|
|
218
259
|
res.json(store.setPiApiKey(param(req, "provider"), body.key));
|
|
219
260
|
}));
|
|
220
261
|
r.delete("/device/pi-auth/:provider", route(async (req, res) => res.json(store.removePiApiKey(param(req, "provider")))));
|
|
@@ -222,8 +263,19 @@ export function v1(
|
|
|
222
263
|
// ---------------------------------------------------- notifications
|
|
223
264
|
// Outbound fan-out (webhook/ntfy). Configured here, delivered by the device.
|
|
224
265
|
r.get("/notify/sinks", (_req, res) => res.json({ sinks: store.notifySinkList() }));
|
|
225
|
-
|
|
226
|
-
|
|
266
|
+
// allowPrivateHosts (B5) is a per-request grant on top of the env default — strictly boolean.
|
|
267
|
+
const sinkBody = (body: unknown): Parameters<Store["createNotifySink"]>[0] => {
|
|
268
|
+
if (
|
|
269
|
+
body &&
|
|
270
|
+
typeof body === "object" &&
|
|
271
|
+
(body as { allowPrivateHosts?: unknown }).allowPrivateHosts !== undefined &&
|
|
272
|
+
typeof (body as { allowPrivateHosts?: unknown }).allowPrivateHosts !== "boolean"
|
|
273
|
+
)
|
|
274
|
+
throw invalid("allowPrivateHosts must be a boolean");
|
|
275
|
+
return (body ?? {}) as Parameters<Store["createNotifySink"]>[0];
|
|
276
|
+
};
|
|
277
|
+
r.post("/notify/sinks", route(async (req, res) => res.status(201).json(await store.createNotifySink(sinkBody(req.body)))));
|
|
278
|
+
r.patch("/notify/sinks/:id", route(async (req, res) => res.json(await store.updateNotifySink(param(req, "id"), sinkBody(req.body)))));
|
|
227
279
|
r.delete("/notify/sinks/:id", route(async (req, res) => res.json(await store.removeNotifySink(param(req, "id")))));
|
|
228
280
|
r.post("/notify/test", route(async (_req, res) => res.json({ results: await store.testNotifySinks() })));
|
|
229
281
|
|
|
@@ -290,7 +342,7 @@ export function v1(
|
|
|
290
342
|
if (!["live", "terminal"].includes(status)) throw invalid("status must be live or terminal");
|
|
291
343
|
const h = store.harness(L(res).row);
|
|
292
344
|
if (status === "live") return res.json(await store.liveTasks(h));
|
|
293
|
-
res.json(await store.tasks(h, status,
|
|
345
|
+
res.json(await store.tasks(h, status, intArg(req.query.limit, "limit", 20, 1, 5000)));
|
|
294
346
|
}),
|
|
295
347
|
);
|
|
296
348
|
r.post(
|
|
@@ -307,7 +359,7 @@ export function v1(
|
|
|
307
359
|
await store.settled(
|
|
308
360
|
store.harness(L(res).row),
|
|
309
361
|
int(req.params.id, "submission id"),
|
|
310
|
-
|
|
362
|
+
intArg(req.query.waitMs, "waitMs", 0, 0, 300_000),
|
|
311
363
|
closed.signal,
|
|
312
364
|
),
|
|
313
365
|
);
|
|
@@ -319,7 +371,13 @@ export function v1(
|
|
|
319
371
|
r.post(
|
|
320
372
|
"/sessions/:s/agents",
|
|
321
373
|
create,
|
|
322
|
-
route(async (req, res) =>
|
|
374
|
+
route(async (req, res) => {
|
|
375
|
+
// An agent is a deliberate act: a body with a name is required, so a
|
|
376
|
+
// mistyped request never spawns a default agent (B6).
|
|
377
|
+
const body = req.body ?? {};
|
|
378
|
+
if (typeof body.name !== "string" || !body.name.trim()) throw invalid("name is required");
|
|
379
|
+
res.status(201).json(await store.createAgent(L(res).row, body));
|
|
380
|
+
}),
|
|
323
381
|
);
|
|
324
382
|
const a = "/sessions/:s/agents/:a";
|
|
325
383
|
r.get(a, route(async (_req, res) => res.json(await store.agentDetail(L(res).row, L(res).c))));
|
|
@@ -336,7 +394,7 @@ export function v1(
|
|
|
336
394
|
route(async (req, res) => {
|
|
337
395
|
const scope = String(req.query.scope ?? "all");
|
|
338
396
|
if (scope === "active") return res.json({ items: await store.activeEntries(L(res).c) });
|
|
339
|
-
res.json(await store.entries(L(res).c, req.query.cursor as string | undefined,
|
|
397
|
+
res.json(await store.entries(L(res).c, req.query.cursor as string | undefined, intArg(req.query.limit, "limit", 500, 1, 5000)));
|
|
340
398
|
}),
|
|
341
399
|
);
|
|
342
400
|
r.get(`${a}/transcript`, route(async (req, res) => res.json(await store.transcript(L(res).c, String(req.query.format ?? "json")))));
|
|
@@ -345,7 +403,7 @@ export function v1(
|
|
|
345
403
|
route(async (req, res) => {
|
|
346
404
|
const { h, c } = L(res);
|
|
347
405
|
const submission = await store.send(c, req.body ?? {});
|
|
348
|
-
const waitMs =
|
|
406
|
+
const waitMs = intArg(req.body?.waitMs, "waitMs", 0, 0, 300_000);
|
|
349
407
|
if (!waitMs) return res.status(202).json({ submissionId: submission.id, status: "queued" });
|
|
350
408
|
const closed = new AbortController();
|
|
351
409
|
res.on("close", () => closed.abort());
|
|
@@ -74,7 +74,7 @@ import { NotifySinks, type DeliveryResult, type SinkInput, type SinkRecord } fro
|
|
|
74
74
|
import { zipSync, type ZipEntry } from "./zip.js";
|
|
75
75
|
import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
|
|
76
76
|
import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
|
|
77
|
-
import { join, dirname, relative, resolve } from "node:path";
|
|
77
|
+
import { join, dirname, relative, resolve, sep } from "node:path";
|
|
78
78
|
import { homedir, hostname, platform } from "node:os";
|
|
79
79
|
import { randomUUID } from "node:crypto";
|
|
80
80
|
import { createRequire } from "node:module";
|
|
@@ -698,6 +698,44 @@ export class Store {
|
|
|
698
698
|
|
|
699
699
|
// ------------------------------------------------------------ directories
|
|
700
700
|
|
|
701
|
+
/** Every start dir, realpathed (missing ones dropped): the containment roots
|
|
702
|
+
* for /fs/dirs and the git routes — symlinks cannot tunnel under them. */
|
|
703
|
+
async startDirRoots(): Promise<string[]> {
|
|
704
|
+
const roots: string[] = [];
|
|
705
|
+
for (const dir of this.startDirs) {
|
|
706
|
+
try {
|
|
707
|
+
roots.push(await realpath(dir));
|
|
708
|
+
} catch {}
|
|
709
|
+
}
|
|
710
|
+
return roots;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** A resolved path IS a start dir root or lives under one. */
|
|
714
|
+
private underRoots(candidate: string, roots: string[]): boolean {
|
|
715
|
+
return roots.some((root) => candidate === root || candidate.startsWith(root + sep) || candidate.startsWith(root + "/"));
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** A caller-supplied path that must stay inside the start dirs: `~` expands,
|
|
719
|
+
* symlinks resolve, and anything outside answers 400 `invalid`. A path that
|
|
720
|
+
* does not exist is judged lexically (git then reports "not a repository"). */
|
|
721
|
+
async containedPath(input: string): Promise<string> {
|
|
722
|
+
const expanded = input === "~" ? homedir() : input.startsWith("~/") ? join(homedir(), input.slice(2)) : input;
|
|
723
|
+
let candidate: string;
|
|
724
|
+
try {
|
|
725
|
+
candidate = await realpath(resolve(expanded));
|
|
726
|
+
} catch {
|
|
727
|
+
candidate = resolve(expanded);
|
|
728
|
+
}
|
|
729
|
+
if (!this.underRoots(candidate, await this.startDirRoots())) throw invalid("path must live under a start dir");
|
|
730
|
+
return candidate;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** The deterministic default when a git route gets no path: the first start
|
|
734
|
+
* dir — never the daemon's own cwd. */
|
|
735
|
+
async firstStartDir(): Promise<string> {
|
|
736
|
+
return (await this.startDirRoots())[0] ?? resolve(this.startDirs[0] ?? homedir());
|
|
737
|
+
}
|
|
738
|
+
|
|
701
739
|
async directories(): Promise<DirListing> {
|
|
702
740
|
const dirs: { name: string; path: string }[] = [];
|
|
703
741
|
for (const root of this.startDirs) {
|
|
@@ -718,6 +756,10 @@ export class Store {
|
|
|
718
756
|
} catch {
|
|
719
757
|
throw notFound(`Not a directory on ${this.name}: ${path}`);
|
|
720
758
|
}
|
|
759
|
+
// Containment: only the start dirs and their subdirectories are listable —
|
|
760
|
+
// `~` and ".." traversal count only when they land inside one.
|
|
761
|
+
const roots = await this.startDirRoots();
|
|
762
|
+
if (!this.underRoots(real, roots)) throw invalid("path must live under a start dir");
|
|
721
763
|
const dirs: { name: string; path: string }[] = [];
|
|
722
764
|
try {
|
|
723
765
|
for (const entry of await readdir(real, { withFileTypes: true })) {
|
|
@@ -728,7 +770,10 @@ export class Store {
|
|
|
728
770
|
throw new ApiFault("unavailable", `Cannot list ${real}: ${(e as Error).message}`);
|
|
729
771
|
}
|
|
730
772
|
dirs.sort((a, b) => a.name.localeCompare(b.name));
|
|
731
|
-
|
|
773
|
+
// Parent navigation clamps at the roots: a start dir's parent is outside
|
|
774
|
+
// and is never offered to the picker.
|
|
775
|
+
const up = dirname(real) !== real && this.underRoots(dirname(real), roots) ? dirname(real) : undefined;
|
|
776
|
+
return { path: real, parent: up, dirs: dirs.slice(0, 500) };
|
|
732
777
|
}
|
|
733
778
|
|
|
734
779
|
// ------------------------------------------------------------ sessions
|
|
@@ -801,14 +846,19 @@ export class Store {
|
|
|
801
846
|
return this.sinks.list().map((sink) => ({ ...sink, silencedUntil: recent.get(sink.id) ?? null }));
|
|
802
847
|
}
|
|
803
848
|
|
|
804
|
-
async createNotifySink(input: SinkInput): Promise<NotifySinkView> {
|
|
805
|
-
const sink =
|
|
849
|
+
async createNotifySink(input: SinkInput & { allowPrivateHosts?: boolean }): Promise<NotifySinkView> {
|
|
850
|
+
const { allowPrivateHosts, ...sink } = input;
|
|
851
|
+
const created = await this.sinks.create(sink, { allowPrivateHosts: allowPrivateHosts === true });
|
|
806
852
|
this.notify();
|
|
807
|
-
return { ...
|
|
853
|
+
return { ...created, silencedUntil: null };
|
|
808
854
|
}
|
|
809
855
|
|
|
810
|
-
async updateNotifySink(
|
|
811
|
-
|
|
856
|
+
async updateNotifySink(
|
|
857
|
+
id: string,
|
|
858
|
+
patch: Partial<SinkInput> & { enabled?: boolean; allowPrivateHosts?: boolean },
|
|
859
|
+
): Promise<NotifySinkView> {
|
|
860
|
+
const { allowPrivateHosts, ...rest } = patch;
|
|
861
|
+
const sink = await this.sinks.update(id, rest, { allowPrivateHosts: allowPrivateHosts === true });
|
|
812
862
|
this.notify();
|
|
813
863
|
return { ...sink, silencedUntil: null };
|
|
814
864
|
}
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
refreshDetail,
|
|
8
8
|
select,
|
|
9
9
|
selected,
|
|
10
|
+
sessionAgents,
|
|
10
11
|
sessionHandle,
|
|
11
12
|
showInspector,
|
|
12
13
|
ui,
|
|
@@ -50,9 +51,10 @@ export const commands: SlashCommand[] = [
|
|
|
50
51
|
description: "New agent in this workspace",
|
|
51
52
|
run: async (arg) => {
|
|
52
53
|
const t = need(selected.value, "workspace");
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
// The device API requires a name (B6); without an argument, number the new agent.
|
|
55
|
+
const created = await need(sessionHandle.value, "workspace").createAgent({
|
|
56
|
+
name: arg || `Agent ${sessionAgents.value.length + 1}`,
|
|
57
|
+
});
|
|
56
58
|
select({ ...t, agentId: created.id });
|
|
57
59
|
notify(`New agent ${created.name}.`);
|
|
58
60
|
},
|
|
@@ -193,7 +193,8 @@ async function action(node: TreeNode, name: string) {
|
|
|
193
193
|
if (node.type === "session") {
|
|
194
194
|
const s = node.session;
|
|
195
195
|
if (name === "new-agent") {
|
|
196
|
-
|
|
196
|
+
// The device API requires a name (B6); number the new agent from the tree.
|
|
197
|
+
const created = await attempt(() => client.session(s.id).createAgent({ name: `Agent ${s.agents.length + 1}` }));
|
|
197
198
|
if (created) {
|
|
198
199
|
select({ deviceId: device.id, sessionId: s.id, agentId: created.id });
|
|
199
200
|
notify("New agent. Same session, same shared App State.");
|
|
@@ -35,6 +35,9 @@ async function load() {
|
|
|
35
35
|
loading.value = false;
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
+
/** The empty state must wait for the first fetch: a tunnel first-hit can take
|
|
39
|
+
* seconds, and "No schedules yet." painted at ~11ms was a lie the real list
|
|
40
|
+
* replaced at ~4s. Same class as the modelsLoading fix (0.0.47). */
|
|
38
41
|
watch(deviceId, load, { immediate: true });
|
|
39
42
|
|
|
40
43
|
const when = (at: number | null) => {
|
|
@@ -168,7 +171,7 @@ async function save() {
|
|
|
168
171
|
</form>
|
|
169
172
|
|
|
170
173
|
<p v-if="!adding && !schedules.length && deviceId && !error" class="hint">
|
|
171
|
-
No schedules yet. Press + to add one.
|
|
174
|
+
{{ loading ? "Reading schedules…" : "No schedules yet. Press + to add one." }}
|
|
172
175
|
</p>
|
|
173
176
|
|
|
174
177
|
<ul v-if="schedules.length" class="schedule-list">
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
online,
|
|
14
14
|
select,
|
|
15
15
|
selected,
|
|
16
|
+
sessionAgents,
|
|
16
17
|
sessionHandle,
|
|
17
18
|
streamState,
|
|
18
19
|
ui,
|
|
@@ -61,7 +62,8 @@ async function newAgent() {
|
|
|
61
62
|
const t = selected.value;
|
|
62
63
|
if (!handle || !t || creatingAgent.value) return;
|
|
63
64
|
creatingAgent.value = true;
|
|
64
|
-
|
|
65
|
+
// The device API requires a name (B6); without a prompt, number the new agent.
|
|
66
|
+
const created = await attempt(() => handle.createAgent({ name: `Agent ${sessionAgents.value.length + 1}` }));
|
|
65
67
|
creatingAgent.value = false;
|
|
66
68
|
if (created) {
|
|
67
69
|
select({ ...t, agentId: created.id });
|
|
@@ -40,7 +40,31 @@ import {
|
|
|
40
40
|
HUB_BUFFER_BUDGET_BYTES,
|
|
41
41
|
} from "../../../../dpi-sdk/src/protocol/limits.js";
|
|
42
42
|
|
|
43
|
+
// Help must never boot the server: the flag parser below only knows value
|
|
44
|
+
// flags, so --help has to be answered here — before the registry opens, a
|
|
45
|
+
// token is minted or the listener binds.
|
|
46
|
+
const HUB_USAGE = `dpi hub — web UI + device tunnel server
|
|
47
|
+
|
|
48
|
+
Usage:
|
|
49
|
+
dpi hub [--port 4781] [--host 127.0.0.1] [--public-host <host>] [--dev]
|
|
50
|
+
|
|
51
|
+
--port N hub port (DPI_HUB_PORT, default 4781)
|
|
52
|
+
--host H interface to bind (DPI_HUB_HOST, default 127.0.0.1)
|
|
53
|
+
--public-host H browser-facing host when behind the TLS proxy
|
|
54
|
+
(DPI_HUB_PUBLIC_HOST; also turns on the require-TLS checks,
|
|
55
|
+
DPI_HUB_REQUIRE_TLS overrides either way)
|
|
56
|
+
--dev serve the web client from Vite instead of the built shell
|
|
57
|
+
(local development only)
|
|
58
|
+
|
|
59
|
+
Environment: DPI_HOME, DPI_HUB_PORT, DPI_HUB_HOST, DPI_HUB_PUBLIC_HOST,
|
|
60
|
+
DPI_HUB_ORIGIN, DPI_HUB_REQUIRE_TLS
|
|
61
|
+
`;
|
|
62
|
+
|
|
43
63
|
const args = process.argv.slice(2);
|
|
64
|
+
if (args.includes("--help") || args.includes("-h") || args[0] === "help") {
|
|
65
|
+
process.stdout.write(HUB_USAGE);
|
|
66
|
+
process.exit(0);
|
|
67
|
+
}
|
|
44
68
|
const option = (key: string, fallback: string) => {
|
|
45
69
|
const i = args.indexOf(key);
|
|
46
70
|
if (i < 0) return fallback;
|
package/apps/dpi-tui/src/app.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
ProcessTerminal,
|
|
9
9
|
TuiAltScreen,
|
|
10
10
|
matchesKey,
|
|
11
|
+
truncateToWidth,
|
|
11
12
|
type Component,
|
|
12
13
|
type OverlayHandle,
|
|
13
14
|
type TuiInputListenerResult,
|
|
@@ -83,19 +84,48 @@ export function slashSuggestions(
|
|
|
83
84
|
return names.length ? { names, prefix } : null;
|
|
84
85
|
}
|
|
85
86
|
|
|
87
|
+
// The palette mirrors the "slash" door: the 4 view switches first, then
|
|
88
|
+
// every command COMMANDS (commands.ts) knows — the same handler runs for both
|
|
89
|
+
// entrances, so behavior can never drift between them.
|
|
86
90
|
const PALETTE: { name: string; hint: string; run: (a: App) => void }[] = [
|
|
87
91
|
{ name: "herd", hint: "session dashboard", run: (a) => a.setView("herd") },
|
|
88
92
|
{ name: "network", hint: "devices and sessions", run: (a) => a.setView("network") },
|
|
89
93
|
{ name: "agent", hint: "back to the conversation", run: (a) => a.setView("agent") },
|
|
90
94
|
{ name: "log", hint: "device events", run: (a) => a.setView("log") },
|
|
91
95
|
{ name: "sessions", hint: "switch or create a session", run: (a) => void a.command("sessions") },
|
|
96
|
+
{ name: "agents", hint: "switch agent: roots, forks, subagents", run: (a) => void a.command("agents") },
|
|
92
97
|
{ name: "model", hint: "choose this agent's model", run: (a) => void a.command("model") },
|
|
98
|
+
{ name: "devices", hint: "switch device", run: (a) => void a.command("devices") },
|
|
99
|
+
{ name: "new", hint: "new agent in this session", run: (a) => void a.command("new") },
|
|
93
100
|
{ name: "fork", hint: "fork at the last reply", run: (a) => void a.command("fork") },
|
|
101
|
+
{ name: "thinking", hint: "set the thinking level", run: (a) => void a.command("thinking") },
|
|
94
102
|
{ name: "compact", hint: "summarize older context", run: (a) => void a.command("compact") },
|
|
103
|
+
{ name: "reset", hint: "start a fresh context", run: (a) => void a.command("reset") },
|
|
104
|
+
{ name: "name", hint: "rename this agent", run: (a) => void a.command("name") },
|
|
105
|
+
{ name: "tasks", hint: "live tasks in this session", run: (a) => void a.command("tasks") },
|
|
106
|
+
{ name: "git", hint: "git on the session's folder", run: (a) => void a.command("git") },
|
|
107
|
+
{ name: "help", hint: "keys and commands", run: (a) => void a.command("help") },
|
|
95
108
|
{ name: "pair", hint: "pair this device with a hub", run: (a) => void a.command("pair") },
|
|
96
109
|
{ name: "quit", hint: "exit (the agent keeps running)", run: (a) => a.exit() },
|
|
97
110
|
];
|
|
98
111
|
|
|
112
|
+
/** The palette's live filter — ONE predicate shared by the rendered list and
|
|
113
|
+
* enter, so what enter runs is always a row the filter actually showed
|
|
114
|
+
* (typing "device events" narrows to `log`; enter used to answer
|
|
115
|
+
* ◆ no command "device events"). */
|
|
116
|
+
const paletteRows = (query: string) =>
|
|
117
|
+
PALETTE.filter((p) => p.name.includes(query) || p.hint.includes(query));
|
|
118
|
+
|
|
119
|
+
/** Enter's deterministic pick: an exact name wins; otherwise the query must
|
|
120
|
+
* narrow the palette to exactly one row; anything wider (or empty) keeps the
|
|
121
|
+
* no-command toast rather than guessing which row was meant. */
|
|
122
|
+
const palettePick = (query: string) => {
|
|
123
|
+
const exact = PALETTE.find((p) => p.name === query);
|
|
124
|
+
if (exact) return exact;
|
|
125
|
+
const rows = paletteRows(query);
|
|
126
|
+
return rows.length === 1 ? rows[0] : undefined;
|
|
127
|
+
};
|
|
128
|
+
|
|
99
129
|
const newId = () => crypto.randomUUID();
|
|
100
130
|
const shellWord = (s: string) => (/^[\w.:@/~-]+$/.test(s) ? s : `'${s}'`);
|
|
101
131
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
@@ -599,6 +629,7 @@ export class App {
|
|
|
599
629
|
else if (data === "m") this.beginInput("message", "follow-up ❯ ");
|
|
600
630
|
else if (data === "]" || matchesKey(data, "tab")) this.cycleTab(1);
|
|
601
631
|
else if (data === "[" || matchesKey(data, "shift+tab")) this.cycleTab(-1);
|
|
632
|
+
else if (data === "t") this.cycleTab(1); // t = tabs, same walk as ]
|
|
602
633
|
else if (/^[1-9]$/.test(data)) this.jump(Number(data));
|
|
603
634
|
// No catch-all: a stray letter used to jump views or open the composer with
|
|
604
635
|
// itself as the first character. herdr and piggery both require an explicit
|
|
@@ -707,7 +738,7 @@ export class App {
|
|
|
707
738
|
this.cursor = 0;
|
|
708
739
|
this.notify(this.filter ? `filter: ${this.filter}` : "filter cleared");
|
|
709
740
|
} else if (input.kind === "palette") {
|
|
710
|
-
const cmd =
|
|
741
|
+
const cmd = palettePick(value.trim());
|
|
711
742
|
if (cmd) cmd.run(this);
|
|
712
743
|
else this.notify(`no command “${value.trim()}”`);
|
|
713
744
|
} else if (input.kind === "kill") {
|
|
@@ -1182,7 +1213,11 @@ export class App {
|
|
|
1182
1213
|
private logBody(w: number, h: number): string[] {
|
|
1183
1214
|
const rows = this.events.filter((e) => !this.filter || e.text.toLowerCase().includes(this.filter.toLowerCase()));
|
|
1184
1215
|
const lines = [c.muted(` ${this.events.length} events · this client`)];
|
|
1185
|
-
|
|
1216
|
+
// A committed filter persists here like the herd's `filter: X` line — a
|
|
1217
|
+
// transient toast alone read as "events vanished", not "events hidden".
|
|
1218
|
+
if (this.filter)
|
|
1219
|
+
lines.push(c.warn(` filter: ${this.filter} · ${rows.length}/${this.events.length} shown — esc clears`));
|
|
1220
|
+
const visible = h - lines.length;
|
|
1186
1221
|
for (const e of rows.slice(-visible)) lines.push(` ${c.muted(e.at)} ${c.accent(e.glyph)} ${c.text(e.text.slice(0, w - 18))}`);
|
|
1187
1222
|
return lines;
|
|
1188
1223
|
}
|
|
@@ -1243,7 +1278,7 @@ export class App {
|
|
|
1243
1278
|
|
|
1244
1279
|
private palettePanel(w: number, h: number): string[] {
|
|
1245
1280
|
const query = (this.input?.value ?? "").trim();
|
|
1246
|
-
const items =
|
|
1281
|
+
const items = paletteRows(query);
|
|
1247
1282
|
const width = Math.min(62, w - 4);
|
|
1248
1283
|
const height = Math.min(items.length + 2, h);
|
|
1249
1284
|
const x = Math.floor((w - width) / 2);
|
|
@@ -1259,9 +1294,9 @@ export class App {
|
|
|
1259
1294
|
const rows = [
|
|
1260
1295
|
`${c.accent("▲")} ${c.bold("dpi keymap (herdr template)")}`,
|
|
1261
1296
|
"",
|
|
1262
|
-
`${c.accent("j k ↑ ↓")} move/scroll ${c.accent("1-
|
|
1263
|
-
`${c.accent("↵")} open ${c.accent("g N L")}
|
|
1264
|
-
`${c.accent("[ ]")}
|
|
1297
|
+
`${c.accent("j k ↑ ↓")} move/scroll ${c.accent("1-4")} views: net/herd/agent/log`,
|
|
1298
|
+
`${c.accent("↵")} open ${c.accent("g N L")} same views, aliases`,
|
|
1299
|
+
`${c.accent("[ ] t")} agent tabs ${c.accent("m")} message (enter sends)`,
|
|
1265
1300
|
`${c.accent("esc")} back/interrupt ${c.accent("i")} interrupt ≠ kill`,
|
|
1266
1301
|
`${c.accent("F")} fork ${c.accent("c")} compact context`,
|
|
1267
1302
|
`${c.accent("y")} thinking level ${c.accent("x")} reset (y/n confirm)`,
|
|
@@ -1300,9 +1335,13 @@ export class App {
|
|
|
1300
1335
|
|
|
1301
1336
|
private panelLine(width: number, content: string, active: boolean): string {
|
|
1302
1337
|
const inner = width - 4;
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1338
|
+
// Visible-width clip + pad, not raw length: the theme's truecolor spans
|
|
1339
|
+
// add ~19 invisible raw chars each, so raw slicing ate the overlay's
|
|
1340
|
+
// right column at every width (help's "views: net/herd/agent/log" never
|
|
1341
|
+
// rendered). truncateToWidth counts ANSI-stripped columns, keeps the
|
|
1342
|
+
// spans, closes any cut style and pads to exactly `inner` — the line can
|
|
1343
|
+
// never exceed the panel. Same helper views.ts already trusts.
|
|
1344
|
+
const padded = truncateToWidth(content, inner, "", true);
|
|
1306
1345
|
return `${c.muted(box.v)} ${active ? c.inverse(padded) : padded} ${c.muted(box.v)}`;
|
|
1307
1346
|
}
|
|
1308
1347
|
|
|
@@ -1332,7 +1371,10 @@ function place(panel: string[], width: number, height: number, x: number, y: num
|
|
|
1332
1371
|
panel.forEach((line, index) => {
|
|
1333
1372
|
const row = y + index;
|
|
1334
1373
|
if (row < 0 || row >= height) return;
|
|
1335
|
-
|
|
1374
|
+
// Visible columns again: raw slicing could cut an escape mid-sequence and
|
|
1375
|
+
// drop the right border; truncateToWidth clips safely and pads the row
|
|
1376
|
+
// to exactly the screen width.
|
|
1377
|
+
out[row] = rep(" ", x) + truncateToWidth(line, Math.max(0, width - x), "", true);
|
|
1336
1378
|
});
|
|
1337
1379
|
return out;
|
|
1338
1380
|
}
|
|
@@ -133,7 +133,9 @@ export async function runCommand(app: App, text: string): Promise<boolean> {
|
|
|
133
133
|
break;
|
|
134
134
|
}
|
|
135
135
|
await app.run(async () => {
|
|
136
|
-
|
|
136
|
+
// The device API requires a name (B6); without an argument, number the new agent.
|
|
137
|
+
const name = arg || `Agent ${app.session.state.agents.length + 1}`;
|
|
138
|
+
const created = await app.client.session(app.sessionId!).createAgent({ name });
|
|
137
139
|
await app.attach(app.sessionId!, created.id);
|
|
138
140
|
app.flash(`New agent ${created.name}`);
|
|
139
141
|
});
|
|
@@ -150,7 +150,11 @@ export function renderHerd(
|
|
|
150
150
|
if (showAge) line += ` ${fit(c.muted(ageOf(s.createdAt)), cols.age)}`;
|
|
151
151
|
lines.push(atCursor && !selected ? c.inverse(fit(line, w)) : fit(line, w));
|
|
152
152
|
}
|
|
153
|
-
if (!rows.length &&
|
|
153
|
+
if (!rows.length && opts.filter) {
|
|
154
|
+
// A filter that matches nothing must say so: 0 rows alone reads as
|
|
155
|
+
// "the sessions vanished", not "your filter is hiding them".
|
|
156
|
+
lines.push("", ` ${c.muted(`no sessions match “${opts.filter}” — esc clears`)}`);
|
|
157
|
+
} else if (!rows.length) {
|
|
154
158
|
// herdr never shows a bare header over nothing: the empty state points at
|
|
155
159
|
// the next move instead of a wall of blank rows.
|
|
156
160
|
lines.push(
|
package/bin/dpi.mjs
CHANGED
|
@@ -25,8 +25,9 @@ const COMMANDS = {
|
|
|
25
25
|
const HELP = `dpi — Durable Pi (bare "dpi" opens the TUI)
|
|
26
26
|
|
|
27
27
|
Usage:
|
|
28
|
-
dpi hub [--port 4781] [--host 127.0.0.1] [--public-host <host>]
|
|
29
|
-
Web UI + device tunnel server (devices dial this).
|
|
28
|
+
dpi hub [--port 4781] [--host 127.0.0.1] [--public-host <host>] [--dev]
|
|
29
|
+
Web UI + device tunnel server (devices dial this). --dev serves the web
|
|
30
|
+
client straight from Vite instead of the built shell (local development).
|
|
30
31
|
dpi device run the device daemon (foreground)
|
|
31
32
|
dpi device start | stop | status background daemon without a terminal
|
|
32
33
|
dpi device install | uninstall OS service (systemd/launchd); Windows: no
|
|
@@ -35,6 +36,13 @@ Usage:
|
|
|
35
36
|
dpi pair --hub <origin> this machine asks the hub itself
|
|
36
37
|
dpi pair offer|list|approve|revoke operator side, from the CLI (dpi pair --help)
|
|
37
38
|
dpi devices [--watch] [--hub <origin>] paired machines + live status (CLI, no web)
|
|
39
|
+
dpi schedule [list|add|enable|disable|run|remove] scheduled sessions (dpi schedule --help)
|
|
40
|
+
dpi notify [list|add|enable|disable|remove|test] outbound notifications (dpi notify --help)
|
|
41
|
+
dpi gc --closed-before 30d [--dry-run|--yes] retention for archived sessions (dry-run default)
|
|
42
|
+
dpi backup [create|list|restore] whole-home snapshots (restore is plan-first)
|
|
43
|
+
dpi diagnostics [--out F] redacted bug-report bundle
|
|
44
|
+
dpi telegram status|bind|unbind|sessions Telegram chat bridge
|
|
45
|
+
dpi graph list|show|add|run|remove|archive|unarchive task-graph DAG (dpi graph --help)
|
|
38
46
|
dpi tui
|
|
39
47
|
Terminal admin client.
|
|
40
48
|
dpi doctor [--json] [--quiet]
|
|
@@ -42,7 +50,7 @@ Usage:
|
|
|
42
50
|
the default-model probe and the hub. Exit 1 when a check fails.
|
|
43
51
|
dpi help | dpi --help | dpi -h
|
|
44
52
|
dpi version | dpi --version | dpi -v
|
|
45
|
-
dpi update [--check]
|
|
53
|
+
dpi update | upgrade [--check]
|
|
46
54
|
--check compare the installed version with the registry, change nothing
|
|
47
55
|
(no flag) install the latest published version globally
|
|
48
56
|
|
|
@@ -124,6 +132,11 @@ if (command === "update" || command === "upgrade") {
|
|
|
124
132
|
process.argv = [process.argv[0], process.argv[1], ...commandRest];
|
|
125
133
|
const { register } = await loadTsx();
|
|
126
134
|
register();
|
|
135
|
+
if (commandRest.includes("--help") || commandRest.includes("-h")) {
|
|
136
|
+
const { DEVICES_USAGE } = await import("../apps/dpi-backend/src/pair-cli.ts");
|
|
137
|
+
process.stdout.write(DEVICES_USAGE);
|
|
138
|
+
process.exit(0);
|
|
139
|
+
}
|
|
127
140
|
const { listDevices } = await import("../apps/dpi-backend/src/pair-cli.ts");
|
|
128
141
|
const hubIdx = commandRest.indexOf("--hub");
|
|
129
142
|
process.exit(
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "my-durable",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.54",
|
|
4
4
|
"description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|