@andorra-labs/code 0.1.13 → 0.1.15

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 (168) hide show
  1. package/dist/src/account-presentation.js +4 -1
  2. package/dist/src/acp-agent.d.ts +54 -0
  3. package/dist/src/acp-agent.js +991 -0
  4. package/dist/src/agent-execution.js +304 -140
  5. package/dist/src/agent-mcp-catalog.js +2 -0
  6. package/dist/src/agent-mcp.d.ts +2 -0
  7. package/dist/src/agent-mcp.js +86 -4
  8. package/dist/src/andorra/endpoint.d.ts +7 -0
  9. package/dist/src/andorra/endpoint.js +46 -0
  10. package/dist/src/andorra/entry.d.ts +21 -0
  11. package/dist/src/andorra/entry.js +118 -0
  12. package/dist/src/andorra/errors.d.ts +2 -0
  13. package/dist/src/andorra/errors.js +39 -0
  14. package/dist/src/andorra/hosted.d.ts +55 -0
  15. package/dist/src/andorra/hosted.js +130 -0
  16. package/dist/src/andorra/monitor.d.ts +151 -0
  17. package/dist/src/andorra/monitor.js +393 -0
  18. package/dist/src/andorra/notices.d.ts +16 -0
  19. package/dist/src/andorra/notices.js +38 -0
  20. package/dist/src/andorra/opt-in.d.ts +58 -0
  21. package/dist/src/andorra/opt-in.js +112 -0
  22. package/dist/src/andorra/request-watch.d.ts +6 -0
  23. package/dist/src/andorra/request-watch.js +10 -0
  24. package/dist/src/andorra/state.d.ts +86 -0
  25. package/dist/src/andorra/state.js +238 -0
  26. package/dist/src/andorra/terminal.d.ts +70 -0
  27. package/dist/src/andorra/terminal.js +125 -0
  28. package/dist/src/andorra/usage-format.d.ts +9 -0
  29. package/dist/src/andorra/usage-format.js +19 -0
  30. package/dist/src/anthropic-credentials.js +9 -1
  31. package/dist/src/app-server/protocol.d.ts +10 -2
  32. package/dist/src/app-server/protocol.js +1 -1
  33. package/dist/src/app-server/workspace.d.ts +1 -0
  34. package/dist/src/app-server/workspace.js +141 -10
  35. package/dist/src/app-server.d.ts +35 -0
  36. package/dist/src/app-server.js +377 -124
  37. package/dist/src/auth/AuthManager.d.ts +9 -0
  38. package/dist/src/auth/AuthManager.js +164 -24
  39. package/dist/src/auth/deployment.d.ts +1 -0
  40. package/dist/src/auth/deployment.js +1 -0
  41. package/dist/src/auth/index.d.ts +1 -1
  42. package/dist/src/auth/index.js +1 -1
  43. package/dist/src/auth/store.d.ts +26 -0
  44. package/dist/src/auth/store.js +34 -1
  45. package/dist/src/browser-bridge.d.ts +1 -0
  46. package/dist/src/browser-bridge.js +5 -2
  47. package/dist/src/browser-external-app.d.ts +27 -0
  48. package/dist/src/browser-external-app.js +60 -0
  49. package/dist/src/browser-panel-tool.d.ts +6 -0
  50. package/dist/src/browser-panel-tool.js +36 -0
  51. package/dist/src/browser-runner.js +1 -1
  52. package/dist/src/browser-server.d.ts +5 -0
  53. package/dist/src/browser-server.js +27 -3
  54. package/dist/src/browser-stealth.d.ts +19 -1
  55. package/dist/src/browser-stealth.js +23 -3
  56. package/dist/src/browser-ui/tokens.css +4 -4
  57. package/dist/src/browser-view.d.ts +81 -0
  58. package/dist/src/browser-view.js +289 -18
  59. package/dist/src/bug-report.d.ts +81 -0
  60. package/dist/src/bug-report.js +235 -0
  61. package/dist/src/claude-provider.d.ts +2 -1
  62. package/dist/src/claude-provider.js +10 -8
  63. package/dist/src/cli-sign-in.d.ts +3 -1
  64. package/dist/src/cli-sign-in.js +4 -1
  65. package/dist/src/cli.js +205 -58
  66. package/dist/src/coding-tools.js +7 -7
  67. package/dist/src/command-screens.d.ts +26 -3
  68. package/dist/src/command-screens.js +323 -85
  69. package/dist/src/commands.d.ts +7 -1
  70. package/dist/src/commands.js +79 -27
  71. package/dist/src/completion-gates.d.ts +22 -0
  72. package/dist/src/completion-gates.js +11 -0
  73. package/dist/src/config.d.ts +11 -1
  74. package/dist/src/config.js +134 -3
  75. package/dist/src/dashboard-view.d.ts +2 -0
  76. package/dist/src/dashboard-view.js +11 -2
  77. package/dist/src/decision/PreparedSteps.js +1 -1
  78. package/dist/src/decision/applyToolMenu.js +1 -1
  79. package/dist/src/decision/toolFamilies.js +1 -1
  80. package/dist/src/decision/types.d.ts +1 -0
  81. package/dist/src/google-provider.d.ts +31 -0
  82. package/dist/src/google-provider.js +153 -0
  83. package/dist/src/graph-health.d.ts +11 -0
  84. package/dist/src/graph-health.js +36 -4
  85. package/dist/src/graph-manager-chat.d.ts +33 -0
  86. package/dist/src/graph-manager-chat.js +165 -6
  87. package/dist/src/graph-runner.js +27 -0
  88. package/dist/src/graph-selection.js +2 -1
  89. package/dist/src/graph-sync.d.ts +1 -0
  90. package/dist/src/graph-sync.js +93 -34
  91. package/dist/src/graph-tool.d.ts +2 -0
  92. package/dist/src/graph-tool.js +2 -2
  93. package/dist/src/graph-ui/app.js +92 -10
  94. package/dist/src/graph-ui/edge-router.js +121 -53
  95. package/dist/src/graph-ui/manager.js +40 -5
  96. package/dist/src/graph-ui/style.css +5 -2
  97. package/dist/src/graph-ui/tokens.css +4 -4
  98. package/dist/src/graph-visibility.d.ts +31 -0
  99. package/dist/src/graph-visibility.js +102 -0
  100. package/dist/src/graphs.js +1 -3
  101. package/dist/src/hardened-runtime.js +1 -1
  102. package/dist/src/live-model.d.ts +24 -0
  103. package/dist/src/live-model.js +37 -0
  104. package/dist/src/managed-sign-in.d.ts +1 -0
  105. package/dist/src/managed-sign-in.js +13 -0
  106. package/dist/src/membership-errors.d.ts +2 -0
  107. package/dist/src/membership-errors.js +6 -2
  108. package/dist/src/membership.d.ts +13 -2
  109. package/dist/src/membership.js +39 -8
  110. package/dist/src/model-context-windows.d.ts +2 -0
  111. package/dist/src/model-context-windows.js +24 -0
  112. package/dist/src/model-health-cache.js +1 -1
  113. package/dist/src/model-metadata.d.ts +1 -0
  114. package/dist/src/model-metadata.js +47 -3
  115. package/dist/src/paged-transcript.d.ts +2 -0
  116. package/dist/src/paged-transcript.js +16 -0
  117. package/dist/src/palette.d.ts +1 -0
  118. package/dist/src/palette.js +1 -1
  119. package/dist/src/permissions.js +17 -4
  120. package/dist/src/provider-connection.js +32 -0
  121. package/dist/src/provider-engine.d.ts +5 -0
  122. package/dist/src/provider-engine.js +3 -3
  123. package/dist/src/provider-import.js +3 -1
  124. package/dist/src/provider-settings.d.ts +16 -1
  125. package/dist/src/provider-settings.js +50 -22
  126. package/dist/src/providers.d.ts +29 -3
  127. package/dist/src/providers.js +100 -18
  128. package/dist/src/react-runtime.js +33 -12
  129. package/dist/src/read-document-tool.d.ts +2 -0
  130. package/dist/src/read-document-tool.js +6 -6
  131. package/dist/src/remote/engine-pool.js +31 -6
  132. package/dist/src/run-control.d.ts +2 -2
  133. package/dist/src/run-control.js +9 -6
  134. package/dist/src/runtime-environment.d.ts +1 -0
  135. package/dist/src/runtime-environment.js +13 -0
  136. package/dist/src/runtime.d.ts +2 -0
  137. package/dist/src/runtime.js +2 -1
  138. package/dist/src/save-lock.js +14 -7
  139. package/dist/src/session-title.d.ts +3 -0
  140. package/dist/src/session-title.js +5 -2
  141. package/dist/src/sessions.d.ts +1 -0
  142. package/dist/src/sessions.js +4 -2
  143. package/dist/src/sign-in-detection.d.ts +1 -1
  144. package/dist/src/sign-in-detection.js +10 -3
  145. package/dist/src/sign-in-offer.js +1 -1
  146. package/dist/src/skill-commands.js +1 -1
  147. package/dist/src/skills/bundled/bug-report/SKILL.md +80 -0
  148. package/dist/src/skills/bundled/graph-manager/SKILL.md +9 -1
  149. package/dist/src/skills/bundled/graph-manager/errors.md +2 -1
  150. package/dist/src/skills/bundled/provenance.json +743 -738
  151. package/dist/src/skills/runtime-skills.js +1 -0
  152. package/dist/src/subagent-run.d.ts +2 -0
  153. package/dist/src/subagent-run.js +14 -3
  154. package/dist/src/telemetry/schema.d.ts +1 -1
  155. package/dist/src/telemetry/schema.js +2 -2
  156. package/dist/src/telemetry/uploader.d.ts +7 -1
  157. package/dist/src/telemetry/uploader.js +11 -2
  158. package/dist/src/terminal-links.d.ts +16 -0
  159. package/dist/src/terminal-links.js +113 -0
  160. package/dist/src/terminal-ui.d.ts +29 -1
  161. package/dist/src/terminal-ui.js +113 -24
  162. package/dist/src/tool-catalog.js +1 -1
  163. package/dist/src/trajectory.js +6 -1
  164. package/dist/src/transcript.d.ts +2 -0
  165. package/dist/src/transcript.js +5 -1
  166. package/dist/src/types.d.ts +5 -0
  167. package/dist/src/workspace-instructions.js +1 -1
  168. package/package.json +13 -1
@@ -0,0 +1,151 @@
1
+ import { type HostedAnswer, type HostedCheck, type HostedModel } from './hosted.js';
2
+ import { type AndorraAvailability, type HostedSurface } from './state.js';
3
+ export declare const HOSTED_CHECK_INTERVAL_MS: number;
4
+ export declare const HOSTED_OPEN_THROTTLE_MS = 30000;
5
+ /**
6
+ * How soon the router is asked again after a check failed or answered that nothing can serve a request, while
7
+ * signed in with an enabled answer on hand: an account with nothing to show is not asked every minute in an outage.
8
+ */
9
+ export declare const HOSTED_RETRY_INTERVAL_MS = 60000;
10
+ /** How many counted failures in a row (see HOSTED_FAILURE_SPACING_MS) make the usage read "not available". */
11
+ export declare const HOSTED_FAILURES_TO_UNAVAILABLE = 2;
12
+ /**
13
+ * A failed check counts toward HOSTED_FAILURES_TO_UNAVAILABLE only this long after the last failure that counted (the
14
+ * first always counts), so one blip seen by two checks moments apart (an interval check and a run-end check) is one failure.
15
+ */
16
+ export declare const HOSTED_FAILURE_SPACING_MS = 30000;
17
+ /**
18
+ * `account`: the user signed in or out. `add`: the user asked to add Andorra. `gate`: a run is about to start.
19
+ * `run-end`: a run that used an Andorra model ended. `retry`: the follow-up after a failed or unavailable check.
20
+ * Only `open` is throttled.
21
+ */
22
+ export type HostedCheckCause = 'startup' | 'interval' | 'open' | 'account' | 'add' | 'gate' | 'run-end' | 'retry';
23
+ /** What a client shows for the hosted models: the share of the weekly allowance used, or that they cannot answer now. */
24
+ export type HostedUsage = {
25
+ kind: 'meter';
26
+ usedPercent: number;
27
+ resetsAt: string;
28
+ } | {
29
+ kind: 'not-available';
30
+ };
31
+ export interface HostedTimers {
32
+ setInterval: typeof setInterval;
33
+ clearInterval: typeof clearInterval;
34
+ setTimeout?: typeof setTimeout;
35
+ clearTimeout?: typeof clearTimeout;
36
+ }
37
+ /** How long an answer counts as fresh: for refusing a run without asking again, and for adding without asking first. */
38
+ export declare const HOSTED_FRESH_MS = 30000;
39
+ export interface HostedAnnouncement {
40
+ promotionId: string;
41
+ offered: boolean;
42
+ }
43
+ export interface HostedMonitorOptions {
44
+ surface: HostedSurface;
45
+ home?: string;
46
+ check?: (signal?: AbortSignal) => Promise<HostedCheck>;
47
+ /**
48
+ * Called for enabled answers only: keeps an existing entry current, and creates a missing one only when the
49
+ * user added Andorra. It reads that decision itself (`andorraEntryMode`) inside its serialized config write.
50
+ */
51
+ applyEntry: (answer: HostedAnswer) => Promise<void>;
52
+ /** Whether the saved config holds an Andorra entry now. */
53
+ hasEntry: () => boolean | Promise<boolean>;
54
+ /** `offered`: there is no entry yet, so the message should say how to add one. */
55
+ onAnnounce: (announcement: HostedAnnouncement) => void;
56
+ onNotice: () => void;
57
+ /** Fired after every check has settled and after `entryChanged()`, whether or not anything differs: for lists that redraw themselves. */
58
+ onSettled?: () => void;
59
+ /** Fired when the availability, the offer, the listed models or the usage differ from the last ones reported. */
60
+ onChange?: (availability: AndorraAvailability, offered: boolean) => void;
61
+ now?: () => number;
62
+ timers?: HostedTimers;
63
+ }
64
+ /**
65
+ * Keeps one client's view of whether Andorra is offered: checks at startup, every
66
+ * HOSTED_CHECK_INTERVAL_MS, and when the provider list opens (at most once per
67
+ * HOSTED_OPEN_THROTTLE_MS). A failed check never changes the snapshot, the entry or the messages;
68
+ * it only counts toward the usage reading "not available", and asks again after HOSTED_RETRY_INTERVAL_MS.
69
+ * It creates nothing by itself: the entry appears when the user adds it (`addAndorraEntry`).
70
+ */
71
+ export declare class HostedMonitor {
72
+ private readonly options;
73
+ private readonly home;
74
+ private readonly runCheck;
75
+ private readonly now;
76
+ private readonly timers;
77
+ private answer;
78
+ /** The allowance and availability of the last answer a check in this process received; never read from the state file. */
79
+ private live;
80
+ private failures;
81
+ private failedAt;
82
+ private retry;
83
+ private signedIn;
84
+ private answeredAt;
85
+ private entryPresent;
86
+ private reported;
87
+ private decision;
88
+ private inflight;
89
+ private lastOpen;
90
+ private handle;
91
+ private stopped;
92
+ private generation;
93
+ private abort;
94
+ /** What this surface has shown, kept here while the state file could not be written, so nothing replays. */
95
+ private unsaved;
96
+ constructor(options: HostedMonitorOptions);
97
+ start(): Promise<void>;
98
+ check(cause: HostedCheckCause): Promise<AndorraAvailability>;
99
+ availability(): AndorraAvailability;
100
+ /**
101
+ * What to show for the hosted models: nothing while signed out or without an enabled answer on hand (received
102
+ * in this process, or saved by an earlier one); "not available" after HOSTED_FAILURES_TO_UNAVAILABLE counted
103
+ * failures in a row (see HOSTED_FAILURE_SPACING_MS); otherwise, from an answer received in this process only, "not
104
+ * available" when the router said nothing can answer, or the allowance used when it sent one. A saved answer holds no allowance, so it never gives a meter.
105
+ */
106
+ usage(): HostedUsage | undefined;
107
+ /** True when a check in this process answered (an answer, or signed out) within the last HOSTED_FRESH_MS. */
108
+ answeredRecently(): boolean;
109
+ /**
110
+ * What a run about to start on Andorra may rely on without sending a model request. A refusal is returned only
111
+ * from fresh knowledge: an "off" answer of the last HOSTED_FRESH_MS, or a check made right now. Anything older
112
+ * (and every "signed out", because another process sharing this home may have signed in since, and asking again
113
+ * costs nothing while still signed out) is asked again first: one check, bounded by the check's own timeout. A
114
+ * check already under way (the one after /login, say) is awaited rather than answered around. Undefined means
115
+ * nothing is known (no check has answered, or the one just made failed): the run's own probe then decides.
116
+ */
117
+ gate(): Promise<AndorraAvailability | undefined>;
118
+ /** The answer Andorra can be added from: one a check in this process received, signed in, turned on, with models. */
119
+ enabledAnswer(): HostedAnswer | undefined;
120
+ /** The hosted models while Andorra is offered to this account and not added yet; undefined otherwise. */
121
+ offer(): HostedModel[] | undefined;
122
+ /** Whether Andorra can be added now: hosted models are on for this account and the config has no entry. */
123
+ offered(): boolean;
124
+ /**
125
+ * The hosted models while Andorra is LISTED without being saved: offered, and not removed by the user. A client
126
+ * shows it then as an ordinary provider, first in its lists; the entry is written the first time the user picks it.
127
+ */
128
+ listed(): HostedModel[] | undefined;
129
+ /** Call after the entry was added or removed: reports the changed offer. */
130
+ entryChanged(): Promise<void>;
131
+ stop(): void;
132
+ /** Asks again after HOSTED_RETRY_INTERVAL_MS: one pending retry at most, replaced each time. */
133
+ private armRetry;
134
+ private clearRetry;
135
+ /** The user's decision as the state file has it; the last one known when the file cannot be read. */
136
+ private decided;
137
+ private present;
138
+ private report;
139
+ private run;
140
+ /**
141
+ * Records what the usage is read from, apart from the answer so it never reaches the state file, and asks
142
+ * again soon while the router cannot be reached or says nothing can answer, for an account that has hosted models
143
+ * to show: signed in, with the answer on hand (this one, or the one held before a failed check) enabled.
144
+ */
145
+ private track;
146
+ private settle;
147
+ /** Writes the state through the shared queue; while it cannot be written, what was shown is remembered here. */
148
+ private save;
149
+ private messages;
150
+ private fire;
151
+ }
@@ -0,0 +1,393 @@
1
+ import { configDirectory } from '../config.js';
2
+ import { defaultHostedCheck } from './hosted.js';
3
+ import { advanceSurface, andorraAvailability, readHostedState, updateHostedState } from './state.js';
4
+ export const HOSTED_CHECK_INTERVAL_MS = 15 * 60_000;
5
+ export const HOSTED_OPEN_THROTTLE_MS = 30_000;
6
+ /**
7
+ * How soon the router is asked again after a check failed or answered that nothing can serve a request, while
8
+ * signed in with an enabled answer on hand: an account with nothing to show is not asked every minute in an outage.
9
+ */
10
+ export const HOSTED_RETRY_INTERVAL_MS = 60_000;
11
+ /** How many counted failures in a row (see HOSTED_FAILURE_SPACING_MS) make the usage read "not available". */
12
+ export const HOSTED_FAILURES_TO_UNAVAILABLE = 2;
13
+ /**
14
+ * A failed check counts toward HOSTED_FAILURES_TO_UNAVAILABLE only this long after the last failure that counted (the
15
+ * first always counts), so one blip seen by two checks moments apart (an interval check and a run-end check) is one failure.
16
+ */
17
+ export const HOSTED_FAILURE_SPACING_MS = 30_000;
18
+ /** How long an answer counts as fresh: for refusing a run without asking again, and for adding without asking first. */
19
+ export const HOSTED_FRESH_MS = 30_000;
20
+ const sameAvailability = (a, b) => !!a && a.available === b.available && (a.available || b.available || a.message === b.message);
21
+ /**
22
+ * Keeps one client's view of whether Andorra is offered: checks at startup, every
23
+ * HOSTED_CHECK_INTERVAL_MS, and when the provider list opens (at most once per
24
+ * HOSTED_OPEN_THROTTLE_MS). A failed check never changes the snapshot, the entry or the messages;
25
+ * it only counts toward the usage reading "not available", and asks again after HOSTED_RETRY_INTERVAL_MS.
26
+ * It creates nothing by itself: the entry appears when the user adds it (`addAndorraEntry`).
27
+ */
28
+ export class HostedMonitor {
29
+ options;
30
+ home;
31
+ runCheck;
32
+ now;
33
+ timers;
34
+ answer;
35
+ /** The allowance and availability of the last answer a check in this process received; never read from the state file. */
36
+ live;
37
+ failures = 0; // counted failures in a row; any answer (signed out included) starts it over
38
+ failedAt; // when the last counted failure happened
39
+ retry;
40
+ signedIn = true;
41
+ answeredAt; // when a check in this process last came back with the router's word (an answer, or signed out)
42
+ entryPresent = false;
43
+ reported;
44
+ decision; // the user's decision, as last read from the state file
45
+ inflight;
46
+ lastOpen;
47
+ handle;
48
+ stopped = false;
49
+ generation = 0; // bumped by stop(): a check begun before it settles nothing
50
+ abort = new AbortController();
51
+ /** What this surface has shown, kept here while the state file could not be written, so nothing replays. */
52
+ unsaved;
53
+ constructor(options) {
54
+ this.options = options;
55
+ this.home = options.home ?? configDirectory();
56
+ this.runCheck = options.check ?? defaultHostedCheck();
57
+ this.now = options.now ?? Date.now;
58
+ const timers = options.timers;
59
+ this.timers = {
60
+ setInterval: timers?.setInterval ?? setInterval,
61
+ clearInterval: timers?.clearInterval ?? clearInterval,
62
+ setTimeout: timers?.setTimeout ?? setTimeout,
63
+ clearTimeout: timers?.clearTimeout ?? clearTimeout,
64
+ };
65
+ }
66
+ async start() {
67
+ this.stopped = false;
68
+ this.failures = 0;
69
+ this.failedAt = undefined;
70
+ try {
71
+ const state = await readHostedState(this.home);
72
+ this.answer = state.answer;
73
+ this.decision = state.entry;
74
+ }
75
+ catch { /* no saved answer */ }
76
+ this.entryPresent = await this.present();
77
+ await this.check('startup');
78
+ if (this.stopped || this.handle !== undefined)
79
+ return;
80
+ const handle = this.timers.setInterval(() => { void this.check('interval'); }, HOSTED_CHECK_INTERVAL_MS);
81
+ handle?.unref?.();
82
+ this.handle = handle;
83
+ }
84
+ check(cause) {
85
+ // Stopped (the client is closing): nothing is asked and no retry is armed.
86
+ if (this.stopped)
87
+ return Promise.resolve(this.availability());
88
+ if (cause === 'open') {
89
+ const at = this.now();
90
+ // A clock set backwards gives a negative gap: that counts as elapsed, not as "just checked".
91
+ const gap = this.lastOpen === undefined ? undefined : at - this.lastOpen;
92
+ if (gap !== undefined && gap >= 0 && gap < HOSTED_OPEN_THROTTLE_MS)
93
+ return Promise.resolve(this.availability());
94
+ this.lastOpen = at;
95
+ }
96
+ if (this.inflight) {
97
+ // A check already out may carry the token of the account that was signed in before: ask again after it.
98
+ if (cause !== 'account')
99
+ return this.inflight;
100
+ const again = this.inflight.then(() => this.run(cause)).finally(() => { if (this.inflight === again)
101
+ this.inflight = undefined; });
102
+ this.inflight = again;
103
+ return again;
104
+ }
105
+ const running = this.run(cause).finally(() => { if (this.inflight === running)
106
+ this.inflight = undefined; });
107
+ this.inflight = running;
108
+ return running;
109
+ }
110
+ availability() {
111
+ return andorraAvailability(this.answer, this.signedIn);
112
+ }
113
+ /**
114
+ * What to show for the hosted models: nothing while signed out or without an enabled answer on hand (received
115
+ * in this process, or saved by an earlier one); "not available" after HOSTED_FAILURES_TO_UNAVAILABLE counted
116
+ * failures in a row (see HOSTED_FAILURE_SPACING_MS); otherwise, from an answer received in this process only, "not
117
+ * available" when the router said nothing can answer, or the allowance used when it sent one. A saved answer holds no allowance, so it never gives a meter.
118
+ */
119
+ usage() {
120
+ if (!this.signedIn || !this.answer?.enabled)
121
+ return undefined;
122
+ if (this.failures >= HOSTED_FAILURES_TO_UNAVAILABLE)
123
+ return { kind: 'not-available' };
124
+ if (this.answeredAt === undefined)
125
+ return undefined;
126
+ if (this.live?.available === false)
127
+ return { kind: 'not-available' };
128
+ const allowance = this.live?.allowance;
129
+ return allowance ? { kind: 'meter', usedPercent: allowance.usedPercent, resetsAt: allowance.resetsAt } : undefined;
130
+ }
131
+ /** True when a check in this process answered (an answer, or signed out) within the last HOSTED_FRESH_MS. */
132
+ answeredRecently() {
133
+ if (this.answeredAt === undefined)
134
+ return false;
135
+ const gap = this.now() - this.answeredAt;
136
+ return gap >= 0 && gap < HOSTED_FRESH_MS;
137
+ }
138
+ /**
139
+ * What a run about to start on Andorra may rely on without sending a model request. A refusal is returned only
140
+ * from fresh knowledge: an "off" answer of the last HOSTED_FRESH_MS, or a check made right now. Anything older
141
+ * (and every "signed out", because another process sharing this home may have signed in since, and asking again
142
+ * costs nothing while still signed out) is asked again first: one check, bounded by the check's own timeout. A
143
+ * check already under way (the one after /login, say) is awaited rather than answered around. Undefined means
144
+ * nothing is known (no check has answered, or the one just made failed): the run's own probe then decides.
145
+ */
146
+ async gate() {
147
+ if (this.inflight)
148
+ await this.inflight;
149
+ if (this.answeredAt === undefined)
150
+ return undefined;
151
+ const before = this.availability();
152
+ if (before.available)
153
+ return before;
154
+ if (this.signedIn && this.answeredRecently())
155
+ return before;
156
+ const asked = this.answeredAt;
157
+ await this.check('gate');
158
+ // The check answered if the time of the last answer moved (or is still fresh under a clock that did not).
159
+ return this.answeredAt !== asked || this.answeredRecently() ? this.availability() : undefined;
160
+ }
161
+ /** The answer Andorra can be added from: one a check in this process received, signed in, turned on, with models. */
162
+ enabledAnswer() {
163
+ return this.answeredAt !== undefined && this.signedIn && this.answer?.enabled && this.answer.models.length > 0 ? this.answer : undefined;
164
+ }
165
+ /** The hosted models while Andorra is offered to this account and not added yet; undefined otherwise. */
166
+ offer() {
167
+ return this.entryPresent ? undefined : this.enabledAnswer()?.models;
168
+ }
169
+ /** Whether Andorra can be added now: hosted models are on for this account and the config has no entry. */
170
+ offered() {
171
+ return this.offer() !== undefined;
172
+ }
173
+ /**
174
+ * The hosted models while Andorra is LISTED without being saved: offered, and not removed by the user. A client
175
+ * shows it then as an ordinary provider, first in its lists; the entry is written the first time the user picks it.
176
+ */
177
+ listed() {
178
+ return this.decision === 'removed' ? undefined : this.offer();
179
+ }
180
+ /** Call after the entry was added or removed: reports the changed offer. */
181
+ async entryChanged() {
182
+ const generation = this.generation;
183
+ const present = await this.present();
184
+ const decision = await this.decided();
185
+ if (this.generation !== generation)
186
+ return;
187
+ this.entryPresent = present;
188
+ this.decision = decision;
189
+ this.report();
190
+ this.fire(() => this.options.onSettled?.());
191
+ }
192
+ stop() {
193
+ this.stopped = true;
194
+ this.generation++;
195
+ this.abort.abort();
196
+ this.abort = new AbortController();
197
+ if (this.handle !== undefined) {
198
+ this.timers.clearInterval(this.handle);
199
+ this.handle = undefined;
200
+ }
201
+ this.clearRetry();
202
+ }
203
+ /** Asks again after HOSTED_RETRY_INTERVAL_MS: one pending retry at most, replaced each time. */
204
+ armRetry() {
205
+ this.clearRetry();
206
+ const retry = this.timers.setTimeout(() => { if (this.retry === retry)
207
+ this.retry = undefined; void this.check('retry'); }, HOSTED_RETRY_INTERVAL_MS);
208
+ retry?.unref?.();
209
+ this.retry = retry;
210
+ }
211
+ clearRetry() {
212
+ if (this.retry !== undefined) {
213
+ this.timers.clearTimeout(this.retry);
214
+ this.retry = undefined;
215
+ }
216
+ }
217
+ /** The user's decision as the state file has it; the last one known when the file cannot be read. */
218
+ async decided() {
219
+ try {
220
+ return (await readHostedState(this.home)).entry;
221
+ }
222
+ catch {
223
+ return this.decision;
224
+ }
225
+ }
226
+ async present() {
227
+ try {
228
+ return await this.options.hasEntry();
229
+ }
230
+ catch {
231
+ return this.entryPresent;
232
+ }
233
+ }
234
+ report() {
235
+ const availability = this.availability();
236
+ const offered = this.offered();
237
+ const listed = JSON.stringify(this.listed() ?? null);
238
+ const usage = JSON.stringify(this.usage() ?? null);
239
+ if (this.reported && sameAvailability(this.reported.availability, availability) && this.reported.offered === offered && this.reported.listed === listed && this.reported.usage === usage)
240
+ return;
241
+ this.reported = { availability, offered, listed, usage };
242
+ this.fire(() => this.options.onChange?.(availability, offered));
243
+ }
244
+ async run(cause) {
245
+ const generation = this.generation;
246
+ const current = () => this.generation === generation;
247
+ let result;
248
+ try {
249
+ result = await this.runCheck(this.abort.signal);
250
+ }
251
+ catch {
252
+ result = { kind: 'failed' };
253
+ }
254
+ // Stopped while the check was out (the app is closing): nobody would see a message, so none is
255
+ // fired or recorded as shown, and the state file is left for the next start.
256
+ if (!current())
257
+ return this.availability();
258
+ this.track(result);
259
+ let messages;
260
+ try {
261
+ messages = await this.settle(result, cause, current);
262
+ }
263
+ catch { /* never reject a check */ }
264
+ if (!current())
265
+ return this.availability();
266
+ this.decision = await this.decided();
267
+ if (!current())
268
+ return this.availability();
269
+ this.report();
270
+ // The status goes out first, so a client that reads "offered" from it has it when the announcement lands.
271
+ if (messages)
272
+ this.messages(messages);
273
+ // Last, after the announcement was printed: an open list redraws itself over whatever the print did.
274
+ this.fire(() => this.options.onSettled?.());
275
+ return this.availability();
276
+ }
277
+ /**
278
+ * Records what the usage is read from, apart from the answer so it never reaches the state file, and asks
279
+ * again soon while the router cannot be reached or says nothing can answer, for an account that has hosted models
280
+ * to show: signed in, with the answer on hand (this one, or the one held before a failed check) enabled.
281
+ */
282
+ track(result) {
283
+ if (result.kind === 'failed') {
284
+ const at = this.now();
285
+ // A clock set backwards gives a negative gap: that counts as elapsed.
286
+ const gap = this.failedAt === undefined ? undefined : at - this.failedAt;
287
+ if (gap === undefined || gap < 0 || gap >= HOSTED_FAILURE_SPACING_MS) {
288
+ this.failures++;
289
+ this.failedAt = at;
290
+ }
291
+ }
292
+ else {
293
+ this.failures = 0;
294
+ this.failedAt = undefined;
295
+ this.live = result.kind === 'answer' ? { allowance: result.answer.allowance, available: result.answer.available } : undefined;
296
+ }
297
+ const showsModels = result.kind === 'answer' ? result.answer.enabled : result.kind === 'failed' && this.signedIn && !!this.answer?.enabled;
298
+ if (showsModels && (result.kind === 'failed' || (result.kind === 'answer' && result.answer.available === false)))
299
+ this.armRetry();
300
+ else
301
+ this.clearRetry();
302
+ }
303
+ async settle(result, cause, current) {
304
+ if (result.kind === 'signed-out') {
305
+ this.signedIn = false;
306
+ this.answeredAt = this.now();
307
+ return undefined;
308
+ }
309
+ if (result.kind === 'failed') {
310
+ // Only the startup check replays a persisted answer, so its messages still reach this
311
+ // client; the answer and the entry are left exactly as they were.
312
+ if (cause !== 'startup' || !this.answer)
313
+ return undefined;
314
+ const state = await readHostedState(this.home);
315
+ if (!state.answer || !current())
316
+ return undefined;
317
+ const present = this.entryPresent;
318
+ const next = advanceSurface(this.unsaved ?? state.surfaces[this.options.surface], state.answer, state.entry ?? (present ? 'wanted' : undefined));
319
+ if (!next.announce && !next.notice)
320
+ return undefined;
321
+ await this.save(next.surface, disk => { disk.surfaces[this.options.surface] = next.surface; return disk; });
322
+ return { ...next, ...(state.answer.promotionId ? { promotionId: state.answer.promotionId } : {}) };
323
+ }
324
+ this.signedIn = true;
325
+ this.answeredAt = this.now();
326
+ const answer = result.answer;
327
+ this.answer = answer;
328
+ if (answer.enabled) {
329
+ try {
330
+ await this.options.applyEntry(answer);
331
+ }
332
+ catch { /* the entry stays as it was */ }
333
+ if (!current())
334
+ return undefined;
335
+ }
336
+ const present = await this.present();
337
+ if (!current())
338
+ return undefined;
339
+ this.entryPresent = present;
340
+ // Decided against the state as it is now, after the entry was applied: a removal or an add recorded while
341
+ // the check was out is the one that counts, and neither is written over.
342
+ let next;
343
+ const decide = (disk) => {
344
+ // An entry already in the config with no decision recorded (a copied config, say) is the user's: wanted.
345
+ const entry = disk.entry ?? (present ? 'wanted' : undefined);
346
+ next = advanceSurface(this.unsaved ?? disk.surfaces[this.options.surface], answer, entry);
347
+ return entry;
348
+ };
349
+ // The write fills in a decision only where the file has none (absent -> wanted). updateHostedState holds the
350
+ // cross-process lock from its read to its write, so a decision another process records cannot fall in between.
351
+ await this.save(() => next?.surface, disk => {
352
+ const entry = decide(disk);
353
+ if (disk.entry === undefined && entry !== undefined)
354
+ disk.entry = entry;
355
+ disk.answer = answer;
356
+ disk.surfaces[this.options.surface] = next.surface;
357
+ return disk;
358
+ });
359
+ // The state could not be read or locked this round (busy for a moment): nothing was written and nothing is shown; the
360
+ // answer stays in memory and the next check decides the messages against the file as it is then.
361
+ if (!next)
362
+ return undefined;
363
+ const decided = next;
364
+ return { ...decided, ...(answer.promotionId ? { promotionId: answer.promotionId } : {}) };
365
+ }
366
+ /** Writes the state through the shared queue; while it cannot be written, what was shown is remembered here. */
367
+ async save(shown, change) {
368
+ const surface = () => typeof shown === 'function' ? shown() : shown;
369
+ try {
370
+ // Undefined: the lock could not be had in time, so this round's write is skipped like a failed one.
371
+ if (await updateHostedState(this.home, change) === undefined)
372
+ throw new Error('state busy');
373
+ this.unsaved = undefined;
374
+ }
375
+ catch {
376
+ this.unsaved = surface() ?? this.unsaved;
377
+ }
378
+ }
379
+ messages(next) {
380
+ if (next.announce && next.promotionId) {
381
+ const announcement = { promotionId: next.promotionId, offered: this.offered() };
382
+ this.fire(() => this.options.onAnnounce(announcement));
383
+ }
384
+ if (next.notice)
385
+ this.fire(() => this.options.onNotice());
386
+ }
387
+ fire(callback) {
388
+ try {
389
+ callback();
390
+ }
391
+ catch { /* a client callback never breaks the monitor */ }
392
+ }
393
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The ways the announcement is worded; one is picked at random each time it is shown. Each is one short
3
+ * sentence or two that fits the terminal's bubble on a narrow window, and none names a model.
4
+ */
5
+ export declare const ANDORRA_ANNOUNCEMENTS: readonly ["New Andorra model is available.", "A new Andorra model just landed.", "Fresh Andorra model, still warm.", "Psst. Andorra has a new model.", "A new Andorra model has entered the chat.", "New Andorra model. No assembly required.", "New Andorra model. Your backlog looks nervous.", "A new Andorra model is eager to meet your bugs.", "New Andorra model. It already read the docs.", "New Andorra model. No opinion on tabs or spaces."];
6
+ /** One of the announcement's wordings, picked with `random` (a number in [0, 1), as Math.random gives). */
7
+ export declare function andorraAnnouncement(random?: () => number): string;
8
+ /** The second line of the announcement while Andorra is listed but not used yet: where to choose it. */
9
+ export declare const ANDORRA_ADD_HINT = "Choose Andorra in /model to use it.";
10
+ /** Said when the model the user picked is not served by the entry that was just saved (the offer changed meanwhile). */
11
+ export declare const ANDORRA_MODEL_GONE = "That model is no longer available.";
12
+ /** The last line of the bubble, in two parts so the terminal can draw the tail as part of the box. */
13
+ export declare const ANDORRA_BUBBLE_TAIL = " \u2570 ";
14
+ export declare const ANDORRA_BUBBLE_SPEAKER = "Andorra";
15
+ /** Short lines of text in a rounded box with a tail naming Andorra as the speaker. */
16
+ export declare function speechBubble(...lines: string[]): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The ways the announcement is worded; one is picked at random each time it is shown. Each is one short
3
+ * sentence or two that fits the terminal's bubble on a narrow window, and none names a model.
4
+ */
5
+ export const ANDORRA_ANNOUNCEMENTS = [
6
+ 'New Andorra model is available.',
7
+ 'A new Andorra model just landed.',
8
+ 'Fresh Andorra model, still warm.',
9
+ 'Psst. Andorra has a new model.',
10
+ 'A new Andorra model has entered the chat.',
11
+ 'New Andorra model. No assembly required.',
12
+ 'New Andorra model. Your backlog looks nervous.',
13
+ 'A new Andorra model is eager to meet your bugs.',
14
+ 'New Andorra model. It already read the docs.',
15
+ 'New Andorra model. No opinion on tabs or spaces.',
16
+ ];
17
+ /** One of the announcement's wordings, picked with `random` (a number in [0, 1), as Math.random gives). */
18
+ export function andorraAnnouncement(random = Math.random) {
19
+ const index = Math.floor(random() * ANDORRA_ANNOUNCEMENTS.length);
20
+ return ANDORRA_ANNOUNCEMENTS[Math.min(ANDORRA_ANNOUNCEMENTS.length - 1, Math.max(0, index))];
21
+ }
22
+ /** The second line of the announcement while Andorra is listed but not used yet: where to choose it. */
23
+ export const ANDORRA_ADD_HINT = 'Choose Andorra in /model to use it.';
24
+ /** Said when the model the user picked is not served by the entry that was just saved (the offer changed meanwhile). */
25
+ export const ANDORRA_MODEL_GONE = 'That model is no longer available.';
26
+ /** The last line of the bubble, in two parts so the terminal can draw the tail as part of the box. */
27
+ export const ANDORRA_BUBBLE_TAIL = ' ╰ ';
28
+ export const ANDORRA_BUBBLE_SPEAKER = 'Andorra';
29
+ /** Short lines of text in a rounded box with a tail naming Andorra as the speaker. */
30
+ export function speechBubble(...lines) {
31
+ const width = Math.max(...lines.map(line => [...line].length));
32
+ return [
33
+ `╭${'─'.repeat(width + 2)}╮`,
34
+ ...lines.map(line => `│ ${line}${' '.repeat(width - [...line].length)} │`),
35
+ `╰─╮${'─'.repeat(width)}╯`,
36
+ ANDORRA_BUBBLE_TAIL + ANDORRA_BUBBLE_SPEAKER,
37
+ ].join('\n');
38
+ }
@@ -0,0 +1,58 @@
1
+ import { type Config } from '../config.js';
2
+ import { type AndorraEntryMode } from './entry.js';
3
+ import type { HostedAnswer } from './hosted.js';
4
+ import { type AndorraAvailability } from './state.js';
5
+ /**
6
+ * How a hosted answer may change the saved config right now. Read it inside the client's serialized config
7
+ * write, so a removal or an add that finished just before is the one that counts.
8
+ */
9
+ export declare function andorraEntryMode(home: string): Promise<AndorraEntryMode>;
10
+ /**
11
+ * Applies a hosted answer to the saved config and returns the config it saved, or undefined when there was nothing
12
+ * to write. The user's decision is read inside the cross-process config lock, so a removal another process
13
+ * recorded just before (it records first, then saves) is the one that counts and the entry is not created again.
14
+ */
15
+ export declare function saveAndorraAnswer(directory: string, answer: HostedAnswer): Promise<Config | undefined>;
16
+ export interface AddAndorraResult {
17
+ added: boolean;
18
+ /** Why nothing was added; with `modelServed: false`, why nothing was selected. */
19
+ message?: string;
20
+ /** The saved entry's provider id, when added. */
21
+ id?: string;
22
+ /**
23
+ * False when the caller named a model and the entry that was saved does not serve it (the offer changed between
24
+ * the menu being drawn and the pick): the entry is saved, nothing is selected, and `message` says so.
25
+ */
26
+ modelServed?: false;
27
+ }
28
+ export interface AddAndorraOptions {
29
+ home: string;
30
+ /** The client's monitor: the answer on hand, a way to ask again, and the sentence to show when there is none. */
31
+ monitor: {
32
+ enabledAnswer(): HostedAnswer | undefined;
33
+ answeredRecently(): boolean;
34
+ check(cause: 'add'): Promise<AndorraAvailability>;
35
+ availability(): AndorraAvailability;
36
+ };
37
+ /** Runs `update` against the saved config and saves what it returns; undefined means there is nothing to write. */
38
+ change(update: (current: Config) => Config | undefined): Promise<void>;
39
+ /**
40
+ * The user picked Andorra to use it: the entry becomes the selected provider, on `model` when one is named (on
41
+ * the entry's own otherwise). Saving and selecting are one config write. A named model the saved entry does not
42
+ * serve is not selected: the entry is still saved and the result says `modelServed: false`.
43
+ */
44
+ select?: {
45
+ model?: string;
46
+ };
47
+ /** The model the user picked, when the caller selects it itself afterwards: checked against the entry that is saved. */
48
+ model?: string;
49
+ /** The client's queue of config writes, when it has one: the save and the recorded decision then happen as one step. */
50
+ serialize?<T>(body: () => Promise<T>): Promise<T>;
51
+ }
52
+ /**
53
+ * Adds the Andorra provider because the user asked for it: first in the list, the selection untouched (a config
54
+ * with no providers selects it), and the user's decision recorded as `wanted`. Adding it twice changes nothing.
55
+ * Without an answer received in the last 30 seconds it asks once first; when Andorra is off, unreachable or the user is signed out,
56
+ * nothing is added and the plain sentence is returned.
57
+ */
58
+ export declare function addAndorraEntry(options: AddAndorraOptions): Promise<AddAndorraResult>;