@phren/cli 0.3.28 → 0.3.31

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.
Files changed (65) hide show
  1. package/dist/bridge/agent-hooks.d.ts +5 -55
  2. package/dist/bridge/agent-hooks.js +22 -155
  3. package/dist/bridge/codex-servers.d.ts +12 -0
  4. package/dist/bridge/codex-servers.js +35 -3
  5. package/dist/bridge/codex-thread-origin.d.ts +12 -0
  6. package/dist/bridge/codex-thread-origin.js +31 -0
  7. package/dist/bridge/hand-off-queue.d.ts +16 -0
  8. package/dist/bridge/hand-off-queue.js +62 -19
  9. package/dist/bridge/hook-main.js +12 -2
  10. package/dist/bridge/prompt-deliveries.d.ts +99 -0
  11. package/dist/bridge/prompt-deliveries.js +327 -0
  12. package/dist/bridge/prompt-once.d.ts +2 -0
  13. package/dist/bridge/prompt-once.js +2 -0
  14. package/dist/bridge/resources.d.ts +21 -0
  15. package/dist/bridge/resources.js +58 -2
  16. package/dist/bridge/server-launch.js +2 -1
  17. package/dist/bridge/server-pane-routes.js +72 -34
  18. package/dist/bridge/server-routes.d.ts +1 -0
  19. package/dist/bridge/server-routes.js +34 -3
  20. package/dist/bridge/server-stream.js +4 -2
  21. package/dist/bridge/server.js +12 -3
  22. package/dist/bridge/simulators.d.ts +3 -1
  23. package/dist/bridge/simulators.js +40 -5
  24. package/dist/bridge/sudo.d.ts +1 -1
  25. package/dist/bridge/sudo.js +51 -17
  26. package/dist/bridge/task-routes.d.ts +282 -0
  27. package/dist/bridge/task-routes.js +162 -0
  28. package/dist/bridge/uploads.d.ts +4 -0
  29. package/dist/bridge/uploads.js +15 -0
  30. package/dist/bridge-hook.mjs +18218 -15566
  31. package/dist/cli/namespaces-store.js +32 -1
  32. package/dist/cli/namespaces-tasks.d.ts +1 -0
  33. package/dist/cli/namespaces-tasks.js +55 -4
  34. package/dist/cli/ops.d.ts +2 -1
  35. package/dist/cli/ops.js +20 -4
  36. package/dist/cli-registry.js +5 -4
  37. package/dist/data/task-contract.d.ts +75 -0
  38. package/dist/data/task-contract.js +161 -0
  39. package/dist/data/task-format.d.ts +20 -0
  40. package/dist/data/task-format.js +55 -0
  41. package/dist/data/task-metadata.d.ts +10 -0
  42. package/dist/data/task-metadata.js +24 -0
  43. package/dist/data/task-store-directory.d.ts +21 -0
  44. package/dist/data/task-store-directory.js +37 -0
  45. package/dist/data/tasks.d.ts +38 -2
  46. package/dist/data/tasks.js +221 -28
  47. package/dist/generated/memory-ui-graph.browser.js +328 -333
  48. package/dist/init/setup.js +2 -2
  49. package/dist/memory-ui-graph.runtime.js +328 -333
  50. package/dist/modules/registry.js +3 -3
  51. package/dist/shell/input.js +49 -4
  52. package/dist/shell/state-store.d.ts +1 -0
  53. package/dist/shell/state-store.js +2 -0
  54. package/dist/shell/view.js +19 -3
  55. package/dist/store-registry.d.ts +12 -1
  56. package/dist/store-registry.js +52 -4
  57. package/dist/sync/task-claim.d.ts +1 -0
  58. package/dist/sync/task-claim.js +8 -1
  59. package/dist/sync/task-merge.d.ts +0 -9
  60. package/dist/sync/task-merge.js +48 -1
  61. package/dist/tools/tasks.js +31 -18
  62. package/dist/ui/page.js +1 -0
  63. package/dist/ui/scripts.js +64 -5
  64. package/dist/ui/server.js +18 -0
  65. package/package.json +8 -8
@@ -1,7 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { EventEmitter } from "node:events";
4
- import { existsSync } from "node:fs";
4
+ import { existsSync, readlinkSync } from "node:fs";
5
5
  import { open, readdir, readFile, readlink, unlink } from "node:fs/promises";
6
6
  import { request } from "node:http";
7
7
  import path from "node:path";
@@ -107,6 +107,30 @@ export async function readProcess(pid) {
107
107
  if (!Number.isInteger(pid) || pid <= 1)
108
108
  return undefined;
109
109
  try {
110
+ if (process.platform === "linux") {
111
+ const base = `/proc/${pid}`;
112
+ const [status, stat, cmdline, env] = await Promise.all([
113
+ readFile(`${base}/status`, "utf8"),
114
+ readFile(`${base}/stat`, "utf8"),
115
+ readFile(`${base}/cmdline`, "utf8"),
116
+ readFile(`${base}/environ`, "utf8").catch(() => undefined),
117
+ ]);
118
+ const ppid = /^PPid:\s+(\d+)$/m.exec(status)?.[1];
119
+ const euid = /^Uid:\s+\d+\s+(\d+)/m.exec(status)?.[1];
120
+ const name = /^Name:\s+(.+)$/m.exec(status)?.[1];
121
+ // Field 22 is the process's start tick. The comm field can contain
122
+ // spaces or parentheses, so split only after its closing parenthesis.
123
+ const start = (value) => value.slice(value.lastIndexOf(")") + 2).trim().split(/\s+/)[19];
124
+ const started = start(stat);
125
+ if (!ppid || !euid || !name || !started || !/^\d+$/.test(started))
126
+ return undefined;
127
+ // Refuse a recycled pid rather than combining two process records.
128
+ if (start(await readFile(`${base}/stat`, "utf8")) !== started)
129
+ return undefined;
130
+ const argv = cmdline.split("\0").filter(Boolean);
131
+ return { ppid: Number(ppid), euid: Number(euid), name: path.basename(name), argv, line: argv.join(" "), started,
132
+ ...(env === undefined ? {} : { env: env.split("\0").filter(Boolean).map(item => item.split("=", 1)[0]) }) };
133
+ }
110
134
  const { stdout } = await exec("ps", ["-ww", "-o", "ppid=", "-o", "uid=", "-o", "comm=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 65_536 });
111
135
  const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(stdout.trim().split("\n")[0] ?? "");
112
136
  if (!match)
@@ -114,12 +138,8 @@ export async function readProcess(pid) {
114
138
  const args = await exec("ps", ["-ww", "-o", "args=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 65_536 });
115
139
  const line = args.stdout.trim();
116
140
  const started = (await exec("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 3_000, maxBuffer: 4_096 }).catch(() => ({ stdout: "" }))).stdout.trim();
117
- let argv = line.split(/\s+/).filter(Boolean), env;
118
- if (process.platform === "linux") {
119
- argv = await readFile(`/proc/${pid}/cmdline`, "utf8").then(text => text.split("\0").filter(Boolean)).catch(() => argv);
120
- env = await readFile(`/proc/${pid}/environ`, "utf8").then(text => text.split("\0").filter(Boolean).map(item => item.split("=", 1)[0])).catch(() => undefined);
121
- }
122
- return { ppid: Number(match[1]), euid: Number(match[2]), name: path.basename(match[3]), argv, line, ...(env ? { env } : {}), ...(started ? { started } : {}) };
141
+ const argv = line.split(/\s+/).filter(Boolean);
142
+ return { ppid: Number(match[1]), euid: Number(match[2]), name: path.basename(match[3]), argv, line, ...(started ? { started } : {}) };
123
143
  }
124
144
  catch {
125
145
  return undefined;
@@ -133,16 +153,30 @@ export async function stdoutReaders(pid, allowed) {
133
153
  const target = await readlink(`/proc/${pid}/fd/1`);
134
154
  if (!/^pipe:\[\d+\]$/.test(target))
135
155
  return "other";
136
- for (const entry of await readdir("/proc")) {
137
- const holder = Number(entry);
138
- if (!Number.isInteger(holder) || holder === pid || allowed.includes(holder))
139
- continue;
140
- const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
141
- for (const fd of fds)
142
- if (await readlink(`/proc/${holder}/fd/${fd}`).catch(() => "") === target)
143
- return "other";
144
- }
145
- return "sudo";
156
+ const holders = (await readdir("/proc")).map(Number)
157
+ .filter(holder => Number.isInteger(holder) && holder !== pid && !allowed.includes(holder));
158
+ let next = 0, other = false;
159
+ // Busy machines can have thousands of descriptors. Bound the process
160
+ // concurrency while checking every visible descriptor of each holder.
161
+ await Promise.all(Array.from({ length: Math.min(16, holders.length) }, async () => {
162
+ while (!other && next < holders.length) {
163
+ const holder = holders[next++];
164
+ const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
165
+ // procfs links are kernel metadata, without disk I/O. Reading a
166
+ // holder's links directly avoids thousands of thread-pool jobs;
167
+ // the directory awaits above still yield between holders.
168
+ for (const fd of fds) {
169
+ try {
170
+ if (readlinkSync(`/proc/${holder}/fd/${fd}`) === target) {
171
+ other = true;
172
+ break;
173
+ }
174
+ }
175
+ catch { /* The descriptor closed or its process exited. */ }
176
+ }
177
+ }
178
+ }));
179
+ return other ? "other" : "sudo";
146
180
  }
147
181
  // macOS: each pipe end has its own address, and `n->` names the other end.
148
182
  const own = await exec("lsof", ["-nP", "-a", "-p", String(pid), "-d", "1", "-F", "tdn"], { timeout: 5_000, maxBuffer: 65_536 });
@@ -0,0 +1,282 @@
1
+ import { z } from "zod";
2
+ import { type Json } from "./protocol.js";
3
+ export declare const taskUpdatesSchema: z.ZodObject<{
4
+ responsibility: z.ZodOptional<z.ZodEnum<{
5
+ agent: "agent";
6
+ human: "human";
7
+ }>>;
8
+ dependencies: z.ZodOptional<z.ZodArray<z.ZodObject<{
9
+ storeId: z.ZodString;
10
+ project: z.ZodString;
11
+ stableId: z.ZodString;
12
+ }, z.core.$strict>>>;
13
+ section: z.ZodOptional<z.ZodEnum<{
14
+ Active: "Active";
15
+ Done: "Done";
16
+ Queue: "Queue";
17
+ }>>;
18
+ }, z.core.$strict>;
19
+ /** Native clients discover portable identities without knowing filesystem paths
20
+ * or accidentally treating machine-local attachment IDs as dependency IDs. */
21
+ export declare function getTaskDirectoryRoute(base: string): Promise<{
22
+ ok: boolean;
23
+ version: number;
24
+ stores: {
25
+ id: string | null;
26
+ name: string;
27
+ role: import("../store-registry.js").StoreRole;
28
+ primary: boolean;
29
+ available: boolean;
30
+ identityReady: boolean;
31
+ ambiguous: boolean;
32
+ repositoryIdentity?: {
33
+ repository: string;
34
+ branch: string;
35
+ } | undefined;
36
+ writerSafety: {
37
+ version: 1;
38
+ metadataVersion: 1;
39
+ activation: "disabled" | "owner-acknowledged";
40
+ requiresCoordinatedAdoption: true;
41
+ legacyWritersFenced: false;
42
+ acknowledgedAt?: string | undefined;
43
+ } | null;
44
+ metadataWritable: boolean;
45
+ projects: string[];
46
+ }[];
47
+ }>;
48
+ export declare function getTaskRoute(base: string, url: URL): {
49
+ ok: boolean;
50
+ version: number;
51
+ storeId: string;
52
+ project: string;
53
+ revision: string | undefined;
54
+ writerSafety: {
55
+ version: 1;
56
+ metadataVersion: 1;
57
+ activation: "disabled" | "owner-acknowledged";
58
+ requiresCoordinatedAdoption: true;
59
+ legacyWritersFenced: false;
60
+ acknowledgedAt?: string | undefined;
61
+ };
62
+ metadataWritable: boolean;
63
+ counts: {
64
+ human: number;
65
+ agentReady: number;
66
+ agentWaitingOnHuman: number;
67
+ agentWaitingOnTask: number;
68
+ done: number;
69
+ };
70
+ items: {
71
+ [k: string]: {
72
+ responsibility: import("../data/task-contract.js").TaskResponsibility;
73
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
74
+ prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
75
+ identity: import("../data/task-contract.js").TaskDependency | null;
76
+ id: string;
77
+ stableId?: string;
78
+ identityAmbiguous?: boolean;
79
+ section: import("../data/tasks.js").TaskSection;
80
+ line: string;
81
+ checked: boolean;
82
+ priority?: "high" | "medium" | "low";
83
+ context?: string;
84
+ pinned?: boolean;
85
+ githubIssue?: number;
86
+ githubUrl?: string;
87
+ claim?: import("../data/tasks.js").TaskClaim;
88
+ rank?: number;
89
+ lastActivity?: string;
90
+ createdAt?: string;
91
+ sessionId?: string;
92
+ scope?: string;
93
+ childFindings?: string[];
94
+ speculative?: boolean;
95
+ parentFinding?: string;
96
+ dependencies?: import("../data/task-contract.js").TaskDependency[];
97
+ history?: import("../data/task-contract.js").TaskChange[];
98
+ taskContractRaw?: string;
99
+ taskContractRecords?: string[];
100
+ taskContractLines?: string[];
101
+ opaqueContinuationLines?: string[];
102
+ }[];
103
+ };
104
+ };
105
+ export declare function updateTaskRoute(base: string, input: unknown): {
106
+ ok: boolean;
107
+ version: number;
108
+ storeId: string;
109
+ project: string;
110
+ revision: string | undefined;
111
+ writerSafety: {
112
+ version: 1;
113
+ metadataVersion: 1;
114
+ activation: "disabled" | "owner-acknowledged";
115
+ requiresCoordinatedAdoption: true;
116
+ legacyWritersFenced: false;
117
+ acknowledgedAt?: string | undefined;
118
+ };
119
+ metadataWritable: boolean;
120
+ counts: {
121
+ human: number;
122
+ agentReady: number;
123
+ agentWaitingOnHuman: number;
124
+ agentWaitingOnTask: number;
125
+ done: number;
126
+ };
127
+ items: {
128
+ [k: string]: {
129
+ responsibility: import("../data/task-contract.js").TaskResponsibility;
130
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
131
+ prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
132
+ identity: import("../data/task-contract.js").TaskDependency | null;
133
+ id: string;
134
+ stableId?: string;
135
+ identityAmbiguous?: boolean;
136
+ section: import("../data/tasks.js").TaskSection;
137
+ line: string;
138
+ checked: boolean;
139
+ priority?: "high" | "medium" | "low";
140
+ context?: string;
141
+ pinned?: boolean;
142
+ githubIssue?: number;
143
+ githubUrl?: string;
144
+ claim?: import("../data/tasks.js").TaskClaim;
145
+ rank?: number;
146
+ lastActivity?: string;
147
+ createdAt?: string;
148
+ sessionId?: string;
149
+ scope?: string;
150
+ childFindings?: string[];
151
+ speculative?: boolean;
152
+ parentFinding?: string;
153
+ dependencies?: import("../data/task-contract.js").TaskDependency[];
154
+ history?: import("../data/task-contract.js").TaskChange[];
155
+ taskContractRaw?: string;
156
+ taskContractRecords?: string[];
157
+ taskContractLines?: string[];
158
+ opaqueContinuationLines?: string[];
159
+ }[];
160
+ };
161
+ };
162
+ /** One locked write: a Human task is never observable as Agent-ready. The
163
+ * client keeps one stable ID across uncertain replies; conflicts never recreate. */
164
+ export declare function createTaskRoute(base: string, input: unknown): {
165
+ ok: boolean;
166
+ version: number;
167
+ storeId: string;
168
+ project: string;
169
+ revision: string | undefined;
170
+ writerSafety: {
171
+ version: 1;
172
+ metadataVersion: 1;
173
+ activation: "disabled" | "owner-acknowledged";
174
+ requiresCoordinatedAdoption: true;
175
+ legacyWritersFenced: false;
176
+ acknowledgedAt?: string | undefined;
177
+ };
178
+ metadataWritable: boolean;
179
+ counts: {
180
+ human: number;
181
+ agentReady: number;
182
+ agentWaitingOnHuman: number;
183
+ agentWaitingOnTask: number;
184
+ done: number;
185
+ };
186
+ items: {
187
+ [k: string]: {
188
+ responsibility: import("../data/task-contract.js").TaskResponsibility;
189
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
190
+ prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
191
+ identity: import("../data/task-contract.js").TaskDependency | null;
192
+ id: string;
193
+ stableId?: string;
194
+ identityAmbiguous?: boolean;
195
+ section: import("../data/tasks.js").TaskSection;
196
+ line: string;
197
+ checked: boolean;
198
+ priority?: "high" | "medium" | "low";
199
+ context?: string;
200
+ pinned?: boolean;
201
+ githubIssue?: number;
202
+ githubUrl?: string;
203
+ claim?: import("../data/tasks.js").TaskClaim;
204
+ rank?: number;
205
+ lastActivity?: string;
206
+ createdAt?: string;
207
+ sessionId?: string;
208
+ scope?: string;
209
+ childFindings?: string[];
210
+ speculative?: boolean;
211
+ parentFinding?: string;
212
+ dependencies?: import("../data/task-contract.js").TaskDependency[];
213
+ history?: import("../data/task-contract.js").TaskChange[];
214
+ taskContractRaw?: string;
215
+ taskContractRecords?: string[];
216
+ taskContractLines?: string[];
217
+ opaqueContinuationLines?: string[];
218
+ }[];
219
+ };
220
+ };
221
+ /** CAS applies the complete change set under the data layer's graph/document
222
+ * locks. Empty context clears it; omitted fields retain their current value. */
223
+ export declare function saveTaskRoute(base: string, input: unknown): {
224
+ ok: boolean;
225
+ version: number;
226
+ storeId: string;
227
+ project: string;
228
+ revision: string | undefined;
229
+ writerSafety: {
230
+ version: 1;
231
+ metadataVersion: 1;
232
+ activation: "disabled" | "owner-acknowledged";
233
+ requiresCoordinatedAdoption: true;
234
+ legacyWritersFenced: false;
235
+ acknowledgedAt?: string | undefined;
236
+ };
237
+ metadataWritable: boolean;
238
+ counts: {
239
+ human: number;
240
+ agentReady: number;
241
+ agentWaitingOnHuman: number;
242
+ agentWaitingOnTask: number;
243
+ done: number;
244
+ };
245
+ items: {
246
+ [k: string]: {
247
+ responsibility: import("../data/task-contract.js").TaskResponsibility;
248
+ readiness: "ready" | "waiting-on-human" | "waiting-on-task";
249
+ prerequisites: import("../data/task-contract.js").TaskPrerequisite[];
250
+ identity: import("../data/task-contract.js").TaskDependency | null;
251
+ id: string;
252
+ stableId?: string;
253
+ identityAmbiguous?: boolean;
254
+ section: import("../data/tasks.js").TaskSection;
255
+ line: string;
256
+ checked: boolean;
257
+ priority?: "high" | "medium" | "low";
258
+ context?: string;
259
+ pinned?: boolean;
260
+ githubIssue?: number;
261
+ githubUrl?: string;
262
+ claim?: import("../data/tasks.js").TaskClaim;
263
+ rank?: number;
264
+ lastActivity?: string;
265
+ createdAt?: string;
266
+ sessionId?: string;
267
+ scope?: string;
268
+ childFindings?: string[];
269
+ speculative?: boolean;
270
+ parentFinding?: string;
271
+ dependencies?: import("../data/task-contract.js").TaskDependency[];
272
+ history?: import("../data/task-contract.js").TaskChange[];
273
+ taskContractRaw?: string;
274
+ taskContractRecords?: string[];
275
+ taskContractLines?: string[];
276
+ opaqueContinuationLines?: string[];
277
+ }[];
278
+ };
279
+ };
280
+ /** The task and prompt are bound by a durable reservation, before invoking the
281
+ * ordinary launcher. Never roll back that claim after an uncertain side effect. */
282
+ export declare function launchTaskRoute(base: string, server: string, input: unknown): Promise<Json>;
@@ -0,0 +1,162 @@
1
+ import { z } from "zod";
2
+ import * as path from "node:path";
3
+ import { addTask, validTaskTitle, readTasks, updateTask, reserveTaskLaunch } from "../data/tasks.js";
4
+ import { taskView, taskCounts, filterTaskDoc, taskStores, taskStoreHasProject } from "../data/task-contract.js";
5
+ import { permissionDeniedError } from "../governance/rbac.js";
6
+ import { BridgeError, launchEfforts, PERMISSION_MODES } from "./protocol.js";
7
+ import { realpath, stat } from "node:fs/promises";
8
+ import { getProjectSourcePath } from "../project-config.js";
9
+ import { getMachineName } from "../machine-identity.js";
10
+ import { launchSession } from "./server-launch.js";
11
+ import { isAccountSlug } from "./claude-accounts.js";
12
+ import { taskStoreProjects, taskStoreRepositoryIdentity } from "../data/task-store-directory.js";
13
+ import { taskWriterSafety } from "../data/task-format.js";
14
+ export const taskUpdatesSchema = z.object({
15
+ responsibility: z.enum(["human", "agent"]).optional(),
16
+ dependencies: z.array(z.object({ storeId: z.string().regex(/^[a-f0-9]{8}$/), project: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/), stableId: z.string().regex(/^[a-f0-9]{8}$/) }).strict()).max(100).optional(),
17
+ section: z.enum(["Active", "Queue", "Done"]).optional(),
18
+ }).strict();
19
+ const revisionSchema = z.string().regex(/^[a-f0-9]{64}$/);
20
+ const identitySchema = z.object({ storeId: z.string().regex(/^[a-f0-9]{8}$/), project: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/), stableId: z.string().regex(/^[a-f0-9]{8}$/) });
21
+ function owner(base, id, write) {
22
+ const matches = taskStores(base).filter(s => s.taskStoreId === id && s.available !== false);
23
+ if (matches.length !== 1)
24
+ throw new BridgeError(404, "Task store is unavailable or ambiguous.");
25
+ if (write && matches[0].role === "readonly")
26
+ throw new BridgeError(403, "Task store is read-only.");
27
+ return matches[0];
28
+ }
29
+ /** Native clients discover portable identities without knowing filesystem paths
30
+ * or accidentally treating machine-local attachment IDs as dependency IDs. */
31
+ export async function getTaskDirectoryRoute(base) {
32
+ const stores = taskStores(base);
33
+ return { ok: true, version: 1, stores: await Promise.all(stores.map(async (store) => {
34
+ const ambiguous = !!store.taskStoreId && stores.filter(s => s.taskStoreId === store.taskStoreId).length !== 1;
35
+ const identityReady = !!store.taskStoreId && !ambiguous;
36
+ const repositoryIdentity = store.available === false ? undefined : await taskStoreRepositoryIdentity(store.path);
37
+ const writerSafety = store.available === false ? null : taskWriterSafety(store.path);
38
+ return {
39
+ id: store.taskStoreId ?? null, name: store.name, role: store.role, primary: store.role === "primary", available: store.available !== false,
40
+ identityReady, ambiguous, ...(repositoryIdentity ? { repositoryIdentity } : {}),
41
+ writerSafety,
42
+ metadataWritable: identityReady && store.role !== "readonly" && !permissionDeniedError(store.path, "update_task") && writerSafety?.activation === "owner-acknowledged",
43
+ projects: taskStoreProjects(store),
44
+ };
45
+ })) };
46
+ }
47
+ export function getTaskRoute(base, url) {
48
+ const { storeId, project } = identitySchema.omit({ stableId: true }).parse(Object.fromEntries(url.searchParams));
49
+ const store = owner(base, storeId, false);
50
+ if (!taskStoreHasProject(store, project))
51
+ throw new BridgeError(404, "Project is not in that task store.");
52
+ const result = readTasks(store.path, project);
53
+ if (!result.ok)
54
+ throw new BridgeError(400, result.error);
55
+ if (path.resolve(result.data.path) !== path.join(path.resolve(store.path), project, "tasks.md"))
56
+ throw new BridgeError(404, "Project is not in that task store.");
57
+ const filter = z.object({ responsibility: z.enum(["human", "agent"]).optional(), readiness: z.enum(["ready", "waiting-on-human", "waiting-on-task"]).optional() }).parse(Object.fromEntries(url.searchParams));
58
+ const filtered = filterTaskDoc(base, result.data, filter);
59
+ const writerSafety = taskWriterSafety(store.path);
60
+ return { ok: true, version: 1, storeId, project, revision: result.data.revision, writerSafety, metadataWritable: store.role !== "readonly" && !permissionDeniedError(store.path, "update_task", project) && writerSafety.activation === "owner-acknowledged", counts: taskCounts(base, result.data), items: Object.fromEntries(Object.entries(filtered.items).map(([section, items]) => [section, items.map(i => taskView(base, result.data, i))])) };
61
+ }
62
+ export function updateTaskRoute(base, input) {
63
+ const data = identitySchema.extend({ updates: taskUpdatesSchema }).strict().parse(input);
64
+ const store = owner(base, data.storeId, true);
65
+ if (!taskStoreHasProject(store, data.project))
66
+ throw new BridgeError(404, "Project is not in that task store.");
67
+ const denied = permissionDeniedError(store.path, "update_task", data.project);
68
+ if (denied)
69
+ throw new BridgeError(403, denied);
70
+ const current = readTasks(store.path, data.project);
71
+ if (!current.ok || path.resolve(current.data.path) !== path.join(path.resolve(store.path), data.project, "tasks.md"))
72
+ throw new BridgeError(404, "Project is not in that task store.");
73
+ const result = updateTask(store.path, data.project, `bid:${data.stableId}`, data.updates, base);
74
+ if (!result.ok)
75
+ throw new BridgeError(400, result.error);
76
+ return getTaskRoute(base, new URL(`http://phren.local/v1/tasks?storeId=${data.storeId}&project=${data.project}`));
77
+ }
78
+ /** One locked write: a Human task is never observable as Agent-ready. The
79
+ * client keeps one stable ID across uncertain replies; conflicts never recreate. */
80
+ export function createTaskRoute(base, input) {
81
+ const data = identitySchema.extend({ text: z.string().min(1).max(16000).refine(validTaskTitle, "Task title must be one line without embedded task identities"),
82
+ responsibility: z.enum(["human", "agent"]) }).strict().parse(input);
83
+ const store = owner(base, data.storeId, true);
84
+ if (!taskStoreHasProject(store, data.project))
85
+ throw new BridgeError(404, "Project is not in that task store.");
86
+ for (const operation of ["add_task", "update_task"]) {
87
+ const denied = permissionDeniedError(store.path, operation, data.project);
88
+ if (denied)
89
+ throw new BridgeError(403, denied);
90
+ }
91
+ const current = readTasks(store.path, data.project);
92
+ if (!current.ok || path.resolve(current.data.path) !== path.join(path.resolve(store.path), data.project, "tasks.md"))
93
+ throw new BridgeError(404, "Project is not in that task store.");
94
+ const result = addTask(store.path, data.project, data.text, { stableId: data.stableId, responsibility: data.responsibility, graphRoot: base });
95
+ if (!result.ok)
96
+ throw new BridgeError(409, result.error);
97
+ return getTaskRoute(base, new URL(`http://phren.local/v1/tasks?storeId=${data.storeId}&project=${data.project}`));
98
+ }
99
+ /** CAS applies the complete change set under the data layer's graph/document
100
+ * locks. Empty context clears it; omitted fields retain their current value. */
101
+ export function saveTaskRoute(base, input) {
102
+ const data = identitySchema.extend({ expectedRevision: revisionSchema, updates: taskUpdatesSchema.extend({
103
+ text: z.string().min(1).max(16000).refine(validTaskTitle).optional(),
104
+ context: z.string().max(14000).refine(value => !/[\x00-\x1f\x7f]/.test(value)).optional(),
105
+ }).strict().refine(value => Object.keys(value).length > 0, "Supply at least one change.") }).strict().parse(input);
106
+ const store = writableTaskProject(base, data.storeId, data.project);
107
+ const result = updateTask(store.path, data.project, `bid:${data.stableId}`, { ...data.updates, replace_context: true }, base, data.expectedRevision);
108
+ if (!result.ok)
109
+ throw new BridgeError(409, result.error, { code: "task-save-conflict" });
110
+ return getTaskRoute(base, new URL(`http://phren.local/v1/tasks?storeId=${data.storeId}&project=${data.project}`));
111
+ }
112
+ function writableTaskProject(base, storeId, project) {
113
+ const store = owner(base, storeId, true);
114
+ if (!taskStoreHasProject(store, project))
115
+ throw new BridgeError(404, "Project is not in that task store.");
116
+ const denied = permissionDeniedError(store.path, "update_task", project);
117
+ if (denied)
118
+ throw new BridgeError(403, denied);
119
+ const current = readTasks(store.path, project);
120
+ if (!current.ok || path.resolve(current.data.path) !== path.join(path.resolve(store.path), project, "tasks.md"))
121
+ throw new BridgeError(404, "Project is not in that task store.");
122
+ if (taskWriterSafety(store.path).activation !== "owner-acknowledged")
123
+ throw new BridgeError(409, "Task metadata is not enabled.");
124
+ return store;
125
+ }
126
+ /** The task and prompt are bound by a durable reservation, before invoking the
127
+ * ordinary launcher. Never roll back that claim after an uncertain side effect. */
128
+ export async function launchTaskRoute(base, server, input) {
129
+ const data = identitySchema.extend({ expectedRevision: revisionSchema, kind: z.enum(["claude", "codex", "opencode"]),
130
+ model: z.string().min(1).max(200).refine(value => !/[\x00-\x1f\x7f]/.test(value)).optional(),
131
+ effort: z.enum(launchEfforts).optional(), account: z.string().refine(isAccountSlug).optional(),
132
+ permissionMode: z.enum(PERMISSION_MODES).optional(),
133
+ }).strict().parse(input);
134
+ if (data.kind === "opencode" && data.permissionMode !== undefined)
135
+ throw new BridgeError(400, "OpenCode takes permissions from its own config.");
136
+ const store = writableTaskProject(base, data.storeId, data.project);
137
+ // Resolve the selected store's configured checkout, never another store's
138
+ // same-named project or a caller-supplied path/prompt.
139
+ const configured = getProjectSourcePath(store.path, data.project);
140
+ const cwd = configured ? await realpath(configured).catch(() => undefined) : undefined;
141
+ if (!cwd || !(await stat(cwd)).isDirectory())
142
+ throw new BridgeError(409, "This task project has no configured checkout on this computer.");
143
+ // Async directory resolution must not leave stale store/rights admission.
144
+ const currentStore = writableTaskProject(base, data.storeId, data.project);
145
+ if (path.resolve(currentStore.path) !== path.resolve(store.path))
146
+ throw new BridgeError(409, "Task store changed; refresh before starting.");
147
+ const reserved = reserveTaskLaunch(store.path, data.project, data.stableId, data.expectedRevision, getMachineName(), base);
148
+ if (!reserved.ok)
149
+ throw new BridgeError(409, reserved.error, { code: "task-launch-conflict" });
150
+ const task = reserved.data;
151
+ const text = `Work on task ${task.identity.storeId}/${task.identity.project}/${task.identity.stableId}.\n\n${task.text}${task.context ? `\n\nContext: ${task.context}` : ""}`;
152
+ try {
153
+ const launched = await launchSession(server, { kind: data.kind, model: data.model, effort: data.effort, account: data.account,
154
+ permissionMode: data.permissionMode, role: "agent", cwd, label: task.text.slice(0, 200),
155
+ launchId: task.launchId, brief: { id: task.launchId, text } }, { trustFolder: true });
156
+ return { ...launched, task: task.identity, taskRevision: task.revision, launchId: task.launchId, claimPreserved: true,
157
+ state: launched.briefState === "sent" ? "started" : "uncertain" };
158
+ }
159
+ catch (error) {
160
+ throw new BridgeError(error instanceof BridgeError ? error.status : 503, "Task launch did not confirm success. Its reservation is preserved; review the worker and claim before retrying.", { ...(error instanceof BridgeError ? error.details : {}), code: "task-launch-uncertain", task: task.identity, launchId: task.launchId, claimPreserved: true });
161
+ }
162
+ }
@@ -10,6 +10,10 @@ export declare function listUploads(session: string): Promise<{
10
10
  size: number;
11
11
  modified: string;
12
12
  }[]>;
13
+ /** Removes one file the phone put in uploads/<session>/, by the path
14
+ * `listUploads` gave. Anything that does not resolve to a regular file
15
+ * directly inside that folder is 404, so no other file can be named. */
16
+ export declare function removeUpload(session: string, requested: string): Promise<void>;
13
17
  /** The bytes of one image the phone put under uploads/, by the absolute
14
18
  * path the transcript names. Served only when the path resolves (through
15
19
  * any link) to a regular file inside the uploads folder whose bytes are
@@ -61,6 +61,21 @@ export async function listUploads(session) {
61
61
  }
62
62
  return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
63
63
  }
64
+ /** Removes one file the phone put in uploads/<session>/, by the path
65
+ * `listUploads` gave. Anything that does not resolve to a regular file
66
+ * directly inside that folder is 404, so no other file can be named. */
67
+ export async function removeUpload(session, requested) {
68
+ const missing = new BridgeError(404, "This file is not one of the phone's uploads.");
69
+ if (!requested || requested.length > 4096 || !path.isAbsolute(requested))
70
+ throw missing;
71
+ const folder = await realpath(path.join(bridgeRoot(), "uploads", session)).catch(() => undefined);
72
+ const file = await realpath(requested).catch(() => undefined);
73
+ if (!folder || !file || path.dirname(file) !== folder)
74
+ throw missing;
75
+ if (!(await lstat(file)).isFile())
76
+ throw missing;
77
+ await unlink(file);
78
+ }
64
79
  /** The bytes of one image the phone put under uploads/, by the absolute
65
80
  * path the transcript names. Served only when the path resolves (through
66
81
  * any link) to a regular file inside the uploads folder whose bytes are