my-durable 0.0.42 → 0.0.44

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.
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Conversation shares (Wave 3 SHOULD of docs/host-project-checklist.md, the
3
+ * zcode conversation-share idea on top of our 1b export surface): the operator
4
+ * uploads a prepared transcript (title + per-agent markdown) and gets back a
5
+ * tokenized public URL. The token IS the capability — the page is public, so
6
+ * retention is explicit: every share expires (7 days by default), an expired
7
+ * share is refused and swept, and the admin API can kill one early.
8
+ *
9
+ * The hub never talks to devices for this: the shell (which already holds the
10
+ * tunnel credentials) fetches the transcripts and POSTs them here.
11
+ *
12
+ * Node builtins only; `now` and the fs go through injectable options so tests
13
+ * never sleep or touch the real filesystem.
14
+ */
15
+ import { randomBytes } from "node:crypto";
16
+ import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
17
+ import { join } from "node:path";
18
+
19
+ /** A shared transcript is read-only text; this is not a file drop. */
20
+ export const MAX_AGENTS = 20;
21
+ export const MAX_MARKDOWN_CHARS = 2 * 1024 * 1024;
22
+ export const MAX_TOTAL_CHARS = 8 * 1024 * 1024;
23
+ export const MAX_TITLE_CHARS = 200;
24
+ /** zcode decides retention per instance; we ship one honest default. */
25
+ export const DEFAULT_TTL_DAYS = 7;
26
+
27
+ export interface ShareAgent {
28
+ name: string;
29
+ markdown: string;
30
+ }
31
+
32
+ export interface ShareMeta {
33
+ token: string;
34
+ title: string;
35
+ createdAt: string;
36
+ expiresAt: string;
37
+ bytes: number;
38
+ }
39
+
40
+ export interface ShareDocument {
41
+ meta: ShareMeta;
42
+ agents: ShareAgent[];
43
+ }
44
+
45
+ export type ShareErrorCode = "invalid";
46
+
47
+ export class ShareError extends Error {
48
+ readonly code: ShareErrorCode;
49
+
50
+ constructor(message: string) {
51
+ super(message);
52
+ this.name = "ShareError";
53
+ this.code = "invalid";
54
+ }
55
+ }
56
+
57
+ export interface SharesIo {
58
+ mkdir(path: string, mode?: number): Promise<void>;
59
+ readdir(path: string): Promise<string[]>;
60
+ readFile(path: string): Promise<string>;
61
+ /** stat is optional: existence probes use readFile's failure instead. */
62
+ writeFile(path: string, data: string, mode?: number): Promise<void>;
63
+ rm(path: string, options: { recursive: boolean }): Promise<void>;
64
+ now(): number;
65
+ }
66
+
67
+ export const defaultSharesIo = (): SharesIo => ({
68
+ mkdir: async (p, mode) => {
69
+ await mkdir(p, { recursive: true, ...(mode ? { mode } : {}) });
70
+ },
71
+ readdir: (p) => readdir(p),
72
+ readFile: (p) => readFile(p, "utf8"),
73
+ writeFile: async (p, d, mode) => {
74
+ await writeFile(p, d, { mode: mode ?? 0o600 });
75
+ },
76
+ rm: async (p, o) => {
77
+ await rm(p, o);
78
+ },
79
+ now: () => Date.now(),
80
+ });
81
+
82
+ const invalid = (message: string) => new ShareError(message);
83
+
84
+ const isToken = (value: string) => /^[A-Za-z0-9_-]{20,32}$/.test(value);
85
+
86
+ export class Shares {
87
+ private constructor(
88
+ private readonly dir: string,
89
+ private readonly io: SharesIo,
90
+ private readonly ttlDays: number,
91
+ ) {}
92
+
93
+ static async open(dir: string, options: { io?: SharesIo; ttlDays?: number } = {}): Promise<Shares> {
94
+ const io = options.io ?? defaultSharesIo();
95
+ await io.mkdir(dir, 0o700);
96
+ return new Shares(dir, io, options.ttlDays ?? DEFAULT_TTL_DAYS);
97
+ }
98
+
99
+ /** Create a share. Expired siblings are swept first — creation is the idle-time GC. */
100
+ async create(input: { title: string; agents: ShareAgent[] }): Promise<ShareMeta> {
101
+ const title = input.title.trim();
102
+ if (!title) throw invalid("a title is required");
103
+ if (title.length > MAX_TITLE_CHARS) throw invalid(`the title is longer than ${MAX_TITLE_CHARS} characters`);
104
+ if (!Array.isArray(input.agents) || input.agents.length === 0) throw invalid("at least one agent transcript is required");
105
+ if (input.agents.length > MAX_AGENTS) throw invalid(`at most ${MAX_AGENTS} agent transcripts per share`);
106
+ let total = 0;
107
+ for (const agent of input.agents) {
108
+ if (!agent || typeof agent.name !== "string" || !agent.name.trim()) throw invalid("every transcript needs a name");
109
+ if (typeof agent.markdown !== "string") throw invalid(`the transcript for ${agent.name} is not text`);
110
+ if (agent.markdown.length > MAX_MARKDOWN_CHARS)
111
+ throw invalid(`the transcript for ${agent.name} is larger than ${MAX_MARKDOWN_CHARS} characters`);
112
+ total += agent.markdown.length;
113
+ }
114
+ if (total > MAX_TOTAL_CHARS) throw invalid(`the share is larger than ${MAX_TOTAL_CHARS} characters`);
115
+
116
+ await this.sweep();
117
+ const now = this.io.now();
118
+ const meta: ShareMeta = {
119
+ token: randomBytes(18).toString("base64url"),
120
+ title,
121
+ createdAt: new Date(now).toISOString(),
122
+ expiresAt: new Date(now + this.ttlDays * 24 * 3600_000).toISOString(),
123
+ bytes: total,
124
+ };
125
+ const target = join(this.dir, meta.token);
126
+ await this.io.mkdir(target, 0o700);
127
+ await this.io.writeFile(join(target, "meta.json"), `${JSON.stringify(meta, null, 2)}\n`, 0o600);
128
+ await this.io.writeFile(
129
+ join(target, "page.json"),
130
+ `${JSON.stringify({ agents: input.agents }, null, 2)}\n`,
131
+ 0o600,
132
+ );
133
+ return meta;
134
+ }
135
+
136
+ /** Read a live share. Expired or unknown → undefined (the page is public: never explain which). */
137
+ async get(token: string): Promise<ShareDocument | undefined> {
138
+ if (!isToken(token)) return undefined;
139
+ const target = join(this.dir, token);
140
+ try {
141
+ const [metaRaw, pageRaw] = await Promise.all([
142
+ this.io.readFile(join(target, "meta.json")),
143
+ this.io.readFile(join(target, "page.json")),
144
+ ]);
145
+ const meta = JSON.parse(metaRaw) as ShareMeta;
146
+ const page = JSON.parse(pageRaw) as { agents: ShareAgent[] };
147
+ if (Date.parse(meta.expiresAt) <= this.io.now()) {
148
+ await this.sweep();
149
+ return undefined;
150
+ }
151
+ return { meta, agents: page.agents };
152
+ } catch {
153
+ return undefined;
154
+ }
155
+ }
156
+
157
+ /** The admin list, newest first. */
158
+ async list(): Promise<ShareMeta[]> {
159
+ await this.sweep();
160
+ const out: ShareMeta[] = [];
161
+ for (const entry of await this.io.readdir(this.dir).catch(() => [])) {
162
+ if (!isToken(entry)) continue;
163
+ try {
164
+ out.push(JSON.parse(await this.io.readFile(join(this.dir, entry, "meta.json"))) as ShareMeta);
165
+ } catch {
166
+ /* a half-written dir is not the list's problem */
167
+ }
168
+ }
169
+ return out.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
170
+ }
171
+
172
+ /** Kill a share early (the "remove link" button). */
173
+ async remove(token: string): Promise<boolean> {
174
+ if (!isToken(token)) return false;
175
+ try {
176
+ await this.io.rm(join(this.dir, token), { recursive: true });
177
+ return true;
178
+ } catch {
179
+ return false;
180
+ }
181
+ }
182
+
183
+ /** Delete every expired share dir. Returns how many. */
184
+ async sweep(): Promise<number> {
185
+ let removed = 0;
186
+ for (const entry of await this.io.readdir(this.dir).catch(() => [])) {
187
+ if (!isToken(entry)) continue;
188
+ try {
189
+ const meta = JSON.parse(await this.io.readFile(join(this.dir, entry, "meta.json"))) as ShareMeta;
190
+ if (Date.parse(meta.expiresAt) <= this.io.now()) {
191
+ await this.io.rm(join(this.dir, entry), { recursive: true });
192
+ removed += 1;
193
+ }
194
+ } catch {
195
+ /* unreadable dir: leave it; rm-ing unknown junk is not sweep's job */
196
+ }
197
+ }
198
+ return removed;
199
+ }
200
+ }
201
+
202
+ // ------------------------------------------------------------ public page
203
+ // Rendered server-side: the share page is public and must not load the app
204
+ // shell (which holds credentials), any script, or any external asset.
205
+
206
+ const escapeHtml = (text: string) =>
207
+ text.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
208
+
209
+ const PAGE_STYLE = `:root{color-scheme:dark}body{margin:0;background:#16181d;color:#e6e6e6;font:16px/1.6 ui-sans-serif,system-ui,sans-serif}
210
+ main{max-width:52rem;margin:0 auto;padding:2rem 1rem}h1{font-size:1.3rem;margin:0 0 .25rem}
211
+ .meta{color:#9aa0aa;font-size:.85rem;margin-bottom:1.5rem}
212
+ details{border:1px solid #2a2d34;border-radius:10px;margin:.75rem 0;background:#1b1e24}
213
+ summary{padding:.6rem .9rem;cursor:pointer;font-weight:600}
214
+ pre{margin:0;padding:0 1rem 1rem;white-space:pre-wrap;word-break:break-word;font:13.5px/1.55 ui-monospace,monospace;color:#cfd3da}
215
+ footer{color:#7c828c;font-size:.8rem;margin-top:2rem}`;
216
+
217
+ /** The public share page: transcripts only, inline-styled, zero scripts. */
218
+ export function renderSharePage(doc: ShareDocument): string {
219
+ const agents = doc.agents
220
+ .map(
221
+ (agent, i) =>
222
+ `<details${i === 0 ? " open" : ""}><summary>${escapeHtml(agent.name)}</summary><pre>${escapeHtml(agent.markdown)}</pre></details>`,
223
+ )
224
+ .join("\n");
225
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
226
+ <title>${escapeHtml(doc.meta.title)}</title><style>${PAGE_STYLE}</style></head>
227
+ <body><main><h1>${escapeHtml(doc.meta.title)}</h1>
228
+ <p class="meta">Shared ${escapeHtml(doc.meta.createdAt.slice(0, 16).replace("T", " "))} · expires ${escapeHtml(doc.meta.expiresAt.slice(0, 16).replace("T", " "))} · read-only</p>
229
+ ${agents}
230
+ <footer>Shared from a durable-pi device. The link stops working when the share expires.</footer>
231
+ </main></body></html>`;
232
+ }
233
+
234
+ /** A public 404 that never says whether the token ever existed. */
235
+ export function renderShareNotFound(): string {
236
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
237
+ <title>No such share</title><style>${PAGE_STYLE}</style></head>
238
+ <body><main><h1>No such share</h1><p class="meta">The link is wrong, or the share expired.</p></main></body></html>`;
239
+ }
@@ -103,7 +103,10 @@ export interface DeviceInfo {
103
103
  storage: { dataDir: string; catalogPath: string; appStatePath: string };
104
104
  /** The checkout the backend runs from (repo root locally, `code_dir` on deployed devices). */
105
105
  codeDir?: string;
106
- capabilities: Array<"events" | "docs" | "demo" | "jobs">;
106
+ /** How this device holds the OS awake while sessions run: systemd idle-inhibit, caffeinate, or "none". */
107
+ keepAwake?: "inhibit" | "caffeinate" | "none";
108
+ /** Feature flags the hub/FE may key on ("keep-awake", "telegram"). */
109
+ capabilities: Array<"events" | "docs" | "demo" | "jobs" | "keep-awake" | "telegram">;
107
110
  /** Durable jobs any agent on this device can run (`POST .../demo/jobs` or the run_durable_job tool). */
108
111
  jobs?: JobDef[];
109
112
  }
package/bin/dpi.mjs CHANGED
@@ -7,6 +7,8 @@
7
7
  // dpi notify [list|add|enable|disable|remove|test] outbound notifications
8
8
  // dpi gc --closed-before 30d [--dry-run|--yes] retention (dry-run default)
9
9
  // dpi backup [create|list|restore] whole-home snapshots
10
+ // dpi diagnostics [--out F] redacted bug-report bundle
11
+ // telegram status|bind|unbind|sessions Telegram chat bridge
10
12
  // dpi doctor [--json] [--quiet] one-shot device health check
11
13
  // Every subcommand runs the TypeScript entry through tsx, so no build step is needed.
12
14
  import { access } from "node:fs/promises";
@@ -161,6 +163,20 @@ if (command === "update" || command === "upgrade") {
161
163
  register();
162
164
  const { gcCli } = await import("../apps/dpi-backend/src/gc-cli.ts");
163
165
  process.exit(await gcCli({ argv: commandRest }));
166
+ } else if (command === "telegram") {
167
+ // Chat bridge: bind a Telegram chat to a device session (token in the env
168
+ // file as DPI_TELEGRAM_TOKEN). The daemon owns the polling loop.
169
+ const { register } = await loadTsx();
170
+ register();
171
+ const { telegramCli } = await import("../apps/dpi-backend/src/telegram-cli.ts");
172
+ process.exit(await telegramCli({ argv: commandRest }));
173
+ } else if (command === "diagnostics") {
174
+ // One redacted zip for a bug report: versions, doctor, device/vitals/env,
175
+ // sessions/registries, log tail — every section fails independently.
176
+ const { register } = await loadTsx();
177
+ register();
178
+ const { diagnosticsCli } = await import("../apps/dpi-backend/src/diagnostics-cli.ts");
179
+ process.exit(await diagnosticsCli({ argv: commandRest }));
164
180
  } else if (command === "backup") {
165
181
  // Whole-home snapshots: create/list, restore is plan-first and refuses while
166
182
  // the daemon runs. Nothing is ever deleted — the old home becomes a .bak.
@@ -1,7 +1,7 @@
1
1
  # Host / Project / Device / Session Management Feature Checklist — orca / paseo / zcode / herdr / piggery → durable-pi
2
2
 
3
3
  Run: `team_20261024143910_47d06fe8b77400d4` · Steps: 01_explore (inventory) → 02_analyze (verify/correct) → 03_write (this file)
4
- Status: **Waves 1a+1b+2 ADOPTED IN FULL (0.0.42 — live-verified in production Chrome: bell+panel, usage chip+total row, transcript download, prompt library, bulk select bar, recent-cwds chips; Host vitals with real uptime/load/memory/disk, tunnel-routed session search, and a bundle zip that real `unzip` opens).** Wave 2 is now complete (env UI, backup/restore and per-project defaults shipped in 0.0.42). Remaining: Wave 3. Policy gates #1/#2/#4 are still open; #3 is implemented as manual-only GC (no defaults, no timer). Companion to `docs/git-ui-checklist.md` (CLOSED): that file covered the git panel; this one covers everything **around** the agent runtime — projects/workspaces, host/device management, session lifecycle, config/credentials, diagnostics, maintenance. Git-panel features are deliberately absent here. Every load-bearing citation below was re-read in the actual files during this run (see [Verification log](#verification-log)).
4
+ Status: **Waves 1a+1b+2 + Wave 3 (diagnostics, keep-awake, telegram, share) ADOPTED (0.0.44 — live-verified in production Chrome: bell+panel, usage chip+total row, transcript download, prompt library, bulk select bar, recent-cwds chips; Host vitals with real uptime/load/memory/disk, tunnel-routed session search, and a bundle zip that real `unzip` opens).** Wave 2 complete (0.0.42); Wave 3: diagnostics + keep-awake (0.0.43), telegram bridge + conversation share (0.0.44), ssh-interactivity and bulk-resume closed by design. Remaining Wave 3: task-graph DAG. Policy gates #1/#2/#4 are still open; #3 is implemented as manual-only GC (no defaults, no timer). Companion to `docs/git-ui-checklist.md` (CLOSED): that file covered the git panel; this one covers everything **around** the agent runtime — projects/workspaces, host/device management, session lifecycle, config/credentials, diagnostics, maintenance. Git-panel features are deliberately absent here. Every load-bearing citation below was re-read in the actual files during this run (see [Verification log](#verification-log)).
5
5
 
6
6
  ## Why this doc exists
7
7
 
@@ -148,13 +148,13 @@ None of them blocks Wave 1.
148
148
 
149
149
  | Tier | Feature | Source (path:line) | Ours | Adoption suggestion |
150
150
  |---|---|---|---|---|
151
- | MUST | Interactive SSH suite | orca `src/main/ssh/` (connection, `port-forwarding/`, `remote-exec/`, `sftp-upload.ts`; the orcad-* provisioning suite is 100+ files) | 🟡 (ssh exists as a device *kind* for transport) | smallest slice first: sftp browse with the `/fs/dirs` shape over ssh; shell/port-forward later |
152
- | SHOULD | Keep-awake during runs | orca `agent-awake-service.ts:53-97` (powerSaveBlocker, LinuxLidSleepAssertion, MacosSystemSleepAssertion, powerMonitor resume) | ❌ | device asserts no-sleep while any session is busy; electron-free needs a per-OS helper — cost it before committing |
153
- | SHOULD | Bulk resume-after-restart UX | orca `NativeChatResumeOnRestartModal.tsx` (+ bulk-progress test) | 🟡 (durability exists — sessions survive daemon restarts) | post-restart modal listing interrupted sessions + one-click reopen, per-session progress |
154
- | SHOULD | Telegram channel bridge | zcode `packages/services/src/bots/telegramChannelRuntime.ts` | ❌ | channel message → existing session inbox submission surface |
155
- | SHOULD | Conversation share | zcode `packages/services/src/conversation-share/` | ❌ | builds on the 1b export bundle; decide retention first |
151
+ | MUST | Interactive SSH suite | orca `src/main/ssh/` (connection, `port-forwarding/`, `remote-exec/`, `sftp-upload.ts`; the orcad-* provisioning suite is 100+ files) | ✅ by design (`0.0.43`) | leader decision: the WSS tunnel already IS our authenticated remote channel — browse (`/fs/dirs`), git, sessions/exec all run over it behind the rest allowlist (`rest-routes.ts`), and `kind: ssh` + `sshDriver` remain the *bring-up* transport for `just net up`. An ssh path into the hub would bypass the pairing/allowlist trust model, so it is deliberately not built |
152
+ | SHOULD | Keep-awake during runs | orca `agent-awake-service.ts:53-97` (powerSaveBlocker, LinuxLidSleepAssertion, MacosSystemSleepAssertion, powerMonitor resume) | ✅ (`0.0.43`) | `awake.ts` + store wiring on notify (1 s debounce, unref'd, never throws): systemd `--what=idle --mode=block` on Linux (verified live: a user MAY hold idle:block; sleep:block answers Access denied, so lid-close/root suspend deliberately still win), `caffeinate -i -s` on macOS, honest `none` elsewhere (`keepAwake` in deviceInfo + HostPanel row). Two live-caught bugs: `require()` in ESM killed the spawn silently, and the first proof missed because the turn finished before the check — held T+6/15/30 s, released at zero busy |
153
+ | SHOULD | Bulk resume-after-restart UX | orca `NativeChatResumeOnRestartModal.tsx` (+ bulk-progress test) | ✅ by durability (`0.0.43`) | pi-durable already does what orca's modal needs a click for: `TaskScheduler.open` turns surviving `running` tasks back to `pending` and `Harness.resume()` re-dispatches — the device's boot loop calls it for every session, so interrupted work continues with NO user action. A "list of interrupted sessions" modal would list work that already resumed itself |
154
+ | SHOULD | Telegram channel bridge | zcode `packages/services/src/bots/telegramChannelRuntime.ts` | ✅ (`0.0.44`) | `telegram.ts` (executor, 28 tests): long-poll loop with offset persisted BEFORE handling (a crash never re-handles), chat↔session binding via a 10-minute single-use `/start <code>` from `dpi telegram bind` (strangers are ignored silently), `/status /stop /session <prefix> /help`; plain text → the bound session's agent, the answer returns as a Telegram reply (120 s cap). Token `DPI_TELEGRAM_TOKEN` in the env file (the 0.0.42 env UI manages it). Live: a fake token made the REAL api.telegram.org answer 401 and the loop stopped itself with the right warning; capability `telegram` appears in deviceInfo only while the loop runs |
155
+ | SHOULD | Conversation share | zcode `packages/services/src/conversation-share/` | ✅ (`0.0.44`) | hub `shares.ts`: the shell uploads prepared transcripts (it holds the tunnel creds — the hub never talks to devices for this) and gets a tokenized PUBLIC link; **retention decided: 7-day expiry, swept on create/get/list, admin DELETE kills early** (the row demanded that decision up front). Public page is server-rendered, escaped, CSP `default-src 'none'; style-src 'unsafe-inline'`, zero scripts; junk/expired/deleted tokens all 404 identically. Live in Chrome: share button → confirm (says what "public" means) → link + expiry toast → page renders logged-out → admin delete → 404 |
156
156
  | SHOULD | Task-graph orchestration | paseo `packages/server/src/server/tasks/task-graph.ts` (+execution-order); zcode `task-groups/` | ❌ | multi-session DAG on top of durable jobs (run/check/approval already exist) |
157
- | SHOULD | Diagnostic bundle | orca `settings/PrivacyDiagnosticBundleControls.tsx` | ❌ | redacted zip: versions, healthz, tunnel diagnostics, recent audit denies |
157
+ | SHOULD | Diagnostic bundle | orca `settings/PrivacyDiagnosticBundleControls.tsx` | ✅ (`0.0.43`) | `dpi diagnostics` (executor module, 14 tests): 10-section 0600 zip — manifest, doctor, device/vitals/env, sessions/projects/schedules/notify, 400-line redacted `device.log` tail. Sections fail independently (a dead device still produces a bundle). `redact()` strips dpi_/Bearer/sk- shapes; verified on the LIVE device: 10/10 ok, **0 raw tokens in any entry**. Hub-side audit denies still not included (the device cannot read the hub's audit log — a hub-side bundle would be a separate feature) |
158
158
  | SHOULD | Crash reporting — **policy #1** | orca `crash-reporting/` | ❌ | opt-in only if adopted at all; leader decides privacy posture |
159
159
  | — (policy) | Writable provider credential store | orca `credentials/encrypted-api-key-file-store.ts` | ❌ (read-only by design, `pi-config.ts:10-11`) | **policy #2** — any write path needs an ownership decision over `~/.pi/agent/auth.json`; do not default |
160
160
  | — | Remote daemon deploy (orcad-style) | orca `ssh/orcad-ssh-provisioning.ts` + migration/cutover suite | 🟡 (`dpi device install` covers local) | only if the SSH suite lands and manual deploy still hurts; orcad is an entire subsystem |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.42",
3
+ "version": "0.0.44",
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": {