@andorra-labs/code 0.1.15 → 0.1.17

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 (242) hide show
  1. package/dist/src/acp-agent.d.ts +6 -0
  2. package/dist/src/acp-agent.js +15 -4
  3. package/dist/src/agent-definitions.js +29 -6
  4. package/dist/src/agent-execution.js +15 -10
  5. package/dist/src/agent-mcp-catalog.js +1 -0
  6. package/dist/src/agent-mcp.d.ts +4 -1
  7. package/dist/src/agent-mcp.js +46 -10
  8. package/dist/src/andorra/entry.d.ts +10 -0
  9. package/dist/src/andorra/entry.js +18 -4
  10. package/dist/src/andorra/hosted.d.ts +2 -1
  11. package/dist/src/andorra/hosted.js +2 -1
  12. package/dist/src/andorra/notices.d.ts +5 -0
  13. package/dist/src/andorra/notices.js +7 -0
  14. package/dist/src/andorra/state.d.ts +3 -2
  15. package/dist/src/andorra/state.js +4 -4
  16. package/dist/src/andorra/terminal.js +7 -2
  17. package/dist/src/anthropic-credentials.js +2 -0
  18. package/dist/src/app-server/error.d.ts +5 -0
  19. package/dist/src/app-server/error.js +7 -0
  20. package/dist/src/app-server/protocol.d.ts +22 -44
  21. package/dist/src/app-server/protocol.js +5 -1
  22. package/dist/src/app-server/workspace.d.ts +89 -0
  23. package/dist/src/app-server/workspace.js +457 -11
  24. package/dist/src/app-server.d.ts +465 -32
  25. package/dist/src/app-server.js +3308 -517
  26. package/dist/src/auth/deployment.js +2 -2
  27. package/dist/src/bridge/cloud.d.ts +27 -0
  28. package/dist/src/bridge/cloud.js +187 -0
  29. package/dist/src/bridge/command.d.ts +30 -0
  30. package/dist/src/bridge/command.js +347 -0
  31. package/dist/src/bridge/control.d.ts +68 -0
  32. package/dist/src/bridge/control.js +233 -0
  33. package/dist/src/bridge/engines.d.ts +90 -0
  34. package/dist/src/bridge/engines.js +601 -0
  35. package/dist/src/bridge/host-ops.d.ts +9 -0
  36. package/dist/src/bridge/host-ops.js +129 -0
  37. package/dist/src/bridge/host.d.ts +47 -0
  38. package/dist/src/bridge/host.js +540 -0
  39. package/dist/src/bridge/link.d.ts +38 -0
  40. package/dist/src/bridge/link.js +508 -0
  41. package/dist/src/bridge/login-link.d.ts +29 -0
  42. package/dist/src/bridge/login-link.js +54 -0
  43. package/dist/src/bridge/protocol.d.ts +136 -0
  44. package/dist/src/bridge/protocol.js +11 -0
  45. package/dist/src/bridge/store.d.ts +12 -0
  46. package/dist/src/bridge/store.js +61 -0
  47. package/dist/src/bridge/wording.d.ts +6 -0
  48. package/dist/src/bridge/wording.js +10 -0
  49. package/dist/src/browser-runner.js +1 -0
  50. package/dist/src/browser-server.js +7 -1
  51. package/dist/src/browser-ui/style.css +3 -3
  52. package/dist/src/browser-ui/tokens.css +28 -17
  53. package/dist/src/change-authors.d.ts +41 -0
  54. package/dist/src/change-authors.js +146 -0
  55. package/dist/src/claude-provider.js +3 -1
  56. package/dist/src/cli.js +202 -38
  57. package/dist/src/codex-errors.js +4 -1
  58. package/dist/src/coding-tools.js +15 -15
  59. package/dist/src/command-screens.d.ts +6 -0
  60. package/dist/src/command-screens.js +19 -14
  61. package/dist/src/commands.d.ts +14 -1
  62. package/dist/src/compaction-phrases.d.ts +4 -0
  63. package/dist/src/compaction-phrases.js +20 -0
  64. package/dist/src/completion.js +82 -5
  65. package/dist/src/config.d.ts +71 -3
  66. package/dist/src/config.js +202 -77
  67. package/dist/src/context-compaction.js +2 -1
  68. package/dist/src/deadline.js +13 -1
  69. package/dist/src/decision/DecisionManager.js +3 -2
  70. package/dist/src/decision/checks.js +1 -1
  71. package/dist/src/decision/requestPhrases.d.ts +4 -0
  72. package/dist/src/decision/requestPhrases.js +22 -0
  73. package/dist/src/default-graph.js +1 -1
  74. package/dist/src/file-diff.d.ts +4 -0
  75. package/dist/src/file-diff.js +2 -1
  76. package/dist/src/github-app/agent-writes.d.ts +102 -0
  77. package/dist/src/github-app/agent-writes.js +320 -0
  78. package/dist/src/github-app/client.d.ts +349 -0
  79. package/dist/src/github-app/client.js +810 -0
  80. package/dist/src/github-app/event-source.d.ts +208 -0
  81. package/dist/src/github-app/event-source.js +684 -0
  82. package/dist/src/github-app/metrics.d.ts +32 -0
  83. package/dist/src/github-app/metrics.js +49 -0
  84. package/dist/src/github-app/review-loop.d.ts +274 -0
  85. package/dist/src/github-app/review-loop.js +1177 -0
  86. package/dist/src/github-app/review-node.d.ts +81 -0
  87. package/dist/src/github-app/review-node.js +205 -0
  88. package/dist/src/github-app/review-post.d.ts +73 -0
  89. package/dist/src/github-app/review-post.js +139 -0
  90. package/dist/src/github-app/review-text.d.ts +107 -0
  91. package/dist/src/github-app/review-text.js +1133 -0
  92. package/dist/src/github-app/review-threads.d.ts +47 -0
  93. package/dist/src/github-app/review-threads.js +107 -0
  94. package/dist/src/github-app/reviewer.d.ts +121 -0
  95. package/dist/src/github-app/reviewer.js +598 -0
  96. package/dist/src/github-app/store.d.ts +59 -0
  97. package/dist/src/github-app/store.js +148 -0
  98. package/dist/src/github-app/triggers.d.ts +141 -0
  99. package/dist/src/github-app/triggers.js +441 -0
  100. package/dist/src/github-inbox.d.ts +55 -0
  101. package/dist/src/github-inbox.js +153 -0
  102. package/dist/src/github-names.d.ts +8 -0
  103. package/dist/src/github-names.js +8 -0
  104. package/dist/src/glob-search.d.ts +61 -0
  105. package/dist/src/glob-search.js +180 -0
  106. package/dist/src/graph-health.js +13 -4
  107. package/dist/src/graph-manager-chat.js +1 -1
  108. package/dist/src/graph-preview.d.ts +46 -0
  109. package/dist/src/graph-preview.js +55 -0
  110. package/dist/src/graph-provider-portability.js +34 -11
  111. package/dist/src/graph-quota.d.ts +29 -2
  112. package/dist/src/graph-quota.js +68 -10
  113. package/dist/src/graph-runner.js +88 -10
  114. package/dist/src/graph-server.d.ts +1 -1
  115. package/dist/src/graph-server.js +11 -9
  116. package/dist/src/graph-sync.js +3 -3
  117. package/dist/src/graph-ui/app.js +201 -40
  118. package/dist/src/graph-ui/controls.css +1 -0
  119. package/dist/src/graph-ui/embed.js +2 -2
  120. package/dist/src/graph-ui/icons.js +3 -1
  121. package/dist/src/graph-ui/index.html +1 -1
  122. package/dist/src/graph-ui/manager.css +1 -1
  123. package/dist/src/graph-ui/manager.js +2 -2
  124. package/dist/src/graph-ui/sidebar.js +30 -0
  125. package/dist/src/graph-ui/studio-canvas.js +26 -13
  126. package/dist/src/graph-ui/studio.css +15 -7
  127. package/dist/src/graph-ui/studio.js +26 -5
  128. package/dist/src/graph-ui/style.css +77 -45
  129. package/dist/src/graph-ui/theme.js +3 -36
  130. package/dist/src/graph-ui/tokens.css +28 -20
  131. package/dist/src/graphs.d.ts +34 -1
  132. package/dist/src/graphs.js +162 -17
  133. package/dist/src/image-input.d.ts +16 -0
  134. package/dist/src/image-input.js +41 -0
  135. package/dist/src/membership.d.ts +30 -1
  136. package/dist/src/membership.js +48 -8
  137. package/dist/src/model-health-cache.js +1 -1
  138. package/dist/src/model-metadata.d.ts +7 -1
  139. package/dist/src/model-metadata.js +39 -17
  140. package/dist/src/model-relay/local.d.ts +116 -0
  141. package/dist/src/model-relay/local.js +468 -0
  142. package/dist/src/model-relay/remote.d.ts +129 -0
  143. package/dist/src/model-relay/remote.js +252 -0
  144. package/dist/src/model-relay/runs.d.ts +34 -0
  145. package/dist/src/model-relay/runs.js +146 -0
  146. package/dist/src/model-relay/wire.d.ts +5 -0
  147. package/dist/src/model-relay/wire.js +5 -0
  148. package/dist/src/plan-pass.d.ts +59 -0
  149. package/dist/src/plan-pass.js +165 -0
  150. package/dist/src/project-registry.d.ts +21 -0
  151. package/dist/src/project-registry.js +74 -0
  152. package/dist/src/provider-engine.js +3 -0
  153. package/dist/src/provider-import.d.ts +0 -12
  154. package/dist/src/provider-import.js +7 -195
  155. package/dist/src/providers.d.ts +40 -2
  156. package/dist/src/providers.js +93 -23
  157. package/dist/src/pull-request-checks.d.ts +26 -0
  158. package/dist/src/pull-request-checks.js +56 -0
  159. package/dist/src/pull-request-conversation.d.ts +134 -0
  160. package/dist/src/pull-request-conversation.js +221 -0
  161. package/dist/src/pull-request-create.d.ts +175 -0
  162. package/dist/src/pull-request-create.js +392 -0
  163. package/dist/src/pull-request-details.d.ts +242 -0
  164. package/dist/src/pull-request-details.js +614 -0
  165. package/dist/src/pull-request-edit.d.ts +23 -0
  166. package/dist/src/pull-request-edit.js +91 -0
  167. package/dist/src/pull-request-logs.d.ts +87 -0
  168. package/dist/src/pull-request-logs.js +183 -0
  169. package/dist/src/pull-request-merge.d.ts +112 -0
  170. package/dist/src/pull-request-merge.js +258 -0
  171. package/dist/src/pull-request-review.d.ts +137 -0
  172. package/dist/src/pull-request-review.js +401 -0
  173. package/dist/src/pull-requests.d.ts +369 -8
  174. package/dist/src/pull-requests.js +524 -55
  175. package/dist/src/react-runtime.js +38 -5
  176. package/dist/src/remote/engine-pool.d.ts +88 -4
  177. package/dist/src/remote/engine-pool.js +379 -90
  178. package/dist/src/remote/roots.d.ts +19 -0
  179. package/dist/src/remote/roots.js +45 -7
  180. package/dist/src/remote/types.d.ts +0 -44
  181. package/dist/src/run-control.d.ts +17 -0
  182. package/dist/src/run-control.js +47 -0
  183. package/dist/src/run-progress.d.ts +10 -0
  184. package/dist/src/run-progress.js +122 -0
  185. package/dist/src/run-records.d.ts +7 -2
  186. package/dist/src/run-records.js +71 -6
  187. package/dist/src/runtime.d.ts +9 -1
  188. package/dist/src/runtime.js +24 -4
  189. package/dist/src/session-changes.d.ts +35 -0
  190. package/dist/src/session-changes.js +194 -6
  191. package/dist/src/session-monitor.js +2 -1
  192. package/dist/src/session-reaper.d.ts +1 -1
  193. package/dist/src/session-reaper.js +6 -1
  194. package/dist/src/session-summary.d.ts +2 -1
  195. package/dist/src/session-summary.js +2 -1
  196. package/dist/src/sessions.d.ts +11 -1
  197. package/dist/src/sessions.js +17 -4
  198. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  199. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  200. package/dist/src/skills/bundled/provenance.json +2 -2
  201. package/dist/src/skills/runtime-skills.js +1 -1
  202. package/dist/src/subagent-run.js +1 -0
  203. package/dist/src/telemetry/capture-core.d.ts +17 -0
  204. package/dist/src/telemetry/capture-core.js +59 -1
  205. package/dist/src/telemetry/classify.d.ts +3 -1
  206. package/dist/src/telemetry/classify.js +37 -0
  207. package/dist/src/telemetry/emitter.d.ts +17 -0
  208. package/dist/src/telemetry/emitter.js +76 -5
  209. package/dist/src/telemetry/schema.d.ts +47 -2
  210. package/dist/src/telemetry/schema.js +120 -5
  211. package/dist/src/telemetry/surface.d.ts +3 -1
  212. package/dist/src/telemetry/surface.js +4 -1
  213. package/dist/src/telemetry/uploader.d.ts +6 -1
  214. package/dist/src/telemetry/uploader.js +22 -3
  215. package/dist/src/terminal-ui.d.ts +1 -0
  216. package/dist/src/terminal-ui.js +10 -3
  217. package/dist/src/test-edit-guard.d.ts +7 -0
  218. package/dist/src/test-edit-guard.js +49 -1
  219. package/dist/src/timers.d.ts +2 -0
  220. package/dist/src/tools.js +59 -9
  221. package/dist/src/transcript.js +8 -2
  222. package/dist/src/types.d.ts +7 -0
  223. package/dist/src/usage-analytics.js +18 -10
  224. package/package.json +6 -1
  225. package/dist/src/remote/cert.d.ts +0 -11
  226. package/dist/src/remote/cert.js +0 -87
  227. package/dist/src/remote/client.d.ts +0 -119
  228. package/dist/src/remote/client.js +0 -544
  229. package/dist/src/remote/command.d.ts +0 -4
  230. package/dist/src/remote/command.js +0 -194
  231. package/dist/src/remote/errors.d.ts +0 -11
  232. package/dist/src/remote/errors.js +0 -14
  233. package/dist/src/remote/network.d.ts +0 -22
  234. package/dist/src/remote/network.js +0 -102
  235. package/dist/src/remote/pairing.d.ts +0 -63
  236. package/dist/src/remote/pairing.js +0 -299
  237. package/dist/src/remote/pem.d.ts +0 -2
  238. package/dist/src/remote/pem.js +0 -7
  239. package/dist/src/remote/serve.d.ts +0 -68
  240. package/dist/src/remote/serve.js +0 -244
  241. package/dist/src/remote/server.d.ts +0 -21
  242. package/dist/src/remote/server.js +0 -406
@@ -0,0 +1,468 @@
1
+ import { configuredModelSnapshot } from '../model-metadata.js';
2
+ import { ANDORRA_SESSION_ID, findProviderById, ProviderRequestError, REASONING_EFFORTS, RetryableProviderError, supportsReasoningEffort } from '../providers.js';
3
+ import { redactSecrets } from '../memory/redaction.js';
4
+ import { RELAY_DELTA_LIMIT_BYTES, RELAY_FAILURE_CODE, RELAY_PAYLOAD_LIMIT_BYTES } from './remote.js';
5
+ /** At most this many relayed requests of one machine are in hand at once, generating or waiting to be delivered; another is left for a later announce. */
6
+ export const LOCAL_RELAY_CONCURRENCY = 5;
7
+ /** While a request is generating, the machine hears that it is alive this often, so it keeps the claim. */
8
+ export const LOCAL_RELAY_ALIVE_MS = 15_000;
9
+ /** Reasoning deltas are sent at most once per this interval. */
10
+ export const LOCAL_RELAY_REASONING_BATCH_MS = 100;
11
+ /** A finished result that could not be sent is tried again this often... */
12
+ export const LOCAL_RELAY_RESULT_RETRY_MS = 5_000;
13
+ /** ...and kept for this long, waiting for the link or for the machine to announce the request again. */
14
+ export const LOCAL_RELAY_RESULT_HOLD_MS = 600_000;
15
+ /**
16
+ * A request this computer ignored because it does not offer the provider or model asked for, still announced unclaimed
17
+ * this long after, is claimed and declined: another desktop of the account that offers it had that long to take it.
18
+ */
19
+ export const LOCAL_RELAY_DECLINE_MS = 60_000;
20
+ /** An ignored request not announced again for this long is forgotten. */
21
+ const IGNORED_FORGET_MS = 120_000;
22
+ const IGNORED_LOG_MS = 60_000;
23
+ /** At most this many announces of runs not known here yet are kept for when they become known. */
24
+ const UNKNOWN_RUN_LIMIT = 256;
25
+ const UNREADABLE = 'The request could not be read.';
26
+ const MAX_ID = 128;
27
+ const MAX_MODEL = 500;
28
+ const CONTEXT_FIELDS = ['runId', 'nodeId', 'providerId', 'subagentId', 'invocationId'];
29
+ /** The failure codes of a call that did not reach the machine because the link is down; anything else is the machine's answer. */
30
+ const LINK_DOWN = new Set(['network', 'cancelled']);
31
+ /**
32
+ * The models a provider offers a linked machine: its default and its listed models. The relay block names exactly
33
+ * these, and a request for any other model is not answered.
34
+ */
35
+ export function relayedModelIds(provider) {
36
+ const usable = (model) => typeof model === 'string' && !!model.trim() && model.length <= MAX_MODEL && !['__proto__', 'constructor', 'prototype'].includes(model);
37
+ return [...new Set([provider.model, ...(provider.models ?? [])])].filter(usable).slice(0, 1_000);
38
+ }
39
+ function isRecord(value) {
40
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
41
+ }
42
+ function boundedString(value, limit) {
43
+ return typeof value === 'string' && value.length > 0 && value.length <= limit;
44
+ }
45
+ /** The request a machine announced, or undefined when any part of it is not what a relay announce is. */
46
+ function readAnnounce(data) {
47
+ const { id, runId, provider, model, bytes } = data;
48
+ if (!boundedString(id, MAX_ID) || !boundedString(runId, MAX_ID) || typeof provider !== 'string' || !/^[\w-]{1,128}$/.test(provider))
49
+ return undefined;
50
+ if (!boundedString(model, MAX_MODEL) || typeof bytes !== 'number' || !Number.isSafeInteger(bytes) || bytes < 0)
51
+ return undefined;
52
+ return { id, runId, provider, model, bytes };
53
+ }
54
+ /** The payload a claim answered with, when it is the announced request's: undefined when it is not a relay payload. */
55
+ function readPayload(value, model) {
56
+ if (!isRecord(value) || value.model !== model || !Array.isArray(value.messages) || !Array.isArray(value.tools))
57
+ return undefined;
58
+ return value;
59
+ }
60
+ /** The known fields of the run's request context, as strings; anything else the machine put there is dropped. */
61
+ function readContext(value) {
62
+ if (!isRecord(value))
63
+ return undefined;
64
+ const context = {};
65
+ for (const field of CONTEXT_FIELDS)
66
+ if (boundedString(value[field], 256))
67
+ context[field] = value[field];
68
+ return Object.keys(context).length ? context : undefined;
69
+ }
70
+ /** A failure's message as the machine may show it: no secret, no address of this computer's provider, and bounded. */
71
+ function shownMessage(error) {
72
+ const raw = redactSecrets(error instanceof Error ? error.message : String(error)).text;
73
+ const cleaned = raw.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s'"<>)]+/gi, 'your provider').trim().slice(0, 4_000);
74
+ return cleaned || 'The model request failed on your computer.';
75
+ }
76
+ function failureOf(error) {
77
+ const message = shownMessage(error);
78
+ if (!(error instanceof ProviderRequestError))
79
+ return { message, kind: 'other' };
80
+ const code = typeof error.telemetryCode === 'string' && RELAY_FAILURE_CODE.test(error.telemetryCode) ? error.telemetryCode : undefined;
81
+ return {
82
+ message, kind: error instanceof RetryableProviderError ? 'retryable' : 'provider-request',
83
+ ...(error.contextOverflow ? { contextOverflow: true } : {}),
84
+ ...(code === undefined ? {} : { code }),
85
+ };
86
+ }
87
+ /** The longest prefix of `text` whose UTF-8 form fits in RELAY_DELTA_LIMIT_BYTES, cut on a whole character. */
88
+ function deltaPrefix(text) {
89
+ if (Buffer.byteLength(text) <= RELAY_DELTA_LIMIT_BYTES)
90
+ return text;
91
+ const read = new TextEncoder().encodeInto(text, new Uint8Array(RELAY_DELTA_LIMIT_BYTES)).read;
92
+ return text.slice(0, read);
93
+ }
94
+ function retryOf(retry) {
95
+ return {
96
+ retry: retry.retry, maxRetries: retry.maxRetries, delayMs: retry.delayMs, reason: shownMessage(retry.reason),
97
+ ...(retry.quiet === undefined ? {} : { quiet: retry.quiet }),
98
+ ...(retry.cause === undefined ? {} : { cause: retry.cause }),
99
+ ...(retry.code === undefined ? {} : { code: retry.code }),
100
+ ...(typeof retry.unparsedReply === 'string' && Buffer.byteLength(retry.unparsedReply) <= RELAY_DELTA_LIMIT_BYTES ? { unparsedReply: retry.unparsedReply } : {}),
101
+ };
102
+ }
103
+ /**
104
+ * The desktop engine's half of the model relay: a linked machine's `model.relay.request` is claimed, generated with
105
+ * this computer's own provider, and answered with `model.relay.result`. Only machines the user allowed are answered,
106
+ * only for runs this computer started or resumed there, and nothing but the provider id and the model call itself
107
+ * comes from the machine. The announce carries no payload: it arrives in the answer to the claim.
108
+ */
109
+ export class LocalModelRelay {
110
+ deps;
111
+ work = new Map();
112
+ ignoredLogged = new Map();
113
+ /**
114
+ * Requests this computer ignored because it does not offer their provider or model, by machine and id: when it
115
+ * first ignored each, and when it last saw it announced.
116
+ */
117
+ declining = new Map();
118
+ /** The last announce of each request ignored because its run was not known here yet, so it can be taken once it is. */
119
+ unknownRun = new Map();
120
+ closed = false;
121
+ constructor(deps) {
122
+ this.deps = deps;
123
+ }
124
+ /** Takes a `model.relay.*` frame; true when the frame was one (it is the engine's, not the window's). */
125
+ handle(env, frame) {
126
+ if (!frame.event.startsWith('model.relay.'))
127
+ return false;
128
+ if (this.closed)
129
+ return true;
130
+ if (frame.event === 'model.relay.request')
131
+ this.onRequest(env, frame);
132
+ else if (frame.event === 'model.relay.cancel')
133
+ this.onCancel(env, frame.data);
134
+ return true;
135
+ }
136
+ /** Stops every request of `env`: its link ended for good, or it is no longer allowed. */
137
+ dropEnvironment(env) {
138
+ for (const entry of [...this.work.values()])
139
+ if (entry.env === env)
140
+ this.end(entry);
141
+ for (const [key, entry] of [...this.declining])
142
+ if (entry.env === env)
143
+ this.declining.delete(key);
144
+ for (const [key, entry] of [...this.unknownRun])
145
+ if (entry.env === env)
146
+ this.unknownRun.delete(key);
147
+ }
148
+ /**
149
+ * This computer has just started or resumed `runId` on `env`: a request of it announced before that was known is
150
+ * taken now rather than at its next announce.
151
+ */
152
+ reconsider(env, runId) {
153
+ if (this.closed)
154
+ return;
155
+ for (const [key, entry] of [...this.unknownRun]) {
156
+ if (entry.env !== env || entry.frame.data.runId !== runId)
157
+ continue;
158
+ this.unknownRun.delete(key);
159
+ this.onRequest(env, entry.frame);
160
+ }
161
+ }
162
+ /** Stops every machine's requests: the account changed. */
163
+ dropAll() {
164
+ for (const entry of [...this.work.values()])
165
+ this.end(entry);
166
+ this.declining.clear();
167
+ this.unknownRun.clear();
168
+ }
169
+ close() {
170
+ this.closed = true;
171
+ this.dropAll();
172
+ }
173
+ now() { return (this.deps.now ?? Date.now)(); }
174
+ key(env, id) { return `${env}\u0000${id}`; }
175
+ /** `env`'s requests in hand: generating, or answered and waiting to be delivered. */
176
+ inHand(env) {
177
+ let count = 0;
178
+ for (const entry of this.work.values())
179
+ if (entry.env === env)
180
+ count += 1;
181
+ return count;
182
+ }
183
+ onRequest(env, frame) {
184
+ const request = readAnnounce(frame.data);
185
+ if (!request || !boundedString(frame.engine, MAX_ID))
186
+ return;
187
+ const now = this.now();
188
+ for (const [key, entry] of [...this.declining])
189
+ if (now - entry.seen >= IGNORED_FORGET_MS)
190
+ this.declining.delete(key);
191
+ for (const [key, entry] of [...this.unknownRun])
192
+ if (now - entry.seen >= IGNORED_FORGET_MS)
193
+ this.unknownRun.delete(key);
194
+ const held = this.work.get(this.key(env, request.id));
195
+ if (held) {
196
+ // A request announced again while its answer waits to be delivered: the claim was released, so take it again.
197
+ if (held.outcome !== undefined && held.runId === request.runId && !held.sending)
198
+ void this.reclaim(held, frame.engine);
199
+ return;
200
+ }
201
+ // A payload larger than a relay request may be could not be read here: leave it for nobody to claim.
202
+ if (request.bytes > RELAY_PAYLOAD_LIMIT_BYTES)
203
+ return;
204
+ if (this.inHand(env) >= LOCAL_RELAY_CONCURRENCY)
205
+ return;
206
+ const entry = { env, engine: frame.engine, id: request.id, runId: request.runId, controller: new AbortController(), sending: false, reasoning: '' };
207
+ this.work.set(this.key(env, request.id), entry);
208
+ void this.start(entry, request, frame).catch(error => {
209
+ this.deps.log(`A model request from a linked machine could not be answered: ${shownMessage(error)}`);
210
+ this.end(entry);
211
+ });
212
+ }
213
+ onCancel(env, data) {
214
+ if (typeof data.id !== 'string')
215
+ return;
216
+ const entry = this.work.get(this.key(env, data.id));
217
+ if (entry && entry.runId === data.runId)
218
+ this.end(entry);
219
+ }
220
+ ignored(env, why) {
221
+ const now = this.now();
222
+ const last = this.ignoredLogged.get(env);
223
+ if (last !== undefined && now - last < IGNORED_LOG_MS)
224
+ return;
225
+ this.ignoredLogged.set(env, now);
226
+ this.deps.log(`Ignored a model request from linked machine ${env}: ${why}`);
227
+ }
228
+ live(entry) {
229
+ return this.work.get(this.key(entry.env, entry.id)) === entry;
230
+ }
231
+ /**
232
+ * Whether a request this computer does not offer has waited long enough for another desktop to take it. The first
233
+ * time it is seen the clock starts; every announce after that keeps it remembered.
234
+ */
235
+ declineDue(entry) {
236
+ const key = this.key(entry.env, entry.id);
237
+ const now = this.now();
238
+ const known = this.declining.get(key);
239
+ if (!known) {
240
+ this.declining.set(key, { env: entry.env, since: now, seen: now });
241
+ return false;
242
+ }
243
+ known.seen = now;
244
+ return now - known.since >= LOCAL_RELAY_DECLINE_MS;
245
+ }
246
+ async start(entry, request, frame) {
247
+ const subject = await this.deps.subject();
248
+ if (!this.live(entry))
249
+ return;
250
+ if (!await this.deps.allowed(entry.env, subject)) {
251
+ this.end(entry);
252
+ this.ignored(entry.env, 'it is not allowed to use this computer\'s models.');
253
+ return;
254
+ }
255
+ if (!this.live(entry))
256
+ return;
257
+ if (!await this.deps.startedHere(entry.env, entry.runId, subject)) {
258
+ this.end(entry);
259
+ this.rememberUnknownRun(entry.env, entry.id, frame);
260
+ this.ignored(entry.env, 'the task was not started or resumed from this computer.');
261
+ return;
262
+ }
263
+ const saved = findProviderById(await this.deps.providers(), request.provider);
264
+ if (!this.live(entry))
265
+ return;
266
+ if (!saved || !relayedModelIds(saved).includes(request.model)) {
267
+ if (this.declineDue(entry)) {
268
+ await this.decline(entry, request);
269
+ return;
270
+ }
271
+ this.end(entry);
272
+ this.ignored(entry.env, saved ? 'it asked for a model this computer does not offer it.' : 'it asked for a provider this computer does not have.');
273
+ return;
274
+ }
275
+ this.declining.delete(this.key(entry.env, entry.id));
276
+ const claim = await this.deps.send(entry.env, entry.engine, 'model.relay.claim', { id: entry.id, runId: entry.runId });
277
+ if (!this.live(entry))
278
+ return;
279
+ if (!isRecord(claim.result) || claim.result.claimed !== true) {
280
+ this.end(entry);
281
+ return;
282
+ }
283
+ entry.via = claim.via;
284
+ const payload = readPayload(claim.result.payload, request.model);
285
+ if (payload === undefined) {
286
+ // Taken, but not the request that was announced: say so, so the machine does not wait for an answer.
287
+ await this.answer(entry, { ok: false, error: { kind: 'other', message: UNREADABLE } });
288
+ return;
289
+ }
290
+ entry.aliveTimer = setInterval(() => { this.progress(entry, { kind: 'alive' }); }, LOCAL_RELAY_ALIVE_MS);
291
+ entry.aliveTimer.unref?.();
292
+ let outcome;
293
+ try {
294
+ const response = await this.generate(entry, saved, payload);
295
+ outcome = { ok: true, response };
296
+ }
297
+ catch (error) {
298
+ if (!this.live(entry) || entry.controller.signal.aborted)
299
+ return;
300
+ outcome = { ok: false, error: failureOf(error) };
301
+ }
302
+ if (!this.live(entry) || entry.controller.signal.aborted)
303
+ return;
304
+ this.finishGenerating(entry);
305
+ await this.answer(entry, outcome);
306
+ }
307
+ /** Claims a request this computer no longer offers and answers that it does not, with no model call. */
308
+ rememberUnknownRun(env, id, frame) {
309
+ const key = this.key(env, id);
310
+ this.unknownRun.delete(key);
311
+ this.unknownRun.set(key, { env, frame, seen: this.now() });
312
+ while (this.unknownRun.size > UNKNOWN_RUN_LIMIT)
313
+ this.unknownRun.delete(this.unknownRun.keys().next().value);
314
+ }
315
+ async decline(entry, request) {
316
+ this.declining.delete(this.key(entry.env, entry.id));
317
+ const claim = await this.deps.send(entry.env, entry.engine, 'model.relay.claim', { id: entry.id, runId: entry.runId });
318
+ if (!this.live(entry))
319
+ return;
320
+ // Another desktop took it meanwhile, or the run let it go: nothing to say.
321
+ if (!isRecord(claim.result) || claim.result.claimed !== true) {
322
+ this.end(entry);
323
+ return;
324
+ }
325
+ entry.via = claim.via;
326
+ const message = `Your computer no longer offers ${request.model.slice(0, 200)} on ${request.provider.slice(0, 200)}.`;
327
+ await this.answer(entry, { ok: false, error: { kind: 'provider-request', message } });
328
+ }
329
+ /** Holds `outcome` for delivery, for at most LOCAL_RELAY_RESULT_HOLD_MS, and sends it. */
330
+ async answer(entry, outcome) {
331
+ entry.outcome = outcome;
332
+ entry.expiryTimer = setTimeout(() => { this.end(entry); }, LOCAL_RELAY_RESULT_HOLD_MS);
333
+ entry.expiryTimer.unref?.();
334
+ await this.deliver(entry);
335
+ }
336
+ generate(entry, saved, payload) {
337
+ // A copy for this call, as a local run takes it: the model asked for, and the effort the run chose when this provider takes one.
338
+ const snapshot = configuredModelSnapshot(saved, payload.model);
339
+ const effort = payload.reasoningEffort;
340
+ if (typeof effort === 'string' && supportsReasoningEffort(snapshot.type) && REASONING_EFFORTS.includes(effort)) {
341
+ snapshot.reasoningEffort = effort;
342
+ }
343
+ // The session id goes to the adapter only in the form the hosted provider takes; anything else is not passed.
344
+ const sessionId = typeof payload.sessionId === 'string' && ANDORRA_SESSION_ID.test(payload.sessionId) ? payload.sessionId : undefined;
345
+ const adapter = this.deps.createAdapter(snapshot, sessionId === undefined ? {} : { sessionId });
346
+ const context = readContext(payload.context);
347
+ const request = {
348
+ model: snapshot.model, messages: payload.messages, tools: payload.tools,
349
+ ...(Number.isSafeInteger(payload.maxTokens) && payload.maxTokens > 0 ? { maxTokens: payload.maxTokens } : {}),
350
+ ...(Number.isSafeInteger(payload.mutableTail) && payload.mutableTail >= 0 ? { mutableTail: payload.mutableTail } : {}),
351
+ ...(payload.toolChoice === 'required' ? { toolChoice: 'required' } : {}),
352
+ ...(context === undefined ? {} : { context }),
353
+ signal: entry.controller.signal,
354
+ onRequest: () => { this.progress(entry, { kind: 'request' }); },
355
+ onReasoning: delta => { this.reason(entry, delta); },
356
+ onRetry: retry => { this.progress(entry, { kind: 'retry', retry: retryOf(retry) }); },
357
+ // Only the code goes to the machine, and only in the telemetry form; the adapter gives nothing else.
358
+ onRecoveredError: code => { if (typeof code === 'string' && RELAY_FAILURE_CODE.test(code))
359
+ this.progress(entry, { kind: 'recovered-error', code }); },
360
+ };
361
+ return adapter.generate(request);
362
+ }
363
+ /** Sends a progress call; one that fails (the link is down) is let go, and generation goes on. */
364
+ progress(entry, fields) {
365
+ if (!this.live(entry) || entry.outcome !== undefined)
366
+ return;
367
+ void this.deps.send(entry.env, entry.engine, 'model.relay.progress', { id: entry.id, runId: entry.runId, ...fields }, entry.via).catch(() => undefined);
368
+ }
369
+ reason(entry, delta) {
370
+ if (typeof delta !== 'string' || !delta || !this.live(entry) || entry.outcome !== undefined)
371
+ return;
372
+ entry.reasoning += delta;
373
+ this.scheduleReasoning(entry);
374
+ }
375
+ scheduleReasoning(entry) {
376
+ if (entry.reasoningTimer !== undefined || !entry.reasoning)
377
+ return;
378
+ entry.reasoningTimer = setTimeout(() => {
379
+ entry.reasoningTimer = undefined;
380
+ const delta = deltaPrefix(entry.reasoning);
381
+ entry.reasoning = entry.reasoning.slice(delta.length);
382
+ this.progress(entry, { kind: 'reasoning', delta });
383
+ this.scheduleReasoning(entry);
384
+ }, LOCAL_RELAY_REASONING_BATCH_MS);
385
+ entry.reasoningTimer.unref?.();
386
+ }
387
+ /** Generation is over: the last batched reasoning goes out first, then the timers that served it stop. */
388
+ finishGenerating(entry) {
389
+ if (entry.reasoningTimer !== undefined) {
390
+ clearTimeout(entry.reasoningTimer);
391
+ entry.reasoningTimer = undefined;
392
+ }
393
+ if (entry.reasoning) {
394
+ const delta = deltaPrefix(entry.reasoning);
395
+ entry.reasoning = '';
396
+ this.progress(entry, { kind: 'reasoning', delta });
397
+ }
398
+ if (entry.aliveTimer !== undefined) {
399
+ clearInterval(entry.aliveTimer);
400
+ entry.aliveTimer = undefined;
401
+ }
402
+ }
403
+ /**
404
+ * Sends the answer. Delivered or refused by the machine, the work is done with it, except that a refusal leaves the
405
+ * answer held for a re-announce; a link that is down keeps it and tries again every 5 s until the hold expires.
406
+ */
407
+ async deliver(entry) {
408
+ if (!this.live(entry) || entry.outcome === undefined || entry.sending)
409
+ return;
410
+ if (entry.retryTimer !== undefined) {
411
+ clearTimeout(entry.retryTimer);
412
+ entry.retryTimer = undefined;
413
+ }
414
+ entry.sending = true;
415
+ let answer;
416
+ try {
417
+ answer = await this.deps.send(entry.env, entry.engine, 'model.relay.result', { id: entry.id, runId: entry.runId, ...entry.outcome }, entry.via);
418
+ }
419
+ catch (error) {
420
+ answer = { error: { code: 'network', message: shownMessage(error) } };
421
+ }
422
+ finally {
423
+ entry.sending = false;
424
+ }
425
+ if (!this.live(entry))
426
+ return;
427
+ if (answer.error && LINK_DOWN.has(answer.error.code)) {
428
+ entry.retryTimer = setTimeout(() => { entry.retryTimer = undefined; void this.deliver(entry); }, LOCAL_RELAY_RESULT_RETRY_MS);
429
+ entry.retryTimer.unref?.();
430
+ return;
431
+ }
432
+ // Taken: done. Not taken (the claim was released while the link was down): keep it for the request's next announce.
433
+ if (isRecord(answer.result) && answer.result.ok === true)
434
+ this.end(entry);
435
+ else if (answer.error)
436
+ this.end(entry);
437
+ }
438
+ async reclaim(entry, engine) {
439
+ entry.engine = engine;
440
+ entry.sending = true;
441
+ let claim;
442
+ try {
443
+ claim = await this.deps.send(entry.env, engine, 'model.relay.claim', { id: entry.id, runId: entry.runId });
444
+ }
445
+ catch {
446
+ claim = {};
447
+ }
448
+ finally {
449
+ entry.sending = false;
450
+ }
451
+ if (!this.live(entry) || !isRecord(claim.result) || claim.result.claimed !== true)
452
+ return;
453
+ // Claimed again, perhaps through another link than the first claim: the result follows this one.
454
+ entry.via = claim.via;
455
+ await this.deliver(entry);
456
+ }
457
+ end(entry) {
458
+ if (this.live(entry))
459
+ this.work.delete(this.key(entry.env, entry.id));
460
+ entry.controller.abort();
461
+ for (const timer of [entry.reasoningTimer, entry.retryTimer, entry.expiryTimer])
462
+ if (timer !== undefined)
463
+ clearTimeout(timer);
464
+ if (entry.aliveTimer !== undefined)
465
+ clearInterval(entry.aliveTimer);
466
+ entry.reasoningTimer = entry.retryTimer = entry.expiryTimer = entry.aliveTimer = undefined;
467
+ }
468
+ }
@@ -0,0 +1,129 @@
1
+ import { type ProviderConfig } from '../providers.js';
2
+ import type { Message, ModelAdapter, ModelRequestContext, ModelResponse, ModelRetry, ToolSchema } from '../types.js';
3
+ /** One model request's JSON payload may be this large; with its envelope it stays under the relay's 16 MiB frame. */
4
+ export declare const RELAY_PAYLOAD_LIMIT_BYTES: number;
5
+ /** An unclaimed request is announced again this often, so a desktop that attaches later still sees it. */
6
+ export declare const RELAY_REANNOUNCE_MS = 5000;
7
+ /** A claim with no progress for this long is released and the request is announced again. */
8
+ export declare const RELAY_CLAIM_SILENCE_MS = 45000;
9
+ /** A request without a sign of life from a desktop for this long shows the run as awaiting-desktop. */
10
+ export declare const RELAY_AWAY_MS = 600000;
11
+ /** One reasoning delta may be this large; a longer one is cut to whole characters that fit. */
12
+ export declare const RELAY_DELTA_LIMIT_BYTES: number;
13
+ export declare const RELAY_PAYLOAD_TOO_LARGE = "This step's context is too large to send to your computer (limit 12 MiB).";
14
+ export interface RelayWire {
15
+ id: string;
16
+ runId: string;
17
+ provider: string;
18
+ request: {
19
+ model: string;
20
+ messages: Message[];
21
+ tools: ToolSchema[];
22
+ maxTokens?: number;
23
+ mutableTail?: number;
24
+ toolChoice?: 'required';
25
+ context?: ModelRequestContext;
26
+ /** The effort in force for this call (the run's or node's choice), not the provider's saved default. */
27
+ reasoningEffort?: string;
28
+ /** The run's session, for a provider that groups a session's calls; the desktop passes it on only in the form the provider takes. */
29
+ sessionId?: string;
30
+ };
31
+ }
32
+ export type RelayErrorKind = 'retryable' | 'provider-request' | 'other';
33
+ /**
34
+ * A failed model call as the desktop reports it. `contextOverflow` marks the input exceeding the model's window, as
35
+ * `ProviderRequestError.contextOverflow` does locally; `code` is the failure's telemetry code (`http_429`).
36
+ */
37
+ export interface RelayFailure {
38
+ message: string;
39
+ kind: RelayErrorKind;
40
+ contextOverflow?: true;
41
+ code?: string;
42
+ }
43
+ /** The form a relayed failure's telemetry code must have. */
44
+ export declare const RELAY_FAILURE_CODE: RegExp;
45
+ export type RelayRunState = 'awaiting-desktop' | 'running';
46
+ export interface ModelRelayDeps {
47
+ emit(event: string, data: Record<string, unknown>): void;
48
+ setRunState(runId: string, state: RelayRunState): void;
49
+ /** Holds the run's wall-time budgets; the returned function releases the hold. */
50
+ suspendBudget(runId: string): () => void;
51
+ now?: () => number;
52
+ timers?: typeof globalThis;
53
+ }
54
+ /**
55
+ * What a machine announces for a request: no payload, only what a desktop needs to decide whether to claim it. The
56
+ * payload follows once, in the answer to a successful claim.
57
+ */
58
+ export interface RelayAnnounce {
59
+ id: string;
60
+ runId: string;
61
+ provider: string;
62
+ model: string;
63
+ bytes: number;
64
+ }
65
+ /** The answer to `model.relay.claim`. */
66
+ export type RelayClaimAnswer = {
67
+ claimed: true;
68
+ payload: RelayWire['request'];
69
+ } | {
70
+ claimed: false;
71
+ };
72
+ /**
73
+ * The remote engine's half of the model relay: a relayed provider's `generate()` becomes a
74
+ * `model.relay.request` event that a desktop claims and answers with `model.relay.result`.
75
+ * A request never fails because no desktop is there; it waits, and the run shows awaiting-desktop.
76
+ */
77
+ export declare class ModelRelayBroker {
78
+ private readonly deps;
79
+ private readonly pending;
80
+ private readonly timers;
81
+ constructor(deps: ModelRelayDeps);
82
+ adapter(provider: ProviderConfig, runId: string, sessionId?: string): ModelAdapter;
83
+ private generate;
84
+ /** Takes a request for `claimant`; the payload is handed over only here, once the claim holds. */
85
+ claim(params: {
86
+ id: string;
87
+ runId: string;
88
+ claimant: string;
89
+ }): RelayClaimAnswer;
90
+ progress(params: {
91
+ id: string;
92
+ runId: string;
93
+ claimant: string;
94
+ kind: 'alive' | 'request' | 'reasoning' | 'retry' | 'recovered-error';
95
+ delta?: string;
96
+ retry?: ModelRetry;
97
+ code?: string;
98
+ }): {
99
+ ok: boolean;
100
+ };
101
+ result(params: {
102
+ id: string;
103
+ runId: string;
104
+ claimant: string;
105
+ ok: boolean;
106
+ response?: ModelResponse;
107
+ error?: RelayFailure;
108
+ }): {
109
+ ok: boolean;
110
+ };
111
+ /** Whether `runId` has a request no desktop has shown a sign of life for in RELAY_AWAY_MS. */
112
+ awaiting(runId: string): boolean;
113
+ /** Rejects every wait of `runId` as cancelled and tells the desktops to stop. */
114
+ endRun(runId: string): void;
115
+ close(): void;
116
+ private lookup;
117
+ private owned;
118
+ /**
119
+ * Announces an unclaimed request now and every RELAY_REANNOUNCE_MS, holding the run's budgets meanwhile. The
120
+ * announce carries no payload, so repeating it costs little; the payload goes once, to the claim that holds.
121
+ */
122
+ private announce;
123
+ /** (Re)starts the claimant's silence clock; when it runs out the claim is released and the request announced again. */
124
+ private listen;
125
+ /** A sign of life: restarts the away clock, and a returning desktop brings the run back to running. */
126
+ private touch;
127
+ private reportBack;
128
+ private finish;
129
+ }