@phnx-labs/agents-cli 1.23.20 → 1.23.22

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 (180) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +17 -0
  3. package/dist/bootstrap.js +5 -4
  4. package/dist/cli/command-registry.js +2 -0
  5. package/dist/commands/config.js +16 -0
  6. package/dist/commands/daemon.js +3 -3
  7. package/dist/commands/doctor.js +10 -19
  8. package/dist/commands/events.js +1 -14
  9. package/dist/commands/feed-watch.js +5 -2
  10. package/dist/commands/go.js +2 -2
  11. package/dist/commands/lead.d.ts +3 -0
  12. package/dist/commands/lead.js +280 -0
  13. package/dist/commands/projects.js +3 -2
  14. package/dist/commands/ps-roster.d.ts +2 -12
  15. package/dist/commands/ps-roster.js +5 -87
  16. package/dist/commands/ps.js +3 -1
  17. package/dist/commands/repo.js +12 -12
  18. package/dist/commands/resource-view.js +5 -5
  19. package/dist/commands/sessions-browser.js +2 -2
  20. package/dist/commands/sessions-watch.js +5 -2
  21. package/dist/commands/setup-secrets.d.ts +3 -4
  22. package/dist/commands/setup-secrets.js +15 -46
  23. package/dist/commands/setup-session-backup.js +1 -1
  24. package/dist/commands/ssh.d.ts +0 -4
  25. package/dist/commands/ssh.js +14 -81
  26. package/dist/commands/teams-picker.js +1 -12
  27. package/dist/commands/teams.js +1 -13
  28. package/dist/commands/view.d.ts +1 -40
  29. package/dist/commands/view.js +9 -330
  30. package/dist/commands/watchdog.js +4 -4
  31. package/dist/index.js +4 -0
  32. package/dist/lib/accounting/usage.d.ts +0 -1
  33. package/dist/lib/accounting/usage.js +1 -112
  34. package/dist/lib/accounts/add.js +1 -1
  35. package/dist/lib/accounts/migrate.js +1 -1
  36. package/dist/lib/auto-pull-worker.js +2 -16
  37. package/dist/lib/auto-pull.d.ts +1 -0
  38. package/dist/lib/auto-pull.js +27 -0
  39. package/dist/lib/browser-client.js +2 -11
  40. package/dist/lib/cloud/codex.js +3 -0
  41. package/dist/lib/commands.d.ts +0 -6
  42. package/dist/lib/commands.js +3 -116
  43. package/dist/lib/comms-render.d.ts +1 -7
  44. package/dist/lib/comms-render.js +0 -19
  45. package/dist/lib/computer-client.js +2 -11
  46. package/dist/lib/config-keys.d.ts +7 -3
  47. package/dist/lib/config-keys.js +15 -2
  48. package/dist/lib/crabbox/runtimes.d.ts +0 -14
  49. package/dist/lib/crabbox/runtimes.js +0 -80
  50. package/dist/lib/daemon/attention-notify-service.d.ts +51 -28
  51. package/dist/lib/daemon/attention-notify-service.js +219 -53
  52. package/dist/lib/daemon/daemon.js +1 -2
  53. package/dist/lib/daemon/feed-stream-service.js +2 -4
  54. package/dist/lib/device-config.d.ts +0 -5
  55. package/dist/lib/device-config.js +20 -27
  56. package/dist/lib/devices/doctor-findings.d.ts +2 -1
  57. package/dist/lib/devices/doctor-findings.js +12 -1
  58. package/dist/lib/devices/fleet.d.ts +6 -0
  59. package/dist/lib/devices/fleet.js +15 -0
  60. package/dist/lib/devices/harness-inventory.d.ts +9 -0
  61. package/dist/lib/devices/harness-inventory.js +66 -0
  62. package/dist/lib/exec.js +1 -3
  63. package/dist/lib/feed/attention.d.ts +16 -1
  64. package/dist/lib/feed/attention.js +63 -1
  65. package/dist/lib/feed/feed.d.ts +1 -1
  66. package/dist/lib/feed/feed.js +12 -2
  67. package/dist/lib/feed/hub.d.ts +9 -0
  68. package/dist/lib/feed/hub.js +27 -1
  69. package/dist/lib/feed/notify-schedule.d.ts +16 -0
  70. package/dist/lib/feed/notify-schedule.js +62 -0
  71. package/dist/lib/feed/ticket-priority.d.ts +4 -0
  72. package/dist/lib/feed/ticket-priority.js +30 -0
  73. package/dist/lib/feed/watch.d.ts +1 -0
  74. package/dist/lib/feed/watch.js +27 -3
  75. package/dist/lib/feed-ranking.d.ts +1 -0
  76. package/dist/lib/feed-ranking.js +3 -1
  77. package/dist/lib/format.d.ts +0 -2
  78. package/dist/lib/format.js +0 -8
  79. package/dist/lib/github/open-prs.d.ts +0 -2
  80. package/dist/lib/github/open-prs.js +17 -35
  81. package/dist/lib/github/project-prs.d.ts +5 -0
  82. package/dist/lib/github/project-prs.js +73 -32
  83. package/dist/lib/helper-versions.js +1 -1
  84. package/dist/lib/hooks/cache.d.ts +1 -0
  85. package/dist/lib/hooks/cache.js +12 -1
  86. package/dist/lib/installations/duplicate-prune.d.ts +37 -0
  87. package/dist/lib/installations/duplicate-prune.js +85 -0
  88. package/dist/lib/installations/inventory-json.d.ts +20 -0
  89. package/dist/lib/installations/inventory-json.js +252 -0
  90. package/dist/lib/installations/shims.d.ts +0 -18
  91. package/dist/lib/installations/shims.js +1 -257
  92. package/dist/lib/lead/brief.d.ts +49 -0
  93. package/dist/lib/lead/brief.js +173 -0
  94. package/dist/lib/lead/client.d.ts +21 -0
  95. package/dist/lib/lead/client.js +167 -0
  96. package/dist/lib/lead/confirm.d.ts +22 -0
  97. package/dist/lib/lead/confirm.js +73 -0
  98. package/dist/lib/lead/events.d.ts +106 -0
  99. package/dist/lib/lead/events.js +188 -0
  100. package/dist/lib/lead/harness.d.ts +29 -0
  101. package/dist/lib/lead/harness.js +107 -0
  102. package/dist/lib/lead/host.d.ts +132 -0
  103. package/dist/lib/lead/host.js +675 -0
  104. package/dist/lib/lead/paths.d.ts +22 -0
  105. package/dist/lib/lead/paths.js +69 -0
  106. package/dist/lib/lead/refs.d.ts +17 -0
  107. package/dist/lib/lead/refs.js +75 -0
  108. package/dist/lib/lead/roster.d.ts +26 -0
  109. package/dist/lib/lead/roster.js +121 -0
  110. package/dist/lib/lead/shapes.d.ts +23 -0
  111. package/dist/lib/lead/shapes.js +95 -0
  112. package/dist/lib/lead/store.d.ts +46 -0
  113. package/dist/lib/lead/store.js +77 -0
  114. package/dist/lib/lead/tools.d.ts +18 -0
  115. package/dist/lib/lead/tools.js +106 -0
  116. package/dist/lib/lead/visibility.d.ts +16 -0
  117. package/dist/lib/lead/visibility.js +77 -0
  118. package/dist/lib/mailbox.d.ts +0 -18
  119. package/dist/lib/mailbox.js +0 -170
  120. package/dist/lib/menubar/notify-desktop.d.ts +5 -0
  121. package/dist/lib/menubar/notify-desktop.js +24 -0
  122. package/dist/lib/models.js +1 -19
  123. package/dist/lib/permissions.d.ts +0 -6
  124. package/dist/lib/permissions.js +0 -140
  125. package/dist/lib/platform/process.d.ts +1 -0
  126. package/dist/lib/platform/process.js +5 -0
  127. package/dist/lib/probe.js +13 -1
  128. package/dist/lib/project-status.js +4 -3
  129. package/dist/lib/projects.d.ts +9 -0
  130. package/dist/lib/projects.js +61 -3
  131. package/dist/lib/scheduling/routines.d.ts +1 -13
  132. package/dist/lib/scheduling/routines.js +1 -37
  133. package/dist/lib/secrets-cli.d.ts +3 -3
  134. package/dist/lib/secrets-cli.js +1 -1
  135. package/dist/lib/secrets-client.d.ts +4 -37
  136. package/dist/lib/secrets-client.js +19 -265
  137. package/dist/lib/session/active.d.ts +18 -8
  138. package/dist/lib/session/active.js +94 -18
  139. package/dist/lib/session/db.d.ts +0 -16
  140. package/dist/lib/session/db.js +1 -134
  141. package/dist/lib/session/detached.d.ts +0 -1
  142. package/dist/lib/session/detached.js +0 -18
  143. package/dist/lib/session/pending-work.d.ts +21 -0
  144. package/dist/lib/session/pending-work.js +284 -0
  145. package/dist/lib/session/remote/remote-list.d.ts +0 -3
  146. package/dist/lib/session/remote/remote-list.js +1 -23
  147. package/dist/lib/session/remote/watch.d.ts +5 -0
  148. package/dist/lib/session/remote/watch.js +19 -2
  149. package/dist/lib/session/session-cache.d.ts +1 -1
  150. package/dist/lib/session/session-cache.js +12 -5
  151. package/dist/lib/session/sync/provision.js +1 -2
  152. package/dist/lib/smart-launch.js +7 -2
  153. package/dist/lib/snapshot.js +3 -4
  154. package/dist/lib/ssh-exec.d.ts +0 -40
  155. package/dist/lib/ssh-exec.js +0 -108
  156. package/dist/lib/ssh-tunnel.d.ts +0 -6
  157. package/dist/lib/ssh-tunnel.js +0 -42
  158. package/dist/lib/standalone-tools.js +12 -1
  159. package/dist/lib/startup/command-registry.js +1 -1
  160. package/dist/lib/startup/spellcheck.d.ts +0 -1
  161. package/dist/lib/startup/spellcheck.js +1 -20
  162. package/dist/lib/state.d.ts +0 -6
  163. package/dist/lib/state.js +1 -14
  164. package/dist/lib/teams/delivery.d.ts +1 -0
  165. package/dist/lib/teams/delivery.js +13 -0
  166. package/dist/lib/types.d.ts +0 -37
  167. package/dist/lib/types.js +0 -9
  168. package/dist/lib/watchdog/log.d.ts +1 -1
  169. package/dist/lib/watchdog/log.js +6 -4
  170. package/package.json +2 -1
  171. package/dist/lib/artifact-actions.d.ts +0 -7
  172. package/dist/lib/artifact-actions.js +0 -39
  173. package/dist/lib/session/sync/managed-config.d.ts +0 -3
  174. package/dist/lib/session/sync/managed-config.js +0 -3
  175. package/dist/lib/session/sync/worker-template.d.ts +0 -1
  176. package/dist/lib/session/sync/worker-template.js +0 -807
  177. package/dist/lib/storage/selection.d.ts +0 -8
  178. package/dist/lib/storage/selection.js +0 -10
  179. package/dist/lib/watchdog/index.d.ts +0 -3
  180. package/dist/lib/watchdog/index.js +0 -3
@@ -1,807 +0,0 @@
1
- export function renderSessionsWorkerScript() {
2
- return `// GENERATED by agents setup session-backup — do not edit; edit
3
- // src/lib/session/sync/worker-template.ts and re-provision.
4
- export const hooks = {
5
- verifyPhoenixToken: defaultVerifyPhoenixToken,
6
- };
7
-
8
- // Free-tier limits for one owner's backup namespace. Product behavior lives in
9
- // code; secrets are bindings, quotas are not ambient deployment knobs.
10
- const PLAN = {
11
- maxBytes: 5 * 1024 * 1024 * 1024,
12
- maxObjects: 200000,
13
- maxPaths: 200000,
14
- maxFileBytes: 64 * 1024 * 1024,
15
- };
16
-
17
- export default {
18
- async fetch(request, env) {
19
- const url = new URL(request.url);
20
- let path;
21
- try {
22
- path = decodeURIComponent(url.pathname.replace(/^\\/+/, ''));
23
- } catch {
24
- return json({ error: 'malformed object path' }, 400);
25
- }
26
-
27
- if (!path) {
28
- return json({ error: 'unauthorized' }, 401);
29
- }
30
-
31
- if (request.method === 'PUT') {
32
- return handlePut(request, env, path);
33
- }
34
- if (request.method === 'GET' || request.method === 'HEAD') {
35
- return handleGet(request, env, path, url);
36
- }
37
- if (request.method === 'DELETE') {
38
- return handleDelete(request, env, path);
39
- }
40
- return json({ error: 'method not allowed' }, 405);
41
- },
42
- };
43
-
44
- // The reserved first-key-segment prefixes: owner-bearer only, never listed, and
45
- // never quota-charged/refunded (the ledger and the DEK are infrastructure, not
46
- // user payload).
47
- function isReservedRelKey(rel) {
48
- const first = rel.split('/').filter(Boolean)[0] || '';
49
- return first === '__usage' || first === '__key';
50
- }
51
-
52
- async function handlePut(request, env, path) {
53
- const auth = await authorizeWrite(request, env);
54
- if (auth.error) return auth.error;
55
-
56
- const segments = path.split('/').filter(Boolean);
57
- const owner = auth.owner;
58
- if (!owner || segments[0] !== owner) {
59
- return json({ error: 'namespace mismatch', owner: owner }, 403);
60
- }
61
- const rel = segments.slice(1).join('/');
62
- if (!rel) return json({ error: 'missing object key' }, 400);
63
-
64
- const reserved = isReservedRelKey(rel);
65
- const isEscrow = rel === '__key/backup-dek';
66
- if (reserved && !isEscrow) {
67
- return json({ error: 'reserved object key' }, 403);
68
- }
69
- const contentType = request.headers.get('content-type') || 'application/octet-stream';
70
-
71
- // Read the body bounded to the per-file cap so a streaming body can never OOM
72
- // the Worker or slip past the quota by lying about its length.
73
- const read = await readBodyBounded(request, PLAN.maxFileBytes);
74
- if (read.oversize) {
75
- return json({ error: 'file too large', maxBytes: PLAN.maxFileBytes }, 413);
76
- }
77
- const body = read.bytes;
78
-
79
- // The escrow key is immutable: all first-use devices conditionally create it,
80
- // then losers read the one winner before encrypting a transcript.
81
- if (isEscrow) {
82
- const created = await env.BUCKET.put(path, body, {
83
- httpMetadata: { contentType: contentType },
84
- customMetadata: { owner: owner, uploadedAt: new Date().toISOString() },
85
- onlyIf: { etagDoesNotMatch: '*' },
86
- });
87
- if (created === null) return json({ error: 'already exists', key: path }, 409);
88
- return json({ ok: true, key: path }, 200);
89
- }
90
-
91
- // Fail closed on a plaintext payload: a managed transcript bundle is always
92
- // client-side-encrypted (SES-51), so an unencrypted bundle here is an
93
- // older/buggy client and MUST be rejected before it lands readable.
94
- if (!isEncryptedManagedBundle(body)) {
95
- return json({ error: 'payload must be an encrypted bundle' }, 422);
96
- }
97
-
98
- // Reserve a bounded historical path slot BEFORE creating its persistent lease
99
- // or tombstone. Live-object count is refundable; internal state is not safely
100
- // garbage-collectable while an unbounded-duration predecessor may resume, so
101
- // this separate cap prevents create/delete churn from growing R2 forever.
102
- const pathId = await mutationPathId(path);
103
- const pathReservation = await reserveMutationPath(env, owner, pathId, PLAN);
104
- if (pathReservation instanceof Response) return pathReservation;
105
-
106
- const acquired = await acquireMutationLease(env, owner, path);
107
- if (acquired.error) return acquired.error;
108
- const lease = acquired.lease;
109
- try {
110
- // PUT and DELETE share this per-key lease. The operation record is durable
111
- // BEFORE its usage delta, so an expired successor can reconcile an
112
- // interrupted request from the actual object's mutationToken metadata.
113
- const physicalPrior = await env.BUCKET.head(path);
114
- const prior = physicalPrior && !isDeletedObject(physicalPrior) ? physicalPrior : null;
115
- const priorBytes = prior && typeof prior.size === 'number' ? prior.size : 0;
116
- const operation = {
117
- token: lease.token,
118
- kind: 'put',
119
- path: path,
120
- pathId: lease.pathId,
121
- generation: lease.generation,
122
- priorEtag: physicalPrior && physicalPrior.etag ? physicalPrior.etag : null,
123
- };
124
- if (!await setLeaseOperation(env, lease, operation)) {
125
- return json({ error: 'mutation lease contended, retry' }, 503);
126
- }
127
- const charge = await beginUsageMutation(env, owner, {
128
- operation: operation,
129
- fileBytes: body.byteLength,
130
- bytes: body.byteLength - priorBytes,
131
- count: prior ? 0 : 1,
132
- }, PLAN);
133
- if (charge instanceof Response) {
134
- await setLeaseOperation(env, lease, null);
135
- return charge;
136
- }
137
- // Renew/fence immediately before touching the object. A successor that
138
- // reclaimed an expired holder prevents this request from mutating state.
139
- if (!await setLeaseOperation(env, lease, operation)) {
140
- return json({ error: 'mutation lease lost; retry' }, 409);
141
- }
142
-
143
- const putOpts = {
144
- httpMetadata: { contentType: contentType },
145
- customMetadata: { owner: owner, uploadedAt: new Date().toISOString(), mutationToken: lease.token },
146
- onlyIf: physicalPrior && physicalPrior.etag
147
- ? { etagMatches: physicalPrior.etag }
148
- : { etagDoesNotMatch: '*' },
149
- };
150
- let stored;
151
- try {
152
- stored = await env.BUCKET.put(path, body, putOpts);
153
- } catch (err) {
154
- const reconciled = await reconcileUsageMutation(env, owner, operation);
155
- if (reconciled) await setLeaseOperation(env, lease, null);
156
- if (!reconciled) return json({ error: 'usage reconciliation contended, retry' }, 503);
157
- throw err;
158
- }
159
- if (stored === null) {
160
- const rolledBack = await finishUsageMutation(env, owner, operation, true);
161
- if (rolledBack) await setLeaseOperation(env, lease, null);
162
- if (!rolledBack) return json({ error: 'usage reconciliation contended, retry' }, 503);
163
- return json({ error: 'conflict', key: path }, 409);
164
- }
165
- const committed = await finishUsageMutation(env, owner, operation, false);
166
- if (committed) await setLeaseOperation(env, lease, null);
167
- if (!committed) return json({ error: 'usage reconciliation contended, retry' }, 503);
168
- } finally {
169
- await releaseMutationLease(env, lease);
170
- }
171
-
172
- const headers = new Headers();
173
- headers.set('content-type', 'application/json; charset=utf-8');
174
- headers.set('cache-control', 'private, no-store');
175
- return new Response(JSON.stringify({ ok: true, key: path }), { status: 200, headers });
176
- }
177
-
178
- async function handleGet(request, env, path, url) {
179
- const auth = await authorizeRead(request, env, path);
180
- if (auth.error) return auth.error;
181
-
182
- const segments = path.split('/').filter(Boolean);
183
- const owner = segments[0];
184
-
185
- // GET /<userId>/?list — enumerate this owner's keys (never the __ reserved
186
- // prefixes), each relative to <userId>/ so the CLI re-prepends inside its
187
- // client (BYO object layout stays identical).
188
- if (segments.length === 1 && url.searchParams.has('list')) {
189
- const keys = await listOwnerKeys(env, owner);
190
- const headers = new Headers();
191
- headers.set('content-type', 'application/json; charset=utf-8');
192
- headers.set('cache-control', 'private, no-store');
193
- return new Response(JSON.stringify({ keys: keys }), { status: 200, headers });
194
- }
195
-
196
- const object = await env.BUCKET.get(path);
197
- if (!object || isDeletedObject(object)) return json({ error: 'not found' }, 404);
198
-
199
- const headers = new Headers(object.httpMetadata ?? {});
200
- headers.set('cache-control', 'private, no-store');
201
- return new Response(request.method === 'HEAD' ? null : object.body, { headers });
202
- }
203
-
204
- async function handleDelete(request, env, path) {
205
- const auth = await authorizeWrite(request, env);
206
- if (auth.error) return auth.error;
207
-
208
- const segments = path.split('/').filter(Boolean);
209
- const owner = auth.owner;
210
- if (!owner || segments[0] !== owner) {
211
- return json({ error: 'namespace mismatch', owner: owner }, 403);
212
- }
213
- const rel = segments.slice(1).join('/');
214
- if (!rel) return json({ error: 'missing object key' }, 400);
215
-
216
- const reserved = isReservedRelKey(rel);
217
- if (reserved) {
218
- // Reserved infrastructure records are not user-deletable: deleting the
219
- // immutable escrow would orphan ciphertext on the next fresh-device mint.
220
- return json({ error: 'reserved object key' }, 403);
221
- }
222
- const beforeLease = await env.BUCKET.head(path);
223
- if (!beforeLease) return json({ ok: true, key: path }, 200);
224
- const pathId = await mutationPathId(path);
225
- const pathReservation = await reserveMutationPath(env, owner, pathId, PLAN);
226
- if (pathReservation instanceof Response) return pathReservation;
227
- if (isDeletedObject(beforeLease)) return json({ ok: true, key: path }, 200);
228
-
229
- const acquired = await acquireMutationLease(env, owner, path);
230
- if (acquired.error) return acquired.error;
231
- const lease = acquired.lease;
232
- try {
233
- const existing = await env.BUCKET.head(path);
234
- if (existing && !isDeletedObject(existing)) {
235
- const size = typeof existing.size === 'number' ? existing.size : 0;
236
- const operation = {
237
- token: lease.token,
238
- kind: 'delete',
239
- path: path,
240
- pathId: lease.pathId,
241
- generation: lease.generation,
242
- priorEtag: existing.etag || null,
243
- };
244
- if (!await setLeaseOperation(env, lease, operation)) {
245
- return json({ error: 'mutation lease contended, retry' }, 503);
246
- }
247
- const refund = await beginUsageMutation(env, owner, {
248
- operation: operation, bytes: -size, count: -1,
249
- }, PLAN);
250
- if (refund instanceof Response) {
251
- await setLeaseOperation(env, lease, null);
252
- return refund;
253
- }
254
- if (!await setLeaseOperation(env, lease, operation)) {
255
- return json({ error: 'mutation lease lost; retry' }, 409);
256
- }
257
- try {
258
- const deleted = await env.BUCKET.put(path, new Uint8Array(0), {
259
- httpMetadata: { contentType: 'application/x-agents-session-tombstone' },
260
- customMetadata: {
261
- owner: owner,
262
- deleted: 'true',
263
- mutationToken: lease.token,
264
- deletedAt: new Date().toISOString(),
265
- },
266
- onlyIf: { etagMatches: existing.etag },
267
- });
268
- if (deleted === null) {
269
- const reconciled = await reconcileUsageMutation(env, owner, operation);
270
- if (reconciled) await setLeaseOperation(env, lease, null);
271
- if (!reconciled) return json({ error: 'usage reconciliation contended, retry' }, 503);
272
- return json({ error: 'conflict', key: path }, 409);
273
- }
274
- } catch (err) {
275
- const reconciled = await reconcileUsageMutation(env, owner, operation);
276
- if (reconciled) await setLeaseOperation(env, lease, null);
277
- if (!reconciled) return json({ error: 'usage reconciliation contended, retry' }, 503);
278
- throw err;
279
- }
280
- const committed = await finishUsageMutation(env, owner, operation, false);
281
- if (committed) await setLeaseOperation(env, lease, null);
282
- if (!committed) return json({ error: 'usage reconciliation contended, retry' }, 503);
283
- }
284
- } finally {
285
- await releaseMutationLease(env, lease);
286
- }
287
-
288
- const headers = new Headers();
289
- headers.set('content-type', 'application/json; charset=utf-8');
290
- headers.set('cache-control', 'private, no-store');
291
- return new Response(JSON.stringify({ ok: true, key: path }), { status: 200, headers });
292
- }
293
-
294
- // Recoverable, storage-backed mutex shared by managed PUT and DELETE for one
295
- // object path. A released lease remains as a tiny internal record so release is
296
- // an etag-guarded PUT (never an unsafe unconditional delete). An expired holder
297
- // can be replaced, and its durable operation is reconciled before new work.
298
- const MUTATION_LEASE_MS = 60 * 1000;
299
-
300
- async function mutationPathId(path) {
301
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(path));
302
- return Array.from(new Uint8Array(digest)).map(function (b) { return b.toString(16).padStart(2, '0'); }).join('');
303
- }
304
-
305
- async function mutationLeaseKey(owner, path) {
306
- return '__mutation/' + owner + '/' + await mutationPathId(path);
307
- }
308
-
309
- async function readMutationLease(env, key) {
310
- const obj = await env.BUCKET.get(key);
311
- if (!obj) return null;
312
- let record = null;
313
- try {
314
- const parsed = JSON.parse(await obj.text());
315
- if (parsed && (parsed.v === 1 || parsed.v === 2) && typeof parsed.holder === 'string') record = parsed;
316
- } catch { /* malformed internal record is reclaimable */ }
317
- return { etag: obj.etag || null, record: record };
318
- }
319
-
320
- async function writeMutationLeaseCas(env, key, priorEtag, record) {
321
- const opts = { httpMetadata: { contentType: 'application/json' } };
322
- opts.onlyIf = priorEtag ? { etagMatches: priorEtag } : { etagDoesNotMatch: '*' };
323
- const stored = await env.BUCKET.put(key, JSON.stringify(record), opts);
324
- return stored !== null;
325
- }
326
-
327
- async function acquireMutationLease(env, owner, path) {
328
- const key = await mutationLeaseKey(owner, path);
329
- const pathId = key.slice(key.lastIndexOf('/') + 1);
330
- for (let attempt = 0; attempt < 6; attempt++) {
331
- const state = await readMutationLease(env, key);
332
- const now = Date.now();
333
- if (state && state.record && state.record.expiresAt > now) {
334
- return { error: json({ error: 'object mutation already in progress; retry' }, 409) };
335
- }
336
- const token = crypto.randomUUID();
337
- const generation = state && state.record && Number.isFinite(state.record.generation)
338
- ? state.record.generation + 1
339
- : 1;
340
- // Preserve an expired holder's operation in the replacement record. If this
341
- // Worker dies during recovery, the next successor still sees the same work.
342
- const record = {
343
- v: 2,
344
- generation: generation,
345
- holder: token,
346
- expiresAt: now + MUTATION_LEASE_MS,
347
- operation: state && state.record ? state.record.operation || null : null,
348
- };
349
- if (!await writeMutationLeaseCas(env, key, state && state.etag, record)) continue;
350
- const lease = { key: key, token: token, pathId: pathId, generation: generation };
351
- if (record.operation) {
352
- // Before settling an expired predecessor, invalidate the exact object etag
353
- // it was authorized to mutate. A predecessor that later resumes can no
354
- // longer PUT or DELETE the successor's object.
355
- const recovered = await fenceAndReconcileStaleMutation(env, owner, record.operation, token);
356
- if (!recovered || !await setLeaseOperation(env, lease, null)) {
357
- await releaseMutationLease(env, lease);
358
- return { error: json({ error: 'stale mutation reconciliation contended, retry' }, 503) };
359
- }
360
- }
361
- return { lease: lease };
362
- }
363
- return { error: json({ error: 'mutation lease contended, retry' }, 503) };
364
- }
365
-
366
- async function setLeaseOperation(env, lease, operation) {
367
- for (let attempt = 0; attempt < 6; attempt++) {
368
- const state = await readMutationLease(env, lease.key);
369
- if (!state || !state.record || state.record.holder !== lease.token) return false;
370
- const next = {
371
- v: 2,
372
- generation: lease.generation,
373
- holder: lease.token,
374
- expiresAt: Date.now() + MUTATION_LEASE_MS,
375
- operation: operation,
376
- };
377
- if (await writeMutationLeaseCas(env, lease.key, state.etag, next)) return true;
378
- }
379
- return false;
380
- }
381
-
382
- async function releaseMutationLease(env, lease) {
383
- for (let attempt = 0; attempt < 6; attempt++) {
384
- const state = await readMutationLease(env, lease.key);
385
- if (!state || !state.record || state.record.holder !== lease.token) return false;
386
- // Keep any unsettled operation recoverable, but make the lease immediately
387
- // acquirable. A normal completed request cleared operation first.
388
- const next = {
389
- v: 2,
390
- generation: lease.generation,
391
- holder: '',
392
- expiresAt: 0,
393
- operation: state.record.operation || null,
394
- };
395
- if (await writeMutationLeaseCas(env, lease.key, state.etag, next)) return true;
396
- }
397
- return false;
398
- }
399
-
400
- async function reconcileUsageMutation(env, owner, operation) {
401
- if (!validMutationOperation(operation)) return true;
402
- const current = await env.BUCKET.head(operation.path);
403
- return finishUsageMutation(env, owner, operation, !mutationApplied(current, operation));
404
- }
405
-
406
- function validMutationOperation(operation) {
407
- return !!operation
408
- && typeof operation.token === 'string'
409
- && typeof operation.path === 'string'
410
- && typeof operation.pathId === 'string'
411
- && Number.isFinite(operation.generation);
412
- }
413
-
414
- function mutationApplied(object, operation) {
415
- const tokenMatches = !!object && !!object.customMetadata
416
- && object.customMetadata.mutationToken === operation.token;
417
- return operation.kind === 'delete'
418
- ? tokenMatches && isDeletedObject(object)
419
- : tokenMatches && !isDeletedObject(object);
420
- }
421
-
422
- // Reclaim an expired predecessor safely. Its object mutation was conditional on
423
- // priorEtag, so we first change/create that physical object under the same etag
424
- // condition. Exactly one side wins: if the predecessor already won, its
425
- // mutationToken is visible and its quota delta commits; if this fence wins, the
426
- // predecessor's later conditional mutation must fail and its delta rolls back.
427
- async function fenceAndReconcileStaleMutation(env, owner, operation, successorToken) {
428
- if (!validMutationOperation(operation)) return true;
429
- for (let attempt = 0; attempt < 6; attempt++) {
430
- const current = await env.BUCKET.get(operation.path);
431
- if (mutationApplied(current, operation)) {
432
- return finishUsageMutation(env, owner, operation, false);
433
- }
434
-
435
- const priorEtag = typeof operation.priorEtag === 'string' ? operation.priorEtag : null;
436
- if (priorEtag && current && current.etag === priorEtag) {
437
- const bytes = new Uint8Array(await current.arrayBuffer());
438
- const metadata = Object.assign({}, current.customMetadata || {}, { fencedBy: successorToken });
439
- const fenced = await env.BUCKET.put(operation.path, bytes, {
440
- httpMetadata: current.httpMetadata || {},
441
- customMetadata: metadata,
442
- onlyIf: { etagMatches: current.etag },
443
- });
444
- if (fenced === null) continue;
445
- } else if (!priorEtag && !current) {
446
- const fenced = await env.BUCKET.put(operation.path, new Uint8Array(0), {
447
- httpMetadata: { contentType: 'application/x-agents-session-tombstone' },
448
- customMetadata: { owner: owner, deleted: 'true', fencedBy: successorToken },
449
- onlyIf: { etagDoesNotMatch: '*' },
450
- });
451
- if (fenced === null) continue;
452
- }
453
- // The prior etag is now absent, changed, or fenced by us. A late predecessor
454
- // cannot pass its object conditional. Persist its terminal generation in the
455
- // SAME CAS ledger that stores pending deltas before rolling back.
456
- return finishUsageMutation(env, owner, operation, true);
457
- }
458
- return false;
459
- }
460
-
461
- // Enumerate every stored key under <owner>/, EXCLUDING the reserved __ prefixes,
462
- // returning each stripped of the <owner>/ prefix. Paginates R2's cursor so a
463
- // large backup set lists completely.
464
- async function listOwnerKeys(env, owner) {
465
- const base = owner + '/';
466
- const out = [];
467
- let cursor = undefined;
468
- do {
469
- const listOpts = cursor
470
- ? { prefix: base, cursor: cursor, include: ['customMetadata'] }
471
- : { prefix: base, include: ['customMetadata'] };
472
- const listed = await env.BUCKET.list(listOpts);
473
- const objects = (listed && listed.objects) || [];
474
- for (const o of objects) {
475
- const key = o.key || '';
476
- if (!key.startsWith(base)) continue;
477
- const rel = key.slice(base.length);
478
- if (!rel || isReservedRelKey(rel) || isDeletedObject(o)) continue;
479
- out.push(rel);
480
- }
481
- cursor = listed && listed.truncated ? listed.cursor : undefined;
482
- } while (cursor);
483
- return out.sort();
484
- }
485
-
486
- function isDeletedObject(object) {
487
- return !!object && !!object.customMetadata && object.customMetadata.deleted === 'true';
488
- }
489
-
490
- // --- Per-user usage ledger (R2 conditional-put CAS), mirrored from agents-share.
491
- // A single object at __usage/<owner> holds
492
- // { bytes, count, pathCount, pending, settled } for one user. R2 has no atomic
493
- // increment, so mutations use read → mutate →
494
- // conditional-put (onlyIf.etagMatches). The __usage key is reserved:
495
- // owner-bearer only, never listed.
496
- function usageKey(owner) { return '__usage/' + owner; }
497
-
498
- function usageNumber(v, dflt) {
499
- const n = typeof v === 'number' ? v : parseFloat(v);
500
- return Number.isFinite(n) && n >= 0 ? n : dflt;
501
- }
502
-
503
- async function readUsage(env, owner) {
504
- const obj = await env.BUCKET.get(usageKey(owner));
505
- if (!obj) return { etag: null, usage: { bytes: 0, count: 0, pathCount: 0, pending: {}, settled: {} } };
506
- let usage = { bytes: 0, count: 0, pathCount: 0, pending: {}, settled: {} };
507
- try {
508
- const raw = typeof obj.text === 'function' ? await obj.text() : '';
509
- const parsed = JSON.parse(raw);
510
- if (parsed && typeof parsed === 'object') {
511
- const settled = parsed.settled && typeof parsed.settled === 'object' ? parsed.settled : {};
512
- usage = {
513
- bytes: usageNumber(parsed.bytes, 0),
514
- count: usageNumber(parsed.count, 0),
515
- pathCount: usageNumber(parsed.pathCount, Object.keys(settled).length),
516
- pending: parsed.pending && typeof parsed.pending === 'object' ? parsed.pending : {},
517
- settled: settled,
518
- };
519
- }
520
- } catch (e) {
521
- // Malformed ledger — treat as fresh zero but KEEP the etag so the next CAS
522
- // put overwrites the corrupt object rather than looping against it forever.
523
- }
524
- return { etag: obj.etag || null, usage: usage };
525
- }
526
-
527
- async function writeUsageCas(env, owner, prevEtag, usage) {
528
- if (usage.pending && Object.keys(usage.pending).length === 0) delete usage.pending;
529
- const body = JSON.stringify(usage);
530
- const opts = { httpMetadata: { contentType: 'application/json' } };
531
- if (prevEtag) {
532
- opts.onlyIf = { etagMatches: prevEtag };
533
- const res = await env.BUCKET.put(usageKey(owner), body, opts);
534
- return res !== null;
535
- }
536
- opts.onlyIf = { etagDoesNotMatch: '*' };
537
- const res = await env.BUCKET.put(usageKey(owner), body, opts);
538
- return res !== null;
539
- }
540
-
541
- // CAS retry loop. fn(usage) returns { reject: Response } to fail loud without
542
- // committing, or { commit: usage } to persist. On CAS contention it re-reads and
543
- // retries; exhausting the retries fails loud with 503.
544
- async function withUsage(env, owner, fn) {
545
- for (let attempt = 0; attempt < 6; attempt++) {
546
- const state = await readUsage(env, owner);
547
- const outcome = fn(state.usage);
548
- if (outcome.reject) return outcome.reject;
549
- if (outcome.skip) return null;
550
- const ok = await writeUsageCas(env, owner, state.etag, outcome.commit);
551
- if (ok) return null;
552
- }
553
- return json({ error: 'usage ledger contended, retry' }, 503);
554
- }
555
-
556
- // Permanently reserve one logical object-path hash in the quota ledger before
557
- // any persistent per-path state is created. DELETE refunds live bytes/count but
558
- // not this historical slot: tombstones, mutation leases, and settled generations
559
- // cannot be time-GCed safely because HTTP invocations have unbounded wall time.
560
- // The path cap therefore bounds every internal structure under adversarial churn.
561
- async function reserveMutationPath(env, owner, pathId, limits) {
562
- return withUsage(env, owner, function (usage) {
563
- usage.settled = usage.settled && typeof usage.settled === 'object' ? usage.settled : {};
564
- const hasPath = Object.prototype.hasOwnProperty.call(usage.settled, pathId);
565
- const derivedCount = Object.keys(usage.settled).length;
566
- const pathCount = usageNumber(usage.pathCount, derivedCount);
567
- if (hasPath) {
568
- if (usage.pathCount === pathCount) return { skip: true };
569
- usage.pathCount = pathCount;
570
- return { commit: usage };
571
- }
572
- if (pathCount + 1 > limits.maxPaths) {
573
- return { reject: json({ error: 'historical path limit reached', maxPaths: limits.maxPaths }, 413) };
574
- }
575
- usage.pathCount = pathCount + 1;
576
- usage.settled[pathId] = 0;
577
- return { commit: usage };
578
- });
579
- }
580
-
581
- // Apply one idempotent usage delta and retain it under pending[token] until the
582
- // corresponding object mutation commits or rolls back. A stale lease successor
583
- // can therefore finish an interrupted two-object transaction without guessing
584
- // whether the CAS ledger mutation landed.
585
- async function beginUsageMutation(env, owner, params, limits) {
586
- if (typeof params.fileBytes === 'number' && params.fileBytes > limits.maxFileBytes) {
587
- return json({ error: 'file too large', maxBytes: limits.maxFileBytes, gotBytes: params.fileBytes }, 413);
588
- }
589
- return withUsage(env, owner, function (usage) {
590
- const operation = params.operation;
591
- usage.pending = usage.pending && typeof usage.pending === 'object' ? usage.pending : {};
592
- usage.settled = usage.settled && typeof usage.settled === 'object' ? usage.settled : {};
593
- const settledGeneration = usageNumber(usage.settled[operation.pathId], 0);
594
- if (settledGeneration >= operation.generation) {
595
- return { reject: json({ error: 'mutation superseded; retry' }, 409) };
596
- }
597
- if (usage.pending[operation.token]) return { commit: usage };
598
- const requestedCount = typeof params.count === 'number' ? params.count : 0;
599
- const requestedBytes = typeof params.bytes === 'number' ? params.bytes : 0;
600
- if (usage.count + requestedCount > limits.maxObjects) {
601
- return { reject: json({ error: 'artifact limit reached', maxObjects: limits.maxObjects }, 413) };
602
- }
603
- if (usage.bytes + requestedBytes > limits.maxBytes) {
604
- return { reject: json({ error: 'storage limit reached', maxBytes: limits.maxBytes, usedBytes: usage.bytes }, 413) };
605
- }
606
- const nextBytes = Math.max(0, usage.bytes + requestedBytes);
607
- const nextCount = Math.max(0, usage.count + requestedCount);
608
- usage.pending[operation.token] = {
609
- bytes: nextBytes - usage.bytes,
610
- count: nextCount - usage.count,
611
- pathId: operation.pathId,
612
- generation: operation.generation,
613
- };
614
- usage.bytes = nextBytes;
615
- usage.count = nextCount;
616
- return { commit: usage };
617
- });
618
- }
619
-
620
- // Settle a pending delta and persist a bounded terminal generation for this
621
- // object path in the SAME CAS ledger. A late predecessor that read an older
622
- // ledger etag cannot add its delta after recovery: its CAS loses, then begin sees
623
- // settled[pathId] >= generation and refuses it. One entry per logical path keeps
624
- // this tombstone bounded independently of overwrite count.
625
- async function finishUsageMutation(env, owner, operation, rollback) {
626
- for (let attempt = 0; attempt < 6; attempt++) {
627
- const state = await readUsage(env, owner);
628
- state.usage.pending = state.usage.pending && typeof state.usage.pending === 'object'
629
- ? state.usage.pending
630
- : {};
631
- state.usage.settled = state.usage.settled && typeof state.usage.settled === 'object'
632
- ? state.usage.settled
633
- : {};
634
- const pending = state.usage.pending[operation.token];
635
- const priorSettled = usageNumber(state.usage.settled[operation.pathId], 0);
636
- if (!pending && priorSettled >= operation.generation) return true;
637
- if (rollback && pending) {
638
- const bytes = typeof pending.bytes === 'number' && Number.isFinite(pending.bytes) ? pending.bytes : 0;
639
- const count = typeof pending.count === 'number' && Number.isFinite(pending.count) ? pending.count : 0;
640
- state.usage.bytes = Math.max(0, state.usage.bytes - bytes);
641
- state.usage.count = Math.max(0, state.usage.count - count);
642
- }
643
- delete state.usage.pending[operation.token];
644
- state.usage.settled[operation.pathId] = Math.max(priorSettled, operation.generation);
645
- if (await writeUsageCas(env, owner, state.etag, state.usage)) return true;
646
- }
647
- return false;
648
- }
649
-
650
- // Read a request body fully into memory, BOUNDED: abort the moment it exceeds
651
- // maxBytes. Returns { oversize: true, size } once the cap is passed, else
652
- // { bytes, size } with the exact bytes.
653
- async function readBodyBounded(request, maxBytes) {
654
- if (!request.body || typeof request.body.getReader !== 'function') {
655
- const buf = await request.arrayBuffer();
656
- const bytes = new Uint8Array(buf);
657
- if (bytes.byteLength > maxBytes) return { oversize: true, size: bytes.byteLength };
658
- return { bytes: bytes, size: bytes.byteLength };
659
- }
660
- const reader = request.body.getReader();
661
- const chunks = [];
662
- let size = 0;
663
- while (true) {
664
- const step = await reader.read();
665
- if (step.done) break;
666
- const chunk = step.value;
667
- size += chunk.byteLength;
668
- if (size > maxBytes) {
669
- try { await reader.cancel(); } catch (e) { /* best-effort */ }
670
- return { oversize: true, size: size };
671
- }
672
- chunks.push(chunk);
673
- }
674
- const out = new Uint8Array(size);
675
- let offset = 0;
676
- for (let i = 0; i < chunks.length; i++) { out.set(chunks[i], offset); offset += chunks[i].byteLength; }
677
- return { bytes: out, size: size };
678
- }
679
-
680
- // Require a Phoenix bearer that owns the path prefix. No public GET, ever.
681
- // This managed store is Phoenix-only: there is no static-token principal. The
682
- // zero-knowledge BYO path talks to the operator's OWN R2 bucket directly through
683
- // the CLI's R2Client and never reaches this Worker, so a WRITE_TOKEN here would
684
- // be a Phoenix-and-quota bypass with no legitimate caller — it is deliberately
685
- // absent (PHNX-3726 fix-forward).
686
- async function authorizeRead(request, env, path) {
687
- const claims = await hooks.verifyPhoenixToken(request, env);
688
- if (!claims) {
689
- return { error: json({ error: 'unauthorized' }, 401) };
690
- }
691
- const ownerId = path.split('/').filter(Boolean)[0] || '';
692
- if (!ownerId || ownerId !== claims.userId) {
693
- return { error: json({ error: 'forbidden' }, 403) };
694
- }
695
- return { claims: claims, owner: claims.userId };
696
- }
697
-
698
- // The single write principal is a Phoenix bearer whose verified userId owns the
699
- // path prefix. 401 when it does not authenticate.
700
- async function authorizeWrite(request, env) {
701
- const claims = await hooks.verifyPhoenixToken(request, env);
702
- if (claims && typeof claims.userId === 'string' && claims.userId) {
703
- return { owner: claims.userId };
704
- }
705
- return { error: json({ error: 'unauthorized' }, 401) };
706
- }
707
-
708
- // A stored managed body MUST be an ENCRYPTED bundle — never plaintext (SES-51).
709
- // The upload wire is NDJSON: a header line then one record line per transcript
710
- // (serializeBundle). This Worker independently re-checks what the CLI already
711
- // fails-closed on before upload: the header claims encryption AND every record
712
- // body is a real AES-256-GCM transcript envelope (v/alg/iv/ct/tag), so an
713
- // older/buggy client's plaintext PUT is rejected 422 rather than landing readable
714
- // in the bucket. Reserved __key / __usage records are exempt (not user payload).
715
- function isTranscriptEnvelopeString(body) {
716
- if (typeof body !== 'string') return false;
717
- const trimmed = body.trimStart();
718
- if (!trimmed.startsWith('{')) return false;
719
- let obj;
720
- try {
721
- obj = JSON.parse(body);
722
- } catch {
723
- return false;
724
- }
725
- return !!obj
726
- && typeof obj === 'object'
727
- && obj.v === 1
728
- && obj.alg === 'aes-256-gcm'
729
- && base64ByteLength(obj.iv) === 12
730
- && base64ByteLength(obj.tag) === 16
731
- && base64ByteLength(obj.ct) >= 0;
732
- }
733
-
734
- function isEncryptedManagedBundle(bytes) {
735
- let text;
736
- try {
737
- text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
738
- } catch {
739
- return false;
740
- }
741
- const lines = text.split(/\\r?\\n/).filter(function (l) { return l.trim().length > 0; });
742
- if (lines.length < 2) return false; // a header line + at least one record line
743
- let header;
744
- try {
745
- header = JSON.parse(lines[0]);
746
- } catch {
747
- return false;
748
- }
749
- if (!header
750
- || header.kind !== 'agents-session-bundle'
751
- || header.version !== 1
752
- || header.encrypted !== true
753
- || header.count !== lines.length - 1
754
- || header.count < 1) return false;
755
- for (let i = 1; i < lines.length; i++) {
756
- let rec;
757
- try {
758
- rec = JSON.parse(lines[i]);
759
- } catch {
760
- return false;
761
- }
762
- if (!rec || rec.encrypted !== true || !isTranscriptEnvelopeString(rec.body)) return false;
763
- }
764
- return true;
765
- }
766
-
767
- function base64ByteLength(value) {
768
- if (typeof value !== 'string') return -1;
769
- try { return atob(value).length; } catch { return -1; }
770
- }
771
-
772
- async function defaultVerifyPhoenixToken(request, env) {
773
- const presented = (request.headers.get('authorization') || '').replace(/^Bearer\\s+/i, '');
774
- if (!presented) return null;
775
- const base = typeof env.PHOENIX_ID_BASE === 'string' ? env.PHOENIX_ID_BASE.replace(/\\/+$/, '') : '';
776
- if (!base) return null;
777
- let res;
778
- try {
779
- res = await fetch(base + '/api/v1/auth/me', {
780
- method: 'GET',
781
- headers: { Authorization: 'Bearer ' + presented },
782
- });
783
- } catch {
784
- return null;
785
- }
786
- if (!res.ok) return null;
787
- let body;
788
- try {
789
- body = await res.json();
790
- } catch {
791
- return null;
792
- }
793
- if (!body || typeof body.userId !== 'string' || !body.userId) return null;
794
- return { userId: body.userId, email: typeof body.email === 'string' ? body.email : '' };
795
- }
796
-
797
- function json(body, status = 200) {
798
- return new Response(JSON.stringify(body), {
799
- status,
800
- headers: {
801
- 'content-type': 'application/json; charset=utf-8',
802
- 'cache-control': 'private, no-store',
803
- },
804
- });
805
- }
806
- `;
807
- }