@aragon-agent/cli 0.6.75 → 0.6.77

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 (66) hide show
  1. package/CHANGELOG.md +7 -1
  2. package/README.md +3 -3
  3. package/dist/account/config.d.ts +4 -1
  4. package/dist/account/config.js +14 -1
  5. package/dist/account/device-client.d.ts +2 -0
  6. package/dist/account/device-client.js +11 -5
  7. package/dist/account/login-flow.d.ts +1 -0
  8. package/dist/account/login-flow.js +11 -5
  9. package/dist/account/store.d.ts +5 -0
  10. package/dist/account/store.js +38 -0
  11. package/dist/agent/controller.js +4 -1
  12. package/dist/app/App.d.ts +0 -6
  13. package/dist/app/App.js +36 -5
  14. package/dist/cli.js +6 -0
  15. package/dist/cloud-sync/coordinator.d.ts +64 -0
  16. package/dist/cloud-sync/coordinator.js +294 -0
  17. package/dist/cloud-sync/gene-adapter.d.ts +2 -0
  18. package/dist/cloud-sync/gene-adapter.js +234 -0
  19. package/dist/cloud-sync/identity.d.ts +19 -0
  20. package/dist/cloud-sync/identity.js +311 -0
  21. package/dist/cloud-sync/lease.d.ts +9 -0
  22. package/dist/cloud-sync/lease.js +173 -0
  23. package/dist/cloud-sync/memory-adapter.d.ts +4 -0
  24. package/dist/cloud-sync/memory-adapter.js +107 -0
  25. package/dist/cloud-sync/project-bindings.d.ts +7 -0
  26. package/dist/cloud-sync/project-bindings.js +68 -0
  27. package/dist/cloud-sync/protocol.d.ts +65 -0
  28. package/dist/cloud-sync/protocol.js +193 -0
  29. package/dist/cloud-sync/reconcile.d.ts +14 -0
  30. package/dist/cloud-sync/reconcile.js +539 -0
  31. package/dist/cloud-sync/state.d.ts +117 -0
  32. package/dist/cloud-sync/state.js +208 -0
  33. package/dist/cloud-sync/transport.d.ts +28 -0
  34. package/dist/cloud-sync/transport.js +134 -0
  35. package/dist/commands/account-command.d.ts +2 -1
  36. package/dist/commands/account-command.js +54 -7
  37. package/dist/config/app-paths.d.ts +2 -2
  38. package/dist/config/app-paths.js +4 -4
  39. package/dist/config/env.d.ts +2 -0
  40. package/dist/config/env.js +17 -0
  41. package/dist/gene/commit-exec.js +5 -1
  42. package/dist/gene/commit-prepare.js +3 -1
  43. package/dist/gene/commit-types.d.ts +2 -0
  44. package/dist/gene/manager-actions.js +29 -1
  45. package/dist/gene/manager-library.js +5 -4
  46. package/dist/gene/paths.d.ts +4 -3
  47. package/dist/gene/paths.js +9 -2
  48. package/dist/gene/store.d.ts +2 -0
  49. package/dist/gene/store.js +2 -1
  50. package/dist/gene/transfer.d.ts +2 -0
  51. package/dist/gene/transfer.js +2 -1
  52. package/dist/gene/version-service.d.ts +4 -0
  53. package/dist/gene/version-service.js +72 -8
  54. package/dist/gene/wiring.d.ts +9 -0
  55. package/dist/gene/wiring.js +1 -1
  56. package/dist/host/cloud-sync.d.ts +21 -0
  57. package/dist/host/cloud-sync.js +49 -0
  58. package/dist/memory/format.d.ts +2 -0
  59. package/dist/memory/format.js +11 -2
  60. package/dist/memory/paths.d.ts +5 -3
  61. package/dist/memory/paths.js +15 -6
  62. package/dist/memory/service.d.ts +2 -0
  63. package/dist/memory/service.js +43 -6
  64. package/dist/memory/store.d.ts +11 -1
  65. package/dist/memory/store.js +74 -9
  66. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -94,7 +94,13 @@ were written.
94
94
  in tool calls with no results, which the provider would reject, so a retry could only fail).
95
95
  A pending team-wake countdown keeps the timer slot (it redoes the same turn and delivers a real signal),
96
96
  and a recovery that already holds it makes a later wake answer `busy`.
97
- `retry.resumeRun: false` (or `/retry off`, or `retry.maxRetries: 0`) restores the old behaviour exactly.
97
+ `retry.resumeRun: false` (or `/retry off`) restores the old behaviour exactly.
98
+ `retry.maxRetries: 0` no longer does, and that is the point of this entry: the two used to be one
99
+ switch, so a project `.env` carrying `ARAGON_RETRY_MAX=0` left a session with neither a request
100
+ ladder nor a recovery, and a single TLS reset ended the run for good. `0` now says only "do not
101
+ re-send this request". The recovery keeps its own kill switches - `retry.resumeRun: false`,
102
+ `retry.maxRunResumes: 0`, `retry.maxRunResumesPerPrompt: 0` - and `/retry off` /
103
+ `retry.enabled: false` still turns off both layers at once.
98
104
  `aragon -p` and the one-shot `aragon exec` path get **one** recovery, 15 s grace, and exit 1 when it does
99
105
  not end in an answer; text already streamed to stdout before the stall is not retracted (the retry line on
100
106
  stderr says so), as with the ladder's own `stream_restart`.
package/README.md CHANGED
@@ -3877,7 +3877,7 @@ env / `.env` → CLI flags**.
3877
3877
  `ARAGON_TOOL_IMAGES` (`0` stops `read_file` from showing pictures to the model; see
3878
3878
  [Looking at images](#looking-at-images-read_file)),
3879
3879
  `ARAGON_RETRY` (`0` disables API retry), `ARAGON_RETRY_MAX` (retry count; `0`
3880
- also disables),
3880
+ installs no ladder at all and leaves run-level recovery alone),
3881
3881
  `ARAGON_UPDATE` (`0` / `off` disables auto-update, `notify` reports without
3882
3882
  installing), `ARAGON_UPDATE_REGISTRY` (registry base URL for the update check),
3883
3883
  `ARAGON_SKILLS` (`0` disables), `ARAGON_SKILLS_PATH`,
@@ -3936,7 +3936,7 @@ env / `.env` → CLI flags**.
3936
3936
  | `todo.followThrough` | `"notify"` | What happens when a run ends with steps left. `notify` says so and stops; `auto` continues the plan after a 3-second grace window, bounded by two structural limits (one fruitless attempt, 25 continuations per plan) that are deliberately **not** settings; `off` is silent. An unrecognized value falls back to `notify`. |
3937
3937
  | `todo.acceptance` | `true` | Plan acceptance criteria with every list, and show them (`ACCEPT` / `VERIFY` in the rail, the card's second block, `Accept 2/5` on the status line). `false` plans steps only: no criteria, no verify phase, and every surface is byte-identical to a build without the feature. `/todo acceptance off` changes it for the running session too. |
3938
3938
  | `retry.enabled` | `true` | Retry a failed provider call at all. Unlike `team.enabled` / `todo.enabled` this decides nothing at construction — the policy lives on the provider registry, so `/retry on` / `/retry off` takes effect **in the running session**, subagents included. |
3939
- | `retry.maxRetries` | `10` | Retries **after** the first attempt, clamped to `[0, 20]`. `0` is the kill switch and is a real value here, not a typo for the default. The 20 is a hard ceiling enforced twice — on the config value and again inside the engine — so hand-editing this file cannot raise it. |
3939
+ | `retry.maxRetries` | `10` | Retries **after** the first attempt, clamped to `[0, 20]`. `0` is a real value here, not a typo for the default: it installs no ladder at all, so one failure is final for that request (`retry.resumeRun` is a separate switch and is unaffected). The 20 is a hard ceiling enforced twice — on the config value and again inside the engine — so hand-editing this file cannot raise it. |
3940
3940
  | `retry.initialDelayMs` | `1000` | The first wait, clamped to `[100, 30000]`. |
3941
3941
  | `retry.maxDelayMs` | `30000` | Ceiling on one wait, clamped to `[1000, 120000]` and raised to `initialDelayMs` if the two conflict. Kept below the engine's 60 s idle window on purpose, so the mechanism does not depend on the watchdog pause being correct — it merely benefits from it. |
3942
3942
  | `retry.multiplier` | `2` | Growth factor, clamped to `[1, 5]`. The one **float** key in this section: `2.5` is a legitimate factor and is stored as typed. |
@@ -3944,7 +3944,7 @@ env / `.env` → CLI flags**.
3944
3944
  | `retry.respectRetryAfter` | `true` | Honour `Retry-After` (and the provider rate-limit reset headers) as a **floor**, never a replacement — a `Retry-After: 1` on the ninth retry does not undo eight retries of backoff. A stated wait above 60 s is surfaced immediately instead of waited out. |
3945
3945
  | `retry.maxElapsedMs` | `240000` | Wall-clock budget from the first failure, clamped to `[10000, 1800000]`. Under the legacy regime (`team.overseer: false`) with `team.subagentTimeoutMs` positive, keep this below it: an equal budget means a subagent is killed at the same instant its ladder ends, and the user is then told "subagent timed out" for what was a provider outage. |
3946
3946
  | `retry.onPartialStream` | `true` | Allow a restart after content has already streamed to the transcript. The view is rewound and the discarded tool cards removed; engine history is provably clean at that point, because it is only written on a completed turn. `false` refuses the whole path. |
3947
- | `retry.resumeRun` | `true` | Re-run a run the **engine** interrupted - the idle watchdog fired (`[Agent] idle watchdog fired`) or the retry ladder gave up on a transport failure - instead of leaving it dead. Host-side: it redoes a **run** (`controller.continue()`, no message added) where the ladder above retries a **request**, so it never reaches the engine's `RetryPolicy`. Needs no todo plan and ignores `todo.followThrough`. Waits 15 s, then 45 s, then 120 s (cancel with `Esc`), announces the stall and its stage, and is switched off by `retry.enabled: false` / `retry.maxRetries: 0` as well. A rate limit, a rejected key, a context overflow, a run you stopped with `Esc` and a stall that began while a tool was running (unpaired tool calls in the history) are never recovered. `aragon -p` / `aragon exec` get one recovery, 15 s grace. |
3947
+ | `retry.resumeRun` | `true` | Re-run a run the **engine** interrupted - the idle watchdog fired (`[Agent] idle watchdog fired`) or the retry ladder gave up on a transport failure - instead of leaving it dead. Host-side: it redoes a **run** (`controller.continue()`, no message added) where the ladder above retries a **request**, so it never reaches the engine's `RetryPolicy`. Needs no todo plan and ignores `todo.followThrough`. Waits 15 s, then 45 s, then 120 s (cancel with `Esc`), announces the stall and its stage, and is switched off by `retry.enabled: false` or `retry.resumeRun: false` (or by either count below reaching `0`) - `retry.maxRetries: 0` turns off the request ladder above and deliberately leaves this alone, because at `0` the ladder is not installed at all and this is then the only recovery a session has. A rate limit, a rejected key, a context overflow, a run you stopped with `Esc` and a stall that began while a tool was running (unpaired tool calls in the history) are never recovered. `aragon -p` / `aragon exec` get one recovery, 15 s grace. |
3948
3948
  | `retry.maxRunResumes` | `3` | Back-to-back recoveries before control goes back to you, clamped to `[0, 10]`. Cleared by any run that ends without an error. `0` disables recovery and is a real value here, not a typo for the default. |
3949
3949
  | `retry.maxRunResumesPerPrompt` | `10` | Recoveries per prompt, clamped to `[0, 50]`, however well the runs in between went. Cleared **only** by you typing, so a link that dies every other turn still reaches it. `0` disables recovery. |
3950
3950
  | `retry.reconnect` | `"auto"` | The shape of the reconnect ladder. `auto` = the full three tiers in the app and two tiers under `aragon -p` / `aragon exec`; `full` and `bounded` pin it either way; `off` keeps the fast tier and refuses to escalate. `/retry reconnect <mode>` changes it for the running session. |
@@ -18,8 +18,9 @@
18
18
  export declare const DEFAULT_WEB_BASE_URL = "https://aragonagent.com";
19
19
  /** RFC 8628 section 3.1: the client identifier the web side has allow-listed (C1). */
20
20
  export declare const DEVICE_CLIENT_ID = "aragon-cli";
21
- /** The only scope a device grant may request (C1). */
21
+ /** Legacy and account-only grant. */
22
22
  export declare const DEVICE_SCOPE = "account:read";
23
+ export declare const LIBRARY_SCOPE = "account:read library:read library:write";
23
24
  /** RFC 8628 section 3.4 grant type, verbatim: the server compares it byte for byte. */
24
25
  export declare const DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
25
26
  export declare const DEVICE_CODE_PATH = "/api/device/code";
@@ -59,3 +60,5 @@ export declare function normaliseBaseUrl(raw: string | null | undefined): string
59
60
  export declare function resolveWebBaseUrl(env?: NodeJS.ProcessEnv): string;
60
61
  /** `https://host/api/device/code`; `baseUrl` is expected to be normalised. */
61
62
  export declare function apiUrl(baseUrl: string, path: string): string;
63
+ /** Enforce transport confidentiality before exchanging credentials. */
64
+ export declare function isCredentialSite(base: string): boolean;
@@ -19,8 +19,9 @@ import process from 'node:process';
19
19
  export const DEFAULT_WEB_BASE_URL = 'https://aragonagent.com';
20
20
  /** RFC 8628 section 3.1: the client identifier the web side has allow-listed (C1). */
21
21
  export const DEVICE_CLIENT_ID = 'aragon-cli';
22
- /** The only scope a device grant may request (C1). */
22
+ /** Legacy and account-only grant. */
23
23
  export const DEVICE_SCOPE = 'account:read';
24
+ export const LIBRARY_SCOPE = 'account:read library:read library:write';
24
25
  /** RFC 8628 section 3.4 grant type, verbatim: the server compares it byte for byte. */
25
26
  export const DEVICE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
26
27
  export const DEVICE_CODE_PATH = '/api/device/code';
@@ -81,3 +82,15 @@ export function resolveWebBaseUrl(env = process.env) {
81
82
  export function apiUrl(baseUrl, path) {
82
83
  return `${baseUrl.replace(/\/+$/, '')}${path}`;
83
84
  }
85
+ /** Enforce transport confidentiality before exchanging credentials. */
86
+ export function isCredentialSite(base) {
87
+ let url;
88
+ try {
89
+ url = new URL(base);
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ return !url.username && !url.password && (url.protocol === 'https:' ||
95
+ (url.protocol === 'http:' && /^(localhost|127\.\d+\.\d+\.\d+|\[::1\])$/.test(url.hostname)));
96
+ }
@@ -38,6 +38,7 @@ export declare const DEFAULT_MAX_NETWORK_RETRIES = 5;
38
38
  /** A 429 without a usable `retry-after` header waits this long. */
39
39
  export declare const DEFAULT_RETRY_AFTER_SECONDS = 5;
40
40
  export interface DeviceCodeInfo {
41
+ readonly accountOnly?: boolean;
41
42
  readonly deviceCode: string;
42
43
  readonly userCode: string;
43
44
  readonly verificationUri: string;
@@ -99,6 +100,7 @@ export interface DeviceClientDeps {
99
100
  export interface DeviceClient {
100
101
  start(options?: {
101
102
  readonly signal?: AbortSignal;
103
+ readonly accountOnly?: boolean;
102
104
  }): Promise<DeviceCodeResult>;
103
105
  poll(input: PollInput): Promise<DevicePollResult>;
104
106
  }
@@ -31,7 +31,7 @@
31
31
  * from the interval, capped at the same 60 s the server caps its own interval
32
32
  * at. `maxNetworkRetries` bounds the backoff.
33
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';
34
+ import { DEFAULT_POLL_INTERVAL_SECONDS, DEVICE_CLIENT_ID, DEVICE_CODE_PATH, DEVICE_GRANT_TYPE, DEVICE_SCOPE, LIBRARY_SCOPE, isCredentialSite, DEVICE_TOKEN_PATH, MAX_POLL_INTERVAL_SECONDS, MIN_POLL_INTERVAL_SECONDS, SLOW_DOWN_STEP_SECONDS, apiUrl, } from './config.js';
35
35
  import { getLogger } from '../logging/logger.js';
36
36
  /** A whole request may not hang longer than this. */
37
37
  export const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
@@ -122,6 +122,7 @@ async function sendJson(deps, path, payload, signal) {
122
122
  try {
123
123
  const response = await deps.fetchImpl(url, {
124
124
  method: 'POST',
125
+ redirect: 'error',
125
126
  headers: {
126
127
  'content-type': 'application/json',
127
128
  accept: 'application/json',
@@ -366,10 +367,12 @@ function resolveDeps(deps) {
366
367
  requestTimeoutMs: deps.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
367
368
  };
368
369
  }
369
- async function requestCode(deps, signal) {
370
+ async function requestCode(deps, signal, scope = LIBRARY_SCOPE) {
370
371
  if (signal?.aborted)
371
372
  return { kind: 'cancelled' };
372
- const sent = await sendJson(deps, DEVICE_CODE_PATH, { client_id: DEVICE_CLIENT_ID, scope: DEVICE_SCOPE }, signal);
373
+ if (!isCredentialSite(deps.baseUrl))
374
+ return { kind: 'invalid', message: 'A secure issuing site is required.' };
375
+ const sent = await sendJson(deps, DEVICE_CODE_PATH, { client_id: DEVICE_CLIENT_ID, scope }, signal);
373
376
  if (sent.kind !== 'response')
374
377
  return sent;
375
378
  if (sent.status === 200) {
@@ -385,9 +388,12 @@ async function requestCode(deps, signal) {
385
388
  expiresInSec: code.expiresInSec,
386
389
  intervalSec: code.intervalSec,
387
390
  });
388
- return { kind: 'code', code };
391
+ return { kind: 'code', code: scope === DEVICE_SCOPE ? { ...code, accountOnly: true } : code };
389
392
  }
390
393
  const failure = readOAuthError(sent.body);
394
+ if (sent.status === 400 && failure?.code === 'invalid_scope' && scope === LIBRARY_SCOPE) {
395
+ return requestCode(deps, signal, DEVICE_SCOPE);
396
+ }
391
397
  if (failure !== null)
392
398
  return { kind: 'invalid', message: describeOAuthFailure(failure) };
393
399
  return {
@@ -406,7 +412,7 @@ async function requestCode(deps, signal) {
406
412
  export function createDeviceClient(deps) {
407
413
  const resolved = resolveDeps(deps);
408
414
  return {
409
- start: (options = {}) => requestCode(resolved, options.signal),
415
+ start: (options = {}) => requestCode(resolved, options.signal, options.accountOnly ? DEVICE_SCOPE : LIBRARY_SCOPE),
410
416
  poll: (input) => {
411
417
  const startedAt = resolved.now();
412
418
  return runPoll({
@@ -32,6 +32,7 @@ export interface LoginCode {
32
32
  }
33
33
  export interface StartLoginInput {
34
34
  readonly baseUrl?: string;
35
+ readonly accountOnly?: boolean;
35
36
  readonly signal?: AbortSignal;
36
37
  /** Called ONCE, before polling starts, with what the person must open and type. */
37
38
  readonly onCode: (code: LoginCode) => void;
@@ -24,7 +24,7 @@ import { registerSecret } from '@aragon-agent/tui/model/logging/secret-registry'
24
24
  import { ACCOUNT_ME_PATH, apiUrl, normaliseBaseUrl, resolveWebBaseUrl } from './config.js';
25
25
  import { DEFAULT_REQUEST_TIMEOUT_MS, createDeviceClient, } from './device-client.js';
26
26
  import { describeLoginFailure, describeSaveFailure, describeTokenRejected, } from './format.js';
27
- import { writeAccount } from './store.js';
27
+ import { saveLoginAccount } from './store.js';
28
28
  import { getAccountPath } from '../config/app-paths.js';
29
29
  import { getLogger } from '../logging/logger.js';
30
30
  /** How many times the profile call is attempted before the login is abandoned. */
@@ -106,6 +106,7 @@ async function fetchMeOnce(baseUrl, token, deps, signal) {
106
106
  try {
107
107
  const response = await deps.fetchImpl(apiUrl(baseUrl, ACCOUNT_ME_PATH), {
108
108
  method: 'GET',
109
+ redirect: 'error',
109
110
  headers: {
110
111
  authorization: `Bearer ${token}`,
111
112
  accept: 'application/json',
@@ -236,7 +237,7 @@ async function authorizeDevice(input, baseUrl, deps, now) {
236
237
  maxNetworkRetries: deps.maxNetworkRetries,
237
238
  requestTimeoutMs: deps.requestTimeoutMs,
238
239
  });
239
- const started = await client.start({ signal: input.signal });
240
+ const started = await client.start({ signal: input.signal, accountOnly: input.accountOnly });
240
241
  if (started.kind === 'cancelled') {
241
242
  return { ok: false, failure: failed('cancelled', describeLoginFailure('cancelled', baseUrl)) };
242
243
  }
@@ -255,7 +256,7 @@ async function authorizeDevice(input, baseUrl, deps, now) {
255
256
  onProgress: input.onProgress,
256
257
  });
257
258
  if (polled.kind === 'token')
258
- return { ok: true, token: polled.token };
259
+ return { ok: true, token: polled.token, accountOnly: started.code.accountOnly === true };
259
260
  return { ok: false, failure: pollFailure(polled, baseUrl) };
260
261
  }
261
262
  /**
@@ -289,8 +290,13 @@ export async function startLogin(input, deps = {}) {
289
290
  getLogger().warn('cli', 'account.login_failed', { baseUrl, reason: 'me_network' });
290
291
  return failed('network', describeTokenRejected(baseUrl));
291
292
  }
292
- const record = buildRecord(baseUrl, authorized.token, me.me, now());
293
- if (!writeAccount(record)) {
293
+ const granted = buildRecord(baseUrl, authorized.token, me.me, now());
294
+ const record = authorized.accountOnly
295
+ ? { ...granted, scopes: granted.scopes.filter(scope => scope === 'account:read') }
296
+ : granted;
297
+ if (!await saveLoginAccount(record, { signal: input.signal })) {
298
+ if (input.signal?.aborted)
299
+ return failed('cancelled', describeLoginFailure('cancelled', baseUrl));
294
300
  getLogger().warn('cli', 'account.login_failed', { baseUrl, reason: 'save' });
295
301
  return failed('invalid', describeSaveFailure(getAccountPath()));
296
302
  }
@@ -84,3 +84,8 @@ export declare function writeAccount(record: AccountRecord): boolean;
84
84
  * caller may then say "sign-out failed" instead of lying.
85
85
  */
86
86
  export declare function clearAccount(): boolean;
87
+ /** Validate and publish the first device grant before the UI announces success. */
88
+ export declare function saveLoginAccount(record: AccountRecord, options?: {
89
+ signal?: AbortSignal;
90
+ expectedToken?: string;
91
+ }): Promise<boolean>;
@@ -27,6 +27,8 @@
27
27
  * `writeAccount()` answers `false`, `clearAccount()` answers whether the file is
28
28
  * gone afterwards.
29
29
  */
30
+ import { withHomeLockSync } from '../cloud-sync/lease.js';
31
+ import { commitLibraryLogin, switchLibraryAccount } from '../cloud-sync/identity.js';
30
32
  import { randomUUID } from 'node:crypto';
31
33
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
32
34
  import process from 'node:process';
@@ -175,6 +177,15 @@ function errorCodeOf(error) {
175
177
  * skipped there rather than warned about.
176
178
  */
177
179
  export function writeAccount(record) {
180
+ try {
181
+ return switchLibraryAccount(getHomeRoot(), record, () => persistAccount(record));
182
+ }
183
+ catch (error) {
184
+ getLogger().warn('cli', 'account.switch_failed', { code: errorCodeOf(error) });
185
+ return false;
186
+ }
187
+ }
188
+ function persistAccount(record) {
178
189
  const path = getAccountPath();
179
190
  const tmp = `${path}.tmp-${process.pid}-${randomUUID().slice(0, 8)}`;
180
191
  const body = `${JSON.stringify({ ...record, version: ACCOUNT_SCHEMA_VERSION }, null, 2)}\n`;
@@ -214,6 +225,21 @@ export function writeAccount(record) {
214
225
  * caller may then say "sign-out failed" instead of lying.
215
226
  */
216
227
  export function clearAccount() {
228
+ try {
229
+ return switchLibraryAccount(getHomeRoot(), null, removeCredential);
230
+ }
231
+ catch (error) {
232
+ // A damaged sidecar must not strand a bearer token. Keep the sidecar for repair.
233
+ try {
234
+ return withHomeLockSync(getHomeRoot(), removeCredential);
235
+ }
236
+ catch {
237
+ getLogger().warn('cli', 'account.clear_failed', { code: errorCodeOf(error) });
238
+ return !existsSync(getAccountPath());
239
+ }
240
+ }
241
+ }
242
+ function removeCredential() {
217
243
  const path = getAccountPath();
218
244
  const existed = existsSync(path);
219
245
  try {
@@ -229,3 +255,15 @@ export function clearAccount() {
229
255
  getLogger().info('cli', 'account.cleared', { path });
230
256
  return true;
231
257
  }
258
+ /** Validate and publish the first device grant before the UI announces success. */
259
+ export async function saveLoginAccount(record, options = {}) {
260
+ try {
261
+ const current = () => !options.signal?.aborted &&
262
+ (options.expectedToken === undefined || readAccount()?.token === options.expectedToken);
263
+ return await commitLibraryLogin(getHomeRoot(), record, current, () => writeAccount(record));
264
+ }
265
+ catch (error) {
266
+ getLogger().warn('cli', 'account.library_claim_failed', { code: errorCodeOf(error) });
267
+ return false;
268
+ }
269
+ }
@@ -15,6 +15,7 @@ import { resolveEscalationPolicy } from '@aragon-agent/tui/model/config/reconnec
15
15
  import { ReconnectMemory } from './reconnect-memory.js';
16
16
  import { resolveModelProfileState } from '@aragon-agent/tui/model/config/model-profile-resolution';
17
17
  import { makeGetApiKey } from '../config/load.js';
18
+ import { managedConfig } from '../config/env.js';
18
19
  import { updatePersistedConfig } from '../config/store.js';
19
20
  import { ModelWindows } from '../config/model-windows.js';
20
21
  import { createBuiltinTools, gatedToolTimeouts, } from '../tools/index.js';
@@ -1922,7 +1923,9 @@ export class AgentController {
1922
1923
  return {
1923
1924
  ok: false,
1924
1925
  kind: 'config',
1925
- message: `No API key for "${provider}" - open /settings or set ${envVar}.`,
1926
+ message: managedConfig
1927
+ ? `No saved API key for "${provider}". Open aragon config and save a model profile or provider key.`
1928
+ : `No API key for "${provider}" - open /settings or set ${envVar}.`,
1926
1929
  };
1927
1930
  }
1928
1931
  return { ok: true };
package/dist/app/App.d.ts CHANGED
@@ -1,9 +1,3 @@
1
- /**
2
- * App — the root Ink component. Owns the view reducer, subscribes to the
3
- * controller's event stream (with a streaming coalescer), wires global
4
- * keybindings, routes slash commands, and renders the header / transcript /
5
- * input / toast stack / status bar / overlays.
6
- */
7
1
  import React from 'react';
8
2
  import type { ScrollbarBridge } from '@aragon-agent/tui/ui/scrollbar-controller';
9
3
  import type { AgentController } from '../agent/controller.js';
package/dist/app/App.js CHANGED
@@ -7,6 +7,7 @@ import { selectTranscriptEntries, mergePendingEntries } from '@aragon-agent/tui/
7
7
  * keybindings, routes slash commands, and renders the header / transcript /
8
8
  * input / toast stack / status bar / overlays.
9
9
  */
10
+ import { startCloudSync } from '../host/cloud-sync.js';
10
11
  import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from 'react';
11
12
  import process from 'node:process';
12
13
  import { basename } from 'node:path';
@@ -864,11 +865,17 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
864
865
  * its countdown is running, that wake starts a turn which redoes the interrupted
865
866
  * work anyway (and delivers a real signal while doing it); arming here would cancel
866
867
  * the wake (`cancelFollowThrough` -> `teamWakeRef.cancel()`) and spend an
867
- * allowance to do the same thing worse. So this yields, silently, WITHOUT charging.
868
+ * allowance to do the same thing worse. So this yields, WITHOUT charging, and says
869
+ * so only in the log.
868
870
  */
869
871
  const armRunResume = (graceMs, notice) => {
870
872
  if (teamWakeRef.current?.isCounting() === true) {
871
- getLogger().debug('agent', 'run_resume_yield', { reason: 'team_wake_counting' });
873
+ // `warn`, NOT `debug` (`network-error-stuck-task` R-1): the shipped log level is
874
+ // `info` (DEFAULT_LOG_CONFIG), so a debug line here is invisible in exactly the
875
+ // log someone reads after a session froze - and this is a recovery that did NOT
876
+ // happen. The wake redoes the same turn, so nothing is lost; if the wake then
877
+ // fails too, this line is the only evidence of which recovery gave way.
878
+ getLogger().warn('agent', 'run_resume_yield', { reason: 'team_wake_counting' });
872
879
  return;
873
880
  }
874
881
  dispatch({ type: 'notice', level: 'info', text: notice });
@@ -896,7 +903,13 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
896
903
  || controller.isCompactionBusy?.() || controller.isRunning()
897
904
  || interactionPhase.current !== 'idle'
898
905
  || controller.areModelSettingsBlocked?.() === true) {
899
- getLogger().debug('agent', 'run_resume_skipped', { reason: 'host_busy' });
906
+ // ANNOUNCED, THEN DROPPED: the notice promising "retrying automatically" is
907
+ // already in the transcript, so `warn` is the floor here, not `debug`
908
+ // (`network-error-stuck-task` R-1). Not every cause leaves the run dead - a
909
+ // compaction that finishes while a message is queued drains it through
910
+ // `drainCompactionQueue` -> `continue()`, which is why this prints no notice -
911
+ // but none of them is worth hiding at the default `info` log level.
912
+ getLogger().warn('agent', 'run_resume_skipped', { reason: 'host_busy' });
900
913
  return;
901
914
  }
902
915
  const preflight = controller.preflight();
@@ -1798,7 +1811,16 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1798
1811
  return next;
1799
1812
  };
1800
1813
  /** `/login` and the panel's `prompt` phase: show the panel, ask the server nothing yet. */
1801
- const openLoginPanel = () => {
1814
+ const localLogin = useRef(false);
1815
+ const syncHost = useRef(null);
1816
+ useEffect(() => {
1817
+ const host = startCloudSync({ cwd: controller.getCwd() });
1818
+ syncHost.current = host;
1819
+ return () => { syncHost.current = null; void host.dispose(); };
1820
+ }, [controller]);
1821
+ const openLoginPanel = (accountOnly = false) => {
1822
+ if (!loginBusy.current)
1823
+ localLogin.current = accountOnly;
1802
1824
  // A FLOW ALREADY IN FLIGHT IS NOT RESET. `/login` typed while the device poll is waiting
1803
1825
  // (a second terminal, a second thought) has to show the code that is still valid; dropping
1804
1826
  // back to `prompt` would hide it behind an Enter that `startLoginFlow` then refuses, and
@@ -1845,7 +1867,12 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1845
1867
  // expires and a panel the user can close; a RE-READ rather than `outcome.account` is
1846
1868
  // what makes "the header shows who I am" a statement about the disk rather than about
1847
1869
  // what the network answered - and it is the same entry point the other four events use.
1848
- refreshAccountSnapshot();
1870
+ const saved = refreshAccountSnapshot();
1871
+ if (!saved?.scopes.includes('library:write'))
1872
+ notify('info', 'This sign-in has no cloud library access.');
1873
+ else
1874
+ notify('info', 'Reopen active sessions to use this account library.');
1875
+ syncHost.current?.wake();
1849
1876
  };
1850
1877
  /**
1851
1878
  * Run one device-flow login, DETACHED from the composer (the panel's Enter, and every retry).
@@ -1866,6 +1893,7 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1866
1893
  let outcome = null;
1867
1894
  try {
1868
1895
  outcome = await startLogin({
1896
+ accountOnly: localLogin.current,
1869
1897
  signal: abort.signal,
1870
1898
  onCode: (code) => {
1871
1899
  if (!mounted.current)
@@ -1929,6 +1957,8 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1929
1957
  const signOutAccount = () => {
1930
1958
  const hadCredential = readAccountStatus().state !== 'signed-out';
1931
1959
  const ok = clearAccount();
1960
+ if (ok)
1961
+ syncHost.current?.wake();
1932
1962
  refreshAccountSnapshot();
1933
1963
  return { ok, hadCredential };
1934
1964
  };
@@ -1954,6 +1984,7 @@ export function App({ controller, version, initialOverlay, initialPrompt, confir
1954
1984
  accountPath: getAccountPath,
1955
1985
  openLogin: openLoginPanel,
1956
1986
  openAccount: openAccountPanel,
1987
+ cloudSync: () => syncHost.current,
1957
1988
  signOut: () => signOutAccount(),
1958
1989
  });
1959
1990
  return {};
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ import { renderTui as render } from '@aragon-agent/tui/ui/ink-runtime';
7
7
  import { Command } from 'commander';
8
8
  import { ModelProfileConfigError } from './config/model-profile-store.js';
9
9
  import { loadConfig } from './config/load.js';
10
+ import { enableManagedConfig } from './config/env.js';
10
11
  import { getConfigPath, readConfigFile, updatePersistedConfig } from './config/store.js';
11
12
  import { formatMigrationNotice, migrateLegacyState } from './config/migrate-legacy-state.js';
12
13
  import { formatHomeMigrationNotice, migrateToHome } from './config/migrate-home.js';
@@ -2061,6 +2062,7 @@ function buildProgram() {
2061
2062
  .option('--provider <id>', 'anthropic | openai | google')
2062
2063
  .option('--model <id>', 'Model id')
2063
2064
  .option('--base-url <url>', 'Override the provider base URL')
2065
+ .option('--managed-config', 'Use saved Aragon connections and keys; skip project .env and inherited model credentials')
2064
2066
  .option('--api-key <key>', 'One-shot API key override (not persisted)')
2065
2067
  .option('--thinking <level>', 'off|minimal|low|medium|high|xhigh')
2066
2068
  .option('--max-tokens <n|auto>', 'Output token cap: a number, or "auto" for the model ceiling (default 64000)')
@@ -2244,6 +2246,10 @@ function buildProgram() {
2244
2246
  }
2245
2247
  void runInteractive(flags, { initialPrompt: prompt });
2246
2248
  });
2249
+ program.hook('preAction', (root) => {
2250
+ if (root.opts().managedConfig)
2251
+ enableManagedConfig();
2252
+ });
2247
2253
  // The governance flag rules (governance-mode 11.2), checked for EVERY command because the
2248
2254
  // flags are root-level options and `exec` reads them through `toFlags(program.opts())`.
2249
2255
  // A `preAction` hook runs before the root action as well as before each subcommand, so one
@@ -0,0 +1,64 @@
1
+ import { type LibraryKind, type Content, type LibraryAdapter } from './protocol.js';
2
+ export interface CloudConflict {
3
+ key: string;
4
+ itemId: string;
5
+ space: string;
6
+ kind: LibraryKind;
7
+ local: Content | null;
8
+ remote: Content | null;
9
+ remoteDeleted: boolean;
10
+ }
11
+ export interface CloudSyncStatus {
12
+ state: string;
13
+ username: string | null;
14
+ baseUrl: string | null;
15
+ generation: string;
16
+ lastReceivedAt: number | null;
17
+ pendingSend: number;
18
+ pendingApply: number;
19
+ conflicts: CloudConflict[];
20
+ boundSpace: string | null;
21
+ message: string | null;
22
+ issues: Array<{
23
+ space: string;
24
+ kind: LibraryKind;
25
+ itemId: string;
26
+ reason: string;
27
+ }>;
28
+ }
29
+ export declare class LibraryCoordinator {
30
+ readonly cwd: string;
31
+ readonly adapters: Record<LibraryKind, LibraryAdapter>;
32
+ private view;
33
+ private lease;
34
+ private active;
35
+ private queued;
36
+ private stopped;
37
+ private abort;
38
+ private nextTry;
39
+ private retryToken;
40
+ private retryTimer?;
41
+ private editTimer?;
42
+ private failures;
43
+ private deadToken;
44
+ private receiptAt;
45
+ private receiptToken;
46
+ private receiptMark;
47
+ private readonly listeners;
48
+ private readonly timer;
49
+ private readonly detach;
50
+ constructor(cwd: string, adapters: Record<LibraryKind, LibraryAdapter>);
51
+ status(): CloudSyncStatus;
52
+ subscribe(fn: (v: CloudSyncStatus) => void): () => void;
53
+ private emit;
54
+ wake(): void;
55
+ private context;
56
+ private requireContext;
57
+ private summary;
58
+ private cycle;
59
+ private reset;
60
+ bind(space: string, cwd?: string): Promise<void>;
61
+ unbind(cwd?: string): Promise<void>;
62
+ resolve(key: string, choice: 'remote' | 'copy' | 'local'): Promise<void>;
63
+ dispose(): Promise<void>;
64
+ }