@aragon-agent/cli 0.6.70 → 0.6.72

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 (64) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +33 -14
  3. package/dist/account/config.d.ts +61 -0
  4. package/dist/account/config.js +83 -0
  5. package/dist/account/device-client.d.ts +113 -0
  6. package/dist/account/device-client.js +425 -0
  7. package/dist/account/format.d.ts +51 -0
  8. package/dist/account/format.js +102 -0
  9. package/dist/account/login-flow.d.ts +68 -0
  10. package/dist/account/login-flow.js +305 -0
  11. package/dist/account/session.d.ts +62 -0
  12. package/dist/account/session.js +63 -0
  13. package/dist/account/store.d.ts +86 -0
  14. package/dist/account/store.js +231 -0
  15. package/dist/agent/controller.d.ts +25 -1
  16. package/dist/agent/controller.js +78 -3
  17. package/dist/agent/project-guidance-prompt.js +97 -97
  18. package/dist/app/App.d.ts +12 -3
  19. package/dist/app/App.js +216 -3
  20. package/dist/cli.js +2 -2
  21. package/dist/commands/account-command.d.ts +86 -0
  22. package/dist/commands/account-command.js +165 -0
  23. package/dist/commands/builtins.js +15 -0
  24. package/dist/commands/catalog.js +17 -1
  25. package/dist/config/app-paths.d.ts +15 -0
  26. package/dist/config/app-paths.js +17 -0
  27. package/dist/config/cli-commands.d.ts +1 -1
  28. package/dist/config/cli-commands.js +4 -0
  29. package/dist/config/env.js +6 -0
  30. package/dist/config/load.js +36 -1
  31. package/dist/governance/engine/lifecycle.js +1 -1
  32. package/dist/governance/prompts/orchestrator-block.js +3 -3
  33. package/dist/host/controller-factory.d.ts +15 -0
  34. package/dist/host/controller-factory.js +10 -2
  35. package/dist/host/memory.d.ts +5 -1
  36. package/dist/host/memory.js +13 -0
  37. package/dist/memory/block.d.ts +38 -4
  38. package/dist/memory/block.js +52 -5
  39. package/dist/memory/command.js +56 -2
  40. package/dist/memory/journal.d.ts +58 -0
  41. package/dist/memory/journal.js +202 -0
  42. package/dist/memory/ledger.d.ts +54 -0
  43. package/dist/memory/ledger.js +105 -0
  44. package/dist/memory/paths.d.ts +10 -0
  45. package/dist/memory/paths.js +31 -0
  46. package/dist/memory/service.d.ts +54 -1
  47. package/dist/memory/service.js +156 -1
  48. package/dist/memory/store.d.ts +21 -3
  49. package/dist/memory/store.js +66 -6
  50. package/dist/memory/tools-batch.d.ts +27 -0
  51. package/dist/memory/tools-batch.js +462 -0
  52. package/dist/memory/tools-shared.d.ts +176 -0
  53. package/dist/memory/tools-shared.js +305 -0
  54. package/dist/memory/tools.d.ts +19 -28
  55. package/dist/memory/tools.js +148 -228
  56. package/dist/memory/undo.d.ts +53 -0
  57. package/dist/memory/undo.js +173 -0
  58. package/dist/redteam/prompt-template.js +16 -16
  59. package/dist/tools/index.d.ts +2 -2
  60. package/dist/tools/index.js +16 -1
  61. package/package.json +3 -3
  62. package/runtime/insecure-tls-warning.cjs +62 -62
  63. package/runtime/insecure-tls-warning.d.cts +5 -5
  64. package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -14
@@ -0,0 +1,425 @@
1
+ /**
2
+ * The RFC 8628 device-flow client (C1), with no UI and no ambient clock.
3
+ *
4
+ * TWO CALLS AND A STATE MACHINE:
5
+ *
6
+ * start() -> POST {baseUrl}/api/device/code {client_id, scope}
7
+ * poll() -> POST {baseUrl}/api/device/token {grant_type, device_code, client_id}
8
+ *
9
+ * EVERYTHING IS INJECTED - `fetch`, the clock and `sleep`. That is not test
10
+ * decoration: the polling loop's whole contract is about TIME (the server's
11
+ * interval, the `slow_down` growth, the 60 s cap, the `expires_in` ceiling), and
12
+ * a test that waits those seconds is a test nobody runs. With `now` and `sleep`
13
+ * as dependencies the intervals are data a fake clock can measure, and the
14
+ * shipped defaults are the only place a real timer exists.
15
+ *
16
+ * WHAT THIS MODULE REFUSES TO DO, each for a reason:
17
+ *
18
+ * - Never treat a non-200 as success, and never read the site's
19
+ * `{"error":{"code":...}}` envelope (C1). The device endpoints answer in the
20
+ * OAuth shape `{"error":"authorization_pending"}`; an object where a string
21
+ * belongs means this is not the endpoint we think it is, which is an error,
22
+ * not a token.
23
+ * - Never log or embed the `device_code` or the `access_token`. The token is
24
+ * returned to the caller and registered with the redactor there; the device
25
+ * code is a 34.6-bit credential that would let anyone redeem the grant.
26
+ * - Never poll past `expires_in`. The loop stops before a wait that would end
27
+ * after the deadline, so a terminal cannot sit there one interval too long
28
+ * holding a grant the server has already deleted.
29
+ * - Never spin: `authorization_pending` waits the server's interval, 429 waits
30
+ * the server's `retry-after`, and a transport failure backs off exponentially
31
+ * from the interval, capped at the same 60 s the server caps its own interval
32
+ * at. `maxNetworkRetries` bounds the backoff.
33
+ */
34
+ import { DEFAULT_POLL_INTERVAL_SECONDS, DEVICE_CLIENT_ID, DEVICE_CODE_PATH, DEVICE_GRANT_TYPE, DEVICE_SCOPE, DEVICE_TOKEN_PATH, MAX_POLL_INTERVAL_SECONDS, MIN_POLL_INTERVAL_SECONDS, SLOW_DOWN_STEP_SECONDS, apiUrl, } from './config.js';
35
+ import { getLogger } from '../logging/logger.js';
36
+ /** A whole request may not hang longer than this. */
37
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
38
+ /** Consecutive transport failures before `poll()` gives up. */
39
+ export const DEFAULT_MAX_NETWORK_RETRIES = 5;
40
+ /** A 429 without a usable `retry-after` header waits this long. */
41
+ export const DEFAULT_RETRY_AFTER_SECONDS = 5;
42
+ // ---------------------------------------------------------------------------
43
+ // Small pure helpers
44
+ // ---------------------------------------------------------------------------
45
+ function isRecord(value) {
46
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
47
+ }
48
+ function asString(value) {
49
+ return typeof value === 'string' && value.length > 0 ? value : null;
50
+ }
51
+ function asPositiveNumber(value) {
52
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;
53
+ }
54
+ /** Clamp a server-supplied interval into the range the web side honours. */
55
+ function clampInterval(seconds) {
56
+ if (!Number.isFinite(seconds))
57
+ return DEFAULT_POLL_INTERVAL_SECONDS;
58
+ const whole = Math.round(seconds);
59
+ return Math.min(MAX_POLL_INTERVAL_SECONDS, Math.max(MIN_POLL_INTERVAL_SECONDS, whole));
60
+ }
61
+ /**
62
+ * The next interval after `slow_down`.
63
+ *
64
+ * BOTH SIDES OF THE `max`: the RFC says the client must increase its interval by
65
+ * its own step (5 s here, the same step the server adds), and the response also
66
+ * carries the interval the server has already recorded on the grant. Taking the
67
+ * larger of the two means a client that under-counted is corrected immediately
68
+ * instead of after another `slow_down`.
69
+ */
70
+ function slowDownInterval(currentSeconds, requestedSeconds) {
71
+ const stepped = currentSeconds + SLOW_DOWN_STEP_SECONDS;
72
+ return clampInterval(Math.max(stepped, requestedSeconds ?? 0));
73
+ }
74
+ // ---------------------------------------------------------------------------
75
+ // Transport
76
+ // ---------------------------------------------------------------------------
77
+ async function readJsonBody(response) {
78
+ try {
79
+ const text = await response.text();
80
+ if (text.trim().length === 0)
81
+ return null;
82
+ const parsed = JSON.parse(text);
83
+ return isRecord(parsed) ? parsed : null;
84
+ }
85
+ catch {
86
+ // A non-JSON 200 is handled by the caller as a malformed success, which is
87
+ // more accurate than "network error" for a body we did receive.
88
+ return null;
89
+ }
90
+ }
91
+ function readRetryAfter(response) {
92
+ const raw = response.headers.get('retry-after');
93
+ if (raw === null)
94
+ return null;
95
+ const seconds = Number.parseInt(raw.trim(), 10);
96
+ if (!Number.isFinite(seconds) || seconds < 0)
97
+ return null;
98
+ return clampInterval(seconds);
99
+ }
100
+ function describeTransportError(error) {
101
+ if (error instanceof Error && error.message.length > 0)
102
+ return error.message;
103
+ return 'the request failed without an error message';
104
+ }
105
+ /**
106
+ * One POST, bounded by `requestTimeoutMs` and by the caller's signal.
107
+ *
108
+ * THE TIMEOUT IS A SEPARATE CONTROLLER ON PURPOSE: the caller's signal means
109
+ * "the user cancelled" and answers `cancelled`; our own timer means "the server
110
+ * did not answer" and answers `network`, which the poll loop retries. Folding
111
+ * the two into one signal would make a slow server end the login instead of
112
+ * backing off.
113
+ */
114
+ async function sendJson(deps, path, payload, signal) {
115
+ if (signal?.aborted)
116
+ return { kind: 'cancelled' };
117
+ const url = apiUrl(deps.baseUrl, path);
118
+ const controller = new AbortController();
119
+ const timer = setTimeout(() => controller.abort(), deps.requestTimeoutMs);
120
+ const onAbort = () => controller.abort();
121
+ signal?.addEventListener('abort', onAbort);
122
+ try {
123
+ const response = await deps.fetchImpl(url, {
124
+ method: 'POST',
125
+ headers: {
126
+ 'content-type': 'application/json',
127
+ accept: 'application/json',
128
+ 'user-agent': `aragon-cli/${DEVICE_CLIENT_ID}`,
129
+ },
130
+ body: JSON.stringify(payload),
131
+ signal: controller.signal,
132
+ });
133
+ return {
134
+ kind: 'response',
135
+ status: response.status,
136
+ body: await readJsonBody(response),
137
+ retryAfterSec: readRetryAfter(response),
138
+ };
139
+ }
140
+ catch (error) {
141
+ if (signal?.aborted)
142
+ return { kind: 'cancelled' };
143
+ if (controller.signal.aborted) {
144
+ return {
145
+ kind: 'network',
146
+ message: `${url} did not answer within ${deps.requestTimeoutMs} ms`,
147
+ };
148
+ }
149
+ return { kind: 'network', message: describeTransportError(error) };
150
+ }
151
+ finally {
152
+ clearTimeout(timer);
153
+ signal?.removeEventListener('abort', onAbort);
154
+ }
155
+ }
156
+ // ---------------------------------------------------------------------------
157
+ // Response readers
158
+ // ---------------------------------------------------------------------------
159
+ /**
160
+ * `{error: "code"}` -> the code, or `null`.
161
+ *
162
+ * AN OBJECT UNDER `error` IS `null`, NOT A CODE: that is the site's envelope and
163
+ * this endpoint family never sends it (C1). Reading through it would make a
164
+ * `400 {"error":{"code":"E_VALIDATION"}}` look like an OAuth error we might
165
+ * interpret, and the one interpretation that matters is "success".
166
+ */
167
+ function readOAuthError(body) {
168
+ if (body === null)
169
+ return null;
170
+ const code = asString(body['error']);
171
+ if (code === null)
172
+ return null;
173
+ const description = asString(body['error_description']);
174
+ return { code, description };
175
+ }
176
+ function describeOAuthFailure(failure) {
177
+ const detail = failure.description ?? 'no description';
178
+ return `${failure.code}: ${detail}`;
179
+ }
180
+ function readCodeResponse(body) {
181
+ if (body === null)
182
+ return null;
183
+ const deviceCode = asString(body['device_code']);
184
+ const userCode = asString(body['user_code']);
185
+ const verificationUri = asString(body['verification_uri']);
186
+ const expiresInSec = asPositiveNumber(body['expires_in']);
187
+ if (deviceCode === null || userCode === null || verificationUri === null)
188
+ return null;
189
+ if (expiresInSec === null)
190
+ return null;
191
+ const complete = asString(body['verification_uri_complete']);
192
+ return {
193
+ deviceCode,
194
+ userCode,
195
+ verificationUri,
196
+ verificationUriComplete: complete ?? `${verificationUri}?user_code=${encodeURIComponent(userCode)}`,
197
+ expiresInSec: Math.floor(expiresInSec),
198
+ intervalSec: clampInterval(asPositiveNumber(body['interval']) ?? DEFAULT_POLL_INTERVAL_SECONDS),
199
+ };
200
+ }
201
+ function readTokenResponse(body) {
202
+ if (body === null)
203
+ return null;
204
+ const accessToken = asString(body['access_token']);
205
+ if (accessToken === null)
206
+ return null;
207
+ return {
208
+ accessToken,
209
+ tokenType: asString(body['token_type']) ?? 'Bearer',
210
+ expiresInSec: Math.floor(asPositiveNumber(body['expires_in']) ?? 0),
211
+ scope: asString(body['scope']) ?? '',
212
+ tokenPrefix: asString(body['token_prefix']) ?? '',
213
+ };
214
+ }
215
+ // ---------------------------------------------------------------------------
216
+ // The polling state machine
217
+ // ---------------------------------------------------------------------------
218
+ function elapsedSeconds(state) {
219
+ return Math.max(0, Math.floor((state.deps.now() - state.startedAt) / 1000));
220
+ }
221
+ /** Exponential from the interval, doubling per consecutive failure, capped. */
222
+ function backoffMs(state) {
223
+ const grown = state.intervalSec * 2 ** state.networkFailures;
224
+ return clampInterval(grown) * 1000;
225
+ }
226
+ /**
227
+ * Sleep, but never past the deadline.
228
+ *
229
+ * `expired` here is not an error: it is the deadline arriving while we were
230
+ * waiting, which is exactly the moment the grant stops being usable.
231
+ */
232
+ async function waitInPoll(state, waitMs) {
233
+ const remaining = state.deadline - state.deps.now();
234
+ if (remaining <= 0)
235
+ return 'expired';
236
+ await state.deps.sleep(Math.min(waitMs, remaining), state.signal);
237
+ if (state.signal?.aborted)
238
+ return 'cancelled';
239
+ return 'ok';
240
+ }
241
+ /**
242
+ * Turn one response into the next step.
243
+ *
244
+ * The switch is the RFC 8628 table and nothing else: `authorization_pending`
245
+ * and `slow_down` are the two that mean "poll again", `access_denied`,
246
+ * `expired_token` and `invalid_grant` are terminal, and every other code is a
247
+ * terminal client fault that retrying cannot fix.
248
+ */
249
+ function interpretPollResponse(sent, state) {
250
+ if (sent.status === 200) {
251
+ const token = readTokenResponse(sent.body);
252
+ if (token === null) {
253
+ return {
254
+ kind: 'invalid',
255
+ message: 'the token endpoint returned a malformed success response',
256
+ };
257
+ }
258
+ return { kind: 'token', token };
259
+ }
260
+ if (sent.status === 429) {
261
+ const seconds = sent.retryAfterSec ?? DEFAULT_RETRY_AFTER_SECONDS;
262
+ getLogger().debug('cli', 'account.device_poll_rate_limited', { retryAfterSec: seconds });
263
+ return { kind: 'retry', waitMs: seconds * 1000 };
264
+ }
265
+ const failure = readOAuthError(sent.body);
266
+ if (failure === null) {
267
+ return {
268
+ kind: 'invalid',
269
+ message: `the token endpoint answered HTTP ${sent.status} without an OAuth error code`,
270
+ };
271
+ }
272
+ return interpretOAuthCode(failure, sent, state);
273
+ }
274
+ function readIntervalField(body) {
275
+ if (body === null)
276
+ return null;
277
+ return asPositiveNumber(body['interval']);
278
+ }
279
+ function interpretOAuthCode(failure, sent, state) {
280
+ switch (failure.code) {
281
+ case 'authorization_pending':
282
+ return { kind: 'retry', waitMs: state.intervalSec * 1000 };
283
+ case 'slow_down': {
284
+ state.intervalSec = slowDownInterval(state.intervalSec, readIntervalField(sent.body));
285
+ getLogger().debug('cli', 'account.device_poll_slow_down', { intervalSec: state.intervalSec });
286
+ return { kind: 'retry', waitMs: state.intervalSec * 1000 };
287
+ }
288
+ case 'access_denied':
289
+ return { kind: 'denied' };
290
+ case 'expired_token':
291
+ return { kind: 'expired' };
292
+ case 'invalid_grant':
293
+ return {
294
+ kind: 'invalid',
295
+ message: 'the device code is no longer valid (it expired, or the grant was already redeemed)',
296
+ };
297
+ default:
298
+ return { kind: 'invalid', message: describeOAuthFailure(failure) };
299
+ }
300
+ }
301
+ function waitFailed(waited) {
302
+ return waited === 'cancelled' ? { kind: 'cancelled' } : { kind: 'expired' };
303
+ }
304
+ async function runPoll(state) {
305
+ for (;;) {
306
+ if (state.signal?.aborted)
307
+ return { kind: 'cancelled' };
308
+ state.onProgress?.({ elapsedSec: elapsedSeconds(state) });
309
+ if (state.deps.now() >= state.deadline)
310
+ return { kind: 'expired' };
311
+ state.attempts += 1;
312
+ const sent = await sendJson(state.deps, DEVICE_TOKEN_PATH, tokenRequestBody(state.deviceCode), state.signal);
313
+ if (sent.kind === 'cancelled')
314
+ return { kind: 'cancelled' };
315
+ if (sent.kind !== 'response' || sent.status >= 500) {
316
+ const message = sent.kind === 'network' ? sent.message : `HTTP ${sent.status} from the token endpoint`;
317
+ state.networkFailures += 1;
318
+ if (state.networkFailures > state.deps.maxNetworkRetries)
319
+ return { kind: 'network', message };
320
+ getLogger().debug('cli', 'account.device_poll_network_error', {
321
+ attempt: state.attempts,
322
+ failures: state.networkFailures,
323
+ });
324
+ const waited = await waitInPoll(state, backoffMs(state));
325
+ if (waited !== 'ok')
326
+ return waitFailed(waited);
327
+ continue;
328
+ }
329
+ // The transport works again, so the backoff ladder restarts: `maxNetworkRetries`
330
+ // is a budget for CONSECUTIVE failures, not for a login's total failures.
331
+ state.networkFailures = 0;
332
+ const step = interpretPollResponse(sent, state);
333
+ if (step.kind !== 'retry')
334
+ return step;
335
+ const waited = await waitInPoll(state, step.waitMs);
336
+ if (waited !== 'ok')
337
+ return waitFailed(waited);
338
+ }
339
+ }
340
+ function tokenRequestBody(deviceCode) {
341
+ return { grant_type: DEVICE_GRANT_TYPE, device_code: deviceCode, client_id: DEVICE_CLIENT_ID };
342
+ }
343
+ // ---------------------------------------------------------------------------
344
+ // Factory
345
+ // ---------------------------------------------------------------------------
346
+ function defaultSleep(ms, signal) {
347
+ if (ms <= 0 || signal?.aborted)
348
+ return Promise.resolve();
349
+ return new Promise((resolve) => {
350
+ const finish = () => {
351
+ clearTimeout(timer);
352
+ signal?.removeEventListener('abort', finish);
353
+ resolve();
354
+ };
355
+ const timer = setTimeout(finish, ms);
356
+ signal?.addEventListener('abort', finish, { once: true });
357
+ });
358
+ }
359
+ function resolveDeps(deps) {
360
+ return {
361
+ baseUrl: deps.baseUrl,
362
+ fetchImpl: deps.fetchImpl ?? fetch,
363
+ now: deps.now ?? Date.now,
364
+ sleep: deps.sleep ?? defaultSleep,
365
+ maxNetworkRetries: deps.maxNetworkRetries ?? DEFAULT_MAX_NETWORK_RETRIES,
366
+ requestTimeoutMs: deps.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
367
+ };
368
+ }
369
+ async function requestCode(deps, signal) {
370
+ if (signal?.aborted)
371
+ return { kind: 'cancelled' };
372
+ const sent = await sendJson(deps, DEVICE_CODE_PATH, { client_id: DEVICE_CLIENT_ID, scope: DEVICE_SCOPE }, signal);
373
+ if (sent.kind !== 'response')
374
+ return sent;
375
+ if (sent.status === 200) {
376
+ const code = readCodeResponse(sent.body);
377
+ if (code === null) {
378
+ return {
379
+ kind: 'invalid',
380
+ message: 'the authorisation endpoint returned a malformed code response',
381
+ };
382
+ }
383
+ getLogger().debug('cli', 'account.device_code_issued', {
384
+ baseUrl: deps.baseUrl,
385
+ expiresInSec: code.expiresInSec,
386
+ intervalSec: code.intervalSec,
387
+ });
388
+ return { kind: 'code', code };
389
+ }
390
+ const failure = readOAuthError(sent.body);
391
+ if (failure !== null)
392
+ return { kind: 'invalid', message: describeOAuthFailure(failure) };
393
+ return {
394
+ kind: 'network',
395
+ message: `the authorisation endpoint answered HTTP ${sent.status}`,
396
+ };
397
+ }
398
+ /**
399
+ * Build a client bound to one origin.
400
+ *
401
+ * A FACTORY RATHER THAN MODULE STATE: the base URL is per-login (the user may
402
+ * point `ARAGON_WEB_URL` at staging), and a module-level singleton would leak
403
+ * one login's origin into the next. The object is cheap; callers create one per
404
+ * `startLogin`.
405
+ */
406
+ export function createDeviceClient(deps) {
407
+ const resolved = resolveDeps(deps);
408
+ return {
409
+ start: (options = {}) => requestCode(resolved, options.signal),
410
+ poll: (input) => {
411
+ const startedAt = resolved.now();
412
+ return runPoll({
413
+ deps: resolved,
414
+ deviceCode: input.code.deviceCode,
415
+ signal: input.signal,
416
+ onProgress: input.onProgress,
417
+ startedAt,
418
+ deadline: startedAt + Math.max(0, input.code.expiresInSec) * 1000,
419
+ intervalSec: clampInterval(input.code.intervalSec),
420
+ networkFailures: 0,
421
+ attempts: 0,
422
+ });
423
+ },
424
+ };
425
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The account layer's user-facing copy - pure functions, no I/O, no clock (C4).
3
+ *
4
+ * WHY COPY LIVES IN ITS OWN MODULE: three surfaces render the same four states
5
+ * (the `/login` transcript, the startup notice, the status line) and they must
6
+ * not each invent a sentence for "expiring". A pure function is also the only
7
+ * part of this layer a test can pin without a filesystem, a fake clock and a
8
+ * fake server at the same time.
9
+ *
10
+ * ENGLISH, ASCII ONLY, and no trailing period after a path or a URL: these
11
+ * strings reach a terminal whose width and font the CLI does not control.
12
+ */
13
+ import { type AccountStatus } from './session.js';
14
+ /** Closed set; `login-flow.ts` maps every failure onto exactly one of these. */
15
+ export type LoginFailureReason = 'denied' | 'expired' | 'network' | 'cancelled' | 'invalid';
16
+ /** `2027-01-05`, or `unknown` for a value that is not a timestamp. */
17
+ export declare function formatIsoDate(epochMs: number | null): string;
18
+ /**
19
+ * The one line every surface can print (C4).
20
+ *
21
+ * `describeExpiry` names the state first, then the fact that changes what the
22
+ * user should do - days left, or the date it stopped working. The `expiring`
23
+ * sentence names `/login` because that is the entire point of warning three days
24
+ * ahead instead of at zero.
25
+ */
26
+ export declare function describeExpiry(status: AccountStatus): string;
27
+ /**
28
+ * The startup notice, or `null` when there is nothing to say.
29
+ *
30
+ * ONLY `expiring` PRODUCES A LINE, and that is the spec's decision (one prompt
31
+ * per launch at three days, not a banner on every start). `expired` is
32
+ * deliberately silent here: a terminal that greets a user with "your token
33
+ * expired" every single launch is nagging, and `/login` still works.
34
+ */
35
+ export declare function describeStartupNotice(status: AccountStatus): string | null;
36
+ /** Why a login failed, in the words the transcript shows under the code. */
37
+ export declare function describeLoginFailure(reason: LoginFailureReason, baseUrl: string): string;
38
+ /** A token arrived but the profile call did not answer - no file was written. */
39
+ export declare function describeTokenRejected(baseUrl: string): string;
40
+ /**
41
+ * The credential is valid but the disk refused it.
42
+ *
43
+ * NAMING THE PATH IS THE POINT: the usual cause is a read-only or full home
44
+ * directory, and the user cannot fix that from a message that only says "error".
45
+ */
46
+ export declare function describeSaveFailure(path: string): string;
47
+ /** The code box above the polling spinner: what to open, and what to type. */
48
+ export declare function describeDeviceCode(code: {
49
+ code: string;
50
+ link: string;
51
+ }): string;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The account layer's user-facing copy - pure functions, no I/O, no clock (C4).
3
+ *
4
+ * WHY COPY LIVES IN ITS OWN MODULE: three surfaces render the same four states
5
+ * (the `/login` transcript, the startup notice, the status line) and they must
6
+ * not each invent a sentence for "expiring". A pure function is also the only
7
+ * part of this layer a test can pin without a filesystem, a fake clock and a
8
+ * fake server at the same time.
9
+ *
10
+ * ENGLISH, ASCII ONLY, and no trailing period after a path or a URL: these
11
+ * strings reach a terminal whose width and font the CLI does not control.
12
+ */
13
+ import { EXPIRY_WARN_DAYS } from './session.js';
14
+ const REASON_COPY = {
15
+ 'signed-out': 'Not signed in.',
16
+ valid: 'Signed in.',
17
+ expiring: 'Signed in, token nearly expired.',
18
+ expired: 'Signed in, but the token has expired.',
19
+ };
20
+ function plural(count, singular) {
21
+ return count === 1 ? `1 ${singular}` : `${count} ${singular}s`;
22
+ }
23
+ /** `2027-01-05`, or `unknown` for a value that is not a timestamp. */
24
+ export function formatIsoDate(epochMs) {
25
+ if (epochMs === null || !Number.isFinite(epochMs))
26
+ return 'unknown';
27
+ const iso = new Date(epochMs).toISOString();
28
+ return iso.slice(0, 10);
29
+ }
30
+ function whoIsSignedIn(status) {
31
+ return status.user === null ? 'your account' : status.user.username;
32
+ }
33
+ /**
34
+ * The one line every surface can print (C4).
35
+ *
36
+ * `describeExpiry` names the state first, then the fact that changes what the
37
+ * user should do - days left, or the date it stopped working. The `expiring`
38
+ * sentence names `/login` because that is the entire point of warning three days
39
+ * ahead instead of at zero.
40
+ */
41
+ export function describeExpiry(status) {
42
+ const head = REASON_COPY[status.state];
43
+ switch (status.state) {
44
+ case 'signed-out':
45
+ return `${head} Run /login to connect an AragonAgent account.`;
46
+ case 'valid':
47
+ return `${head} ${whoIsSignedIn(status)} - token expires in ${plural(status.daysLeft, 'day')} (${formatIsoDate(status.expiresAt)}).`;
48
+ case 'expiring':
49
+ return `${head} ${whoIsSignedIn(status)} - ${plural(status.daysLeft, 'day')} left (${formatIsoDate(status.expiresAt)}). Run /login to renew before it stops working.`;
50
+ case 'expired':
51
+ return `${head} The token for ${whoIsSignedIn(status)} expired on ${formatIsoDate(status.expiresAt)}. Run /login to sign in again.`;
52
+ }
53
+ }
54
+ /**
55
+ * The startup notice, or `null` when there is nothing to say.
56
+ *
57
+ * ONLY `expiring` PRODUCES A LINE, and that is the spec's decision (one prompt
58
+ * per launch at three days, not a banner on every start). `expired` is
59
+ * deliberately silent here: a terminal that greets a user with "your token
60
+ * expired" every single launch is nagging, and `/login` still works.
61
+ */
62
+ export function describeStartupNotice(status) {
63
+ if (status.state !== 'expiring')
64
+ return null;
65
+ return (`${whoIsSignedIn(status)}: your AragonAgent token expires in ` +
66
+ `${plural(status.daysLeft, 'day')} (${formatIsoDate(status.expiresAt)}). ` +
67
+ `Run /login within ${EXPIRY_WARN_DAYS} days to stay signed in.`);
68
+ }
69
+ /** Why a login failed, in the words the transcript shows under the code. */
70
+ export function describeLoginFailure(reason, baseUrl) {
71
+ switch (reason) {
72
+ case 'denied':
73
+ return 'Sign-in was denied in the browser. Nothing was saved. Run /login to try again.';
74
+ case 'expired':
75
+ return 'The sign-in code expired before it was approved. Run /login to get a new one.';
76
+ case 'network':
77
+ return `Could not reach ${baseUrl}. Check your network and run /login again.`;
78
+ case 'cancelled':
79
+ return 'Sign-in cancelled. No credentials were saved.';
80
+ case 'invalid':
81
+ return `${baseUrl} rejected the sign-in request. Run /login to try again.`;
82
+ }
83
+ }
84
+ /** A token arrived but the profile call did not answer - no file was written. */
85
+ export function describeTokenRejected(baseUrl) {
86
+ return (`${baseUrl} issued a token but refused to describe the account it belongs to. ` +
87
+ 'Nothing was saved. Run /login to try again.');
88
+ }
89
+ /**
90
+ * The credential is valid but the disk refused it.
91
+ *
92
+ * NAMING THE PATH IS THE POINT: the usual cause is a read-only or full home
93
+ * directory, and the user cannot fix that from a message that only says "error".
94
+ */
95
+ export function describeSaveFailure(path) {
96
+ return (`Signed in, but the credential could not be saved to ${path}. ` +
97
+ 'Check permissions and run /login again.');
98
+ }
99
+ /** The code box above the polling spinner: what to open, and what to type. */
100
+ export function describeDeviceCode(code) {
101
+ return `Open ${code.link} and enter the code ${code.code}.`;
102
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * `startLogin()` - the orchestration behind `/login` (C4).
3
+ *
4
+ * 1. ask the server for a device code and hand it to the caller's `onCode`
5
+ * 2. poll until the person approves, refuses, or the code expires
6
+ * 3. register the token with the redactor, then read back who it belongs to
7
+ * 4. write `<home>/account.json` atomically (C3) and answer the username
8
+ *
9
+ * THE ORDER IS THE CONTRACT. Nothing is written until step 4 has everything the
10
+ * file needs, so every failure in steps 1-3 leaves the filesystem untouched:
11
+ * "cancel or fail, and no new file exists" is a property of the ORDER, not of a
12
+ * cleanup handler that could itself fail. An existing credential is never
13
+ * modified by a failed login either - a user who starts a second login and
14
+ * cancels it still has the first one.
15
+ *
16
+ * WHY `/api/v1/me` IS MANDATORY: `account.json` records who the credential
17
+ * belongs to, and the only trustworthy source for that is the server that just
18
+ * issued it; a username typed by the caller would be a claim, not a fact. If
19
+ * that call fails after the token was issued, the token is DISCARDED rather than
20
+ * stored half-described - it is one revocable 20-day credential, and asking the
21
+ * person to approve again costs them one tap on their phone.
22
+ */
23
+ import { type LoginFailureReason } from './format.js';
24
+ /** How many times the profile call is attempted before the login is abandoned. */
25
+ export declare const ME_ATTEMPTS = 2;
26
+ /** Wait before the second profile attempt. */
27
+ export declare const ME_RETRY_DELAY_MS = 1000;
28
+ export interface LoginCode {
29
+ readonly link: string;
30
+ readonly code: string;
31
+ readonly expiresInSec: number;
32
+ }
33
+ export interface StartLoginInput {
34
+ readonly baseUrl?: string;
35
+ readonly signal?: AbortSignal;
36
+ /** Called ONCE, before polling starts, with what the person must open and type. */
37
+ readonly onCode: (code: LoginCode) => void;
38
+ /** Called on every poll iteration; `elapsedSec` is since the poll started. */
39
+ readonly onProgress?: (progress: {
40
+ readonly elapsedSec: number;
41
+ }) => void;
42
+ }
43
+ export interface LoginAccount {
44
+ readonly username: string;
45
+ readonly expiresAt: number;
46
+ }
47
+ export type LoginResult = {
48
+ readonly ok: true;
49
+ readonly account: LoginAccount;
50
+ } | {
51
+ readonly ok: false;
52
+ readonly reason: LoginFailureReason;
53
+ readonly message: string;
54
+ };
55
+ export interface LoginDeps {
56
+ readonly fetchImpl?: typeof fetch;
57
+ readonly now?: () => number;
58
+ readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
59
+ readonly maxNetworkRetries?: number;
60
+ readonly requestTimeoutMs?: number;
61
+ }
62
+ /**
63
+ * Run one device-flow login. Never throws: every failure is a `LoginResult`.
64
+ *
65
+ * `onCode` IS CALLED BEFORE THE FIRST POLL, and the poll is awaited after it, so
66
+ * the UI can paint the code and the spinner while the network is already moving.
67
+ */
68
+ export declare function startLogin(input: StartLoginInput, deps?: LoginDeps): Promise<LoginResult>;